INDEX PAGE
1.
Introduction to Java
2.
Installation and Setup
3.
Sample Program using Notepad
4.
How to Compile Java Application
5.
How to Run Java Application
6.
Escape Sequences
7.
Print vs. Println
8.
Comments
9.
Variables and DataTypes
10.
Eclipse
11.
Package
12.
Naming Conventions
13.
Identifier and keyword
14.
Operators
15.
Control Statements
16.
Input and Output
17.
Arrays
18.
Strings
19.
StringBuffer and StringBuilder
20.
Introduction to OOPS(Features)
21.
Classes and Object Creation
22.
Access Specifiers
23.
Constructors
24.
Methods
25.
Static Method and Static Block
26.
Instance Methods
27.
This keyword
28.
Inner Class and Anonymous Class
29.
Inheritence
30.
Super keyword
31.
Polymorphism
32.
Static Polymorphism
33.
Dynamic Polymorphism
34.
Exception Handling
35.
Type Casting
36.
Abstract Classes
37.
Interfaces
38.
Wrapper Classes
39.
Collection Framework
40.
Streams and Files
41.
Garbage Collections
42.
Threads
43.
Generic Types
1. Introduction to
Java
// To Do
2. Installation and
Setup
Step 1:- Where to download Java
Step 2:- Install JDK
1) Double click
the downloaded .exe file.
2) A License
agreement window opens just accept the agreement.
3) Now a Custom setup window opens. Click on the Change button and
select the installation folder and click on Next which will start the
installation.
4) It prompts for JRE installation click on next.
5) Now the Wizard Complete window appears which indicates the
installation of jdk has been completed. Click on finish button to exit the
installation process.
Step 3:- Setup JDK
1.
Right click on My Computer icon and click on
system properties
2.
Then click on advanced tab and environment
variables.
3.
Now select the path in System
variables and click 'Edit' button and enter the variable value
(If you
install Java into a different directory, you may need to change the directory)
4.
Now setup the JAVA_HOME variable.
5.
clicking on "New" button and
give variable name as "JAVA_HOME" and variable value as your jdk installation folder
Step 4:-
Check for Successful installation
Go to the command prompt and type javac and hit enter. You should
get the below screen
Prevent Errors like --> 'javac' is not recognized as an
internal or external command
3. Sample Program using Notepad
Here we will learn to write first Java program. As usual first
Java program would be “Hello World”. But we will change it to “Hello Vidvaan!”.
If everything till now is configured properly then we can start
writting first application. Open any editor and Write below code.
1.
public class
FirstProgramme {
2.
public static void
main(String args[]) {
3.
System.out.println("Hello
Vidvaan!");
4.
}
5.
}
This class contains public static and void keywords. These are
predefined words in java which carries a specific meaning.
public
keyword specifies the accessibility of a class. Public means it can be accessed
from any where
static
keyword indicates that this method can be invoked simply by using the
name of the class without creating any object for that class.
void
keyword specifies that this method will not return any type of data.
main()
method is the main entry point of the program, to start execution. First of all
JVM calls the main method of a class and start execution . JVM (Java
Virtual Machine) is responsible for running java programs.
args is
a string array that takes values from java command line. It's index starts from
'0'. We can access values by writing args[0], args[1] etc.
println()
function prints the output on the screen.
Once finished edition save the file with name “FirstProgramme.java“.
Note name of the file should be same as given as it is public class. Once file
saved open the command prompt and change directory where file is saved with cd
command.
4.
How to Compile Java Application
Fiire “JAVAC” command to compile the java code as below.
1.
D:\>cd vidvaan
2.
D:vidvaan>javac FirstProgramme.java
3.
C:vidvaan>
As java file is compiled properly compiler must have created a
class file for the java source file in same location or other depending on
package declaration. As there is no package declaration in given code so .class
file will be create in same folder as java file.
5.
How to Run Java Application
As java file is compiled with “JAVAC” command. We can now run the
application. To run above program. Fire “JAVA” command as given below.
1.
C:vidvaan>java FirstProgramme
2.
Hello Vidvaan
3.
C:vidvaan>
6.
Escape Sequences
String literals are contained in quotation marks. So how if you
want to display a quotation mark inside a string literal or how if you want to
break the string literal across lines which is not possible.
So you have to make use of escape sequences to represent
special characters.
Below are the sequences
Sequences
|
Description
|
\t
|
Tab character
|
\n
|
New line character
|
\”
|
Quotation Mark
|
\\
|
Backslash Character
|
Consider the following statements
Example1:
System.out.println("What
\"characters\" does this \\ print?");
If you execute the above statement, you would get the
following output:
What "characters" does this \ print?
Example2:
System.out.println("This\nproduces 3
lines\nof output.");
If you execute it,
you will get the following output:
This
produces 3 lines
of output.
7.
Print vs Println
println command produces the output on the current line and then
moves the cursor to the beginning of the new line.
Print command produces the output on the current line and the
cursor stays in the same line
Thus the series of print statements will generate the output on
the same line. Only println will print the outputs on different lines.
Example:
System.out.println(“One”);
System.out.print(“Two”);
System.out.print(“Three”);
If you execute it, you will get the following output:
One
TwoThree
8.
Comments
Comments are the text that programmers include in a
program to explain their code. The compiler will ignore the comments.
Single Line Comments: These comments are used for making a single line as a comment.
These comments start with //. After this double slash whatever is written till
the end of the line is taken as the comment. For example
//This is my single line comment
Multiline Comments: These comments are used for making
multiple lines as comments. These comments starts with /* and ends with */. For
example
/* This is multiline comment line 1
This is line 2 comment
This is line 3 comment*/
9. Variables and Data
Types
Variables:
Variables are nothing but a memory location to store values. This
memory location has a name and a data type i.e., type of data stored.
This means when you create
a variable you reserve some space in the memory. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals, or characters in these variables.
DataTypes:
There are two data types
1.
Primitive Data types
2.
Object/Reference Data types
Primitive Data Types:
There are eight primitive data types supported by Java.
byte:
- Byte
data type is an 8-bit signed two's complement integer.
- Minimum
value is -128 (-2^7)
- Maximum
value is 127 (inclusive)(2^7 -1)
- Default
value is 0
- Byte
data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int.
- Example:
byte a = 100 , byte b = -50
short:
- Short
data type is a 16-bit signed two's complement integer.
- Minimum
value is -32,768 (-2^15)
- Maximum
value is 32,767 (inclusive) (2^15 -1)
- Short
data type can also be used to save memory as byte data type. A short is 2
times smaller than an int
- Default
value is 0.
- Example:
short s = 10000, short r = -20000
int:
- Int
data type is a 32-bit signed two's complement integer.
- Minimum
value is - 2,147,483,648.(-2^31)
- Maximum
value is 2,147,483,647(inclusive).(2^31 -1)
- Int
is generally used as the default data type for integral values unless
there is a concern about memory.
- The
default value is 0.
- Example:
int a = 100000, int b = -200000
long:
- Long
data type is a 64-bit signed two's complement integer.
- Minimum
value is -9,223,372,036,854,775,808.(-2^63)
- Maximum
value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
- This
type is used when a wider range than int is needed.
- Default
value is 0L.
- Example:
long a = 100000L, int b = -200000L
float:
- Float
data type is a single-precision 32-bit IEEE 754 floating point.
- Float
is mainly used to save memory in large arrays of floating point numbers.
- Default
value is 0.0f.
- Float
data type is never used for precise values such as currency.
- Example:
float f1 = 234.5f
double:
- double
data type is a double-precision 64-bit IEEE 754 floating point.
- This
data type is generally used as the default data type for decimal values,
generally the default choice.
- Double
data type should never be used for precise values such as currency.
- Default
value is 0.0d.
- Example:
double d1 = 123.4
boolean:
- boolean
data type represents one bit of information.
- There
are only two possible values: true and false.
- This
data type is used for simple flags that track true/false conditions.
- Default
value is false.
- Example:
boolean one = true
char:
- char
data type is a single 16-bit Unicode character.
- Minimum
value is 0.
- Maximum
value 65,535.
- Char
data type is used to store any character.
- Example:
char letterA ='A'
In addition to the eight primitive data types listed above, the
Java programming language also provides special support for character strings
via the java.lang.String class
String:
String represents a group of characters. Simplest way is to create
a string and store it in a String type variable.
Ex: String s = "this is a string";
The String class is not technically a primitive data type,
but considering the special support given to it by the language. You will learn
more about String Class later.
Default
Values
Generally speaking, the default will be zero or null,
depending on the data type. The following chart summarizes the default values
for the above data types.
Data
Type
|
Default
Value (for fields)
|
Byte
|
0
|
Short
|
0
|
Int
|
0
|
Long
|
0L
|
Float
|
0.0f
|
Double
|
0.0d
|
Char
|
'\u0000'
|
String (or any object)
|
null
|
Boolean
|
false
|
Example Program for Data Type:
public class DataTypesinJava {
public static
void main(String[] args) {
String
str = "vidvaan";
int age = 23;
double fee = 8000;
float sal = 5000;
char gender = 'M';
boolean status = true;
System.out.println("Your
name is :" + str);
System.out.println("Your age
is :" + age);
System.out.println("salary
" + sal);
System.out.println("vidvaan
fee :" + fee);
System.out.println("gender
:" + gender);
System.out.println("Status
:" + status);
}}
Object/Reference
Data types:
You will learn about reference data types later
10. Eclipse
Eclipse Download:
Step 1:- Where
to download Eclipse
Step 2:-
Download the zip file and save it.
Step 3:- Unzip
this file that you just downloaded. It creates a folder named eclipse.
Step 4:-
Create a shortcut on your desktop to the eclipse.exe file
Step
5:- Double-click the shortcut to Eclipse that you just created. In
the Workspace Launcher window, in the box following Workspace:, should appear
something like C:\Documents and Settings\username\workspace (where username is
your login on the machine). If you want, you can type in (or browse) another
location for the workspace file to be created and then click OK button.
Steps
to write a first java program in eclipse:
Click File > New > Java Project
The 'Create a Java Project' box will popup.
Give your Project a name. In this case I have named it 'EclipseTutorial'
Click FINISH.
You have now setup your first project which will appear in the Package Explorer window.
Before we can begin to write any code, we must first add a Package which will contain all our project files.
Make sure your new project is highlighted and click the 'New Java Package' icon.
The 'Create a Java Project' box will popup.
Give your Project a name. In this case I have named it 'EclipseTutorial'
Click FINISH.
You have now setup your first project which will appear in the Package Explorer window.
Before we can begin to write any code, we must first add a Package which will contain all our project files.
Make sure your new project is highlighted and click the 'New Java Package' icon.
Give your package a name relevant to your project.
Click FINISH
Now your Package has been created we need to add a Class file. Make sure the Package is highlighted by clicking it once and then click the 'New Java Class' icon.
The Create a New Java Class box will popup.
Give your Class a name and tick the public static void main(String[] args) box.
Your Class will now appear in the Workspace and you are ready to start writing code!
Here I have wrote a simple Hello World application which will print the words into the console.
To Run your Java project. Right click the 'TutorialClass.java' file in the Package Explorer window, then click Run As > Java Application
The output will now be displayed in the console.
11. Package
A package is a namespace that organizes a set of related classes
and interfaces. This can be compare to different folders in your computer. You
might keep HTML pages in one folder, images in another, and scripts or
applications in yet another. Because software written in the Java programming
language can be composed of hundreds or thousands of individual
classes, it makes sense to keep things organized by placing related classes and
interfaces into packages.
Syntax: package <package_name>;
12. Naming Conventions
Package: Names of packages are written in small letters.
Ex: java.awt
java.io
Class: All class names should begin with a
capital letter. When you are putting several words together to form a class
name capitalize first letter of each word
Ex:AllMyChildren
An Interface is also similar to a class. A class or an interface
contains methods and variables.
Methods:
The names of methods should begin with lowercase letters, as in the main
method. When you are putting several words together to form a method name start
with the lower case and capitalize the first letter of each word.
Ex: allMyChildren
Variables:
Variable naming conventions are same as method conventions.
Constants: Constants represents fixed values that cannot be
altered. All letters are written in uppercase and words separated by
underscores.
Ex: ALL_MY_CHILDREN
13. Identifier and keyword
Identifiers:
All Java components require names. Names used for classes,
variables and methods are called identifiers.
Rules:
·
All identifiers must start with a letter (A to Z
or a to z), currency character ($) or an underscore (_).
·
After the first character identifiers can have
any combination of characters.
·
A key word cannot be used as an identifier.
·
Identifiers are case sensitive.
·
Examples of legal identifiers: age, $salary,
_value, __1_value
·
Examples of illegal identifiers: 123abc, -salary
Keywords:
Keywords are nothing but reserved words havin a predefined
meaning. Programmers cannot use keywords as identifiers. Below are few examples
of keywords
Examples:
Continue
|
for
|
new
|
switch
|
|
Boolean
|
default
|
if
|
package
|
|
Break
|
do
|
void
|
private
|
|
Byte
|
double
|
while
|
protected
|
|
Byte
|
else
|
import
|
public
|
|
Case
|
try
|
instanceof
|
return
|
|
Catch
|
extends
|
int
|
short
|
|
Char
|
final
|
interface
|
static
|
|
Class
|
finally
|
long
|
throw
|
|
Throws
|
float
|
native
|
super
|
14.
Operators
An operator is a symbol that performs an operation.
a + b
+ is Operator
a and b are Operands
If an operator acts on single variable, it is called a
unary operator. If it acts on two variables, it is called binary operator and
if it acts on three variables, this it is called ternary operator.
Below are various
types of operators.
Arithmetic
Operators:
These operators are used to perform fundamental
arithmetic operations. There are 5 arithmetic operators in java. Since these
operators work on two operands at a time, these are called binary operators.
Assuming the value of a as 13 and b is 5
Operator
|
Meaning
|
Example
|
Result
|
+
|
Addition Operator
|
a+b
|
18
|
-
|
Substraction Operator
|
a-b
|
8
|
*
|
Multiplication Operator
|
a*b
|
65
|
/
|
Division Operator
|
a/b
|
2.6
|
%
|
Modulus
|
a%b
|
3
|
Addition operator is also used to join two Strings.
String s1=”wel”;
String s2=”come”;
String s3 =s1+s2;//here + will join s1 and s2 and output
is welcome
Example Program:
public class
ArthamaticOprators {
public static void main(String[]
args) {
int num1 = 2;
int num2 = 4;
// addition
int add = num1 +
num2;
System.out.println("add
:" + add);
// Subtraction
int sub = num1 -
num2;
System.out.println("sub
:" + sub);
// multification
int mul = num1 *
num2;
System.out.println("mul
:" + mul);
// division
int div = num1 /
num2;
System.out.println("division
:" + div);
// modulus
int mod = num1 %
num2;
System.out.println("modulus
:" + mod);
}
}
Unary Operators:
The unary operators require only one operand; they
perform various operations such as incrementing/decrementing a value by one,
negating an expression, or inverting the value of a boolean.
Operator
|
Meaning
|
+
|
Unary plus operator(indicates
positive
value)
|
-
|
Unary minus operator(negates
a given
value)
|
++
|
Increment Operator
|
--
|
Decrement Operator
|
!
|
Logical complement operator
|
Increment Operator
(++):
Increment Operator is used to increment value of a
variable by 1. This is denoted by the symbol “++”. This can be used
in two ways.
Case1 :
Appending “++” operator after the variable name
Consider the operation “i++”. Here the value
of the variable “i” will be incremented by 1.
Example:
int i = 5;
i++;
i++;
Here the variable “i” will be initialized with a value 5.
Then we use the increment operator to increment its value by 1. As a result,
the value of the variable “i” will be incremented to 6.
Case2 :
Prepending “++” operator before the variable name
Consider the operation “++i”. Here the value
of the variable “i” will be incremented by 1.
Example:
int i = 5;
++i;
++i;
Here the variable “i” will be initialized with a value 5.
Then we use the increment operator to increment its value by 1. As a result,
the value of the variable “i” will be incremented to 6.
Difference between these two Cases
Both the cases looks similar. But there is major
difference. In the first case “variable_name++” the current statement will be
executed and then the value will be incremented by 1.Then the next statement
will be executed.
In the second case “++variable_name” the value will be
incremented by 1 first. Then the current statement will be
executed.
Example1:
int value1 = 10;
int value2 = value1++;
int value2 = value1++;
Here we are using the increment operator, appended to the
variable name (case1).
1. The value of the variable “value1” will be assigned to
the variable "value2”. It means the variable “value2” gets 10 as its
value.
2. Now the value of the variable “value1” will be
incremented by 1. It means the value of the variable “value1” will be 11 now.
Example2:
int value1 = 10;
int value2 = ++value1;
Here we are using the increment operator, prepended to the variable name (case2).
int value2 = ++value1;
Here we are using the increment operator, prepended to the variable name (case2).
1. At first, the value of the variable “value1” will be
incremented by 1. It means the value of the variable “value1” will be 11 now.
2. The value of the variable “value1” will be assigned to
the variable "value2”. It means the variable “value2” gets 11 as its
value.
Decrement Operator(--):
This is used to decrement the value of a variable by 1.
This is denoted by the symbol “--”.
This can be used in two ways.
Case 1- Appending “--” operator after the variable name:
The current statement is executed and then decremented by 1 and then the next
statement is executed.
Case 2 - Prepending “--” operator before the variable
name the value will decrement the value
by 1 first. Then the current statement will be executed.
Assignment
Operators:
One of the most common operators is assignment operator
“=”. This operator assigns a value on its right hand side to the operand
on its left hand.
Ex: int x=5;
int speed = 0;
Compact Notation:
While using assignment operators some time we may have to
use the same variable on both the sides of the operator. In such cases we can
eliminate repetition of variable and use compact notation.
Expanded Notation
|
Compact Notation
|
Name of Operator
|
x=x+5
|
x += 10
|
+= is called addition assignment operator
|
sal=sal*10.5
|
sal *= 10.5
|
*= is called multiplication assignment operator
|
value = value-discount
|
Value -= discount
|
-= is called substraction assignment operator
|
p = p/1000
|
p /= 1000
|
/= is called division assignment operator
|
num = num % 5.5
|
num %= 5.5
|
%= is modulus assignment operator
|
Relational
Operators:
Operator
|
Description
|
Example
|
==
|
Checks if the values of two operands are equal or not,
if yes then condition becomes true.
|
(A == B) is not true.
|
!=
|
Checks if the values of two operands are equal or not,
if values are not equal then condition becomes true.
|
(A != B) is true.
|
>
|
Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes true.
|
(A > B) is not true.
|
<
|
Checks if the value of left operand is less than the
value of right operand, if yes then condition becomes true.
|
(A < B) is true.
|
>=
|
Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then condition becomes true.
|
(A >= B) is not true.
|
<=
|
Checks if the value of left operand is less than or
equal to the value of right operand, if yes then condition becomes true.
|
(A <= B) is true.
|
Example Program:
public class
RelationalOperatorExample {
public static void main(String[] args)
{
int value1 = 1;
int value2 = 2;
if (value1 == value2)
System.out.println("value1 ==
value2");
if (value1 != value2)
System.out.println("value1 !=
value2");
if (value1 > value2)
System.out.println("value1 >
value2");
if (value1 < value2)
System.out.println("value1 <
value2");
if (value1 <=
value2)
System.out.println("value1 <=
value2");
if (value1 >=
value2)
System.out.println("value1 >=
value2");
}
}
Logical Operators:
Below are the logical operators
Operator
|
Description
|
Example
|
&&
|
Called Logical AND operator. If
both the operands are true, then the condition becomes true.
|
(A && B) is false.
|
||
|
Called Logical OR Operator. If
any of the two operands are true, then the condition becomes true.
|
(A || B) is true.
|
!
|
Called Logical NOT Operator. Use
to reverses the logical state of its operand. If a condition is true then
Logical NOT operator will make false.
|
!(A && B) is true.
|
Conditional
Operator:
Conditional operator is also known as the ternary
operator. This operator consists of three operands and is used to evaluate
Boolean expressions. The goal of the operator is to decide which value should
be assigned to the variable.
Syntax:
variable x= (expression)?value if expression is true:
value if expression is false
Example Program:
public class ConditionalOperators
{
public static void main(String[] args)
{
int a, b;
a
= 10;
b
= (a == 1) ? 20 : 30;
System.out.println("Value of b is
: "
+ b);
b
= (a == 10) ? 20 : 30;
System.out.println("Value of b is
: "
+ b);
}
}
Operator
Precedence:
The operators have precedenct i.e., whish operator should
be evaluated first and which operator is next in performing some caluculations
If two operator of same precedence exist in same
calculation then Associativity of the operators will be used to decide which
operator will be executed first.
Operator Precedence Table
|
|
Operators
|
Precedence(High
to Low)
|
Postfix
|
expr++ expr--
|
Unary
|
++expr --expr +expr -expr ~ !
|
Multiplicative
|
* / %
|
Additive
|
+ -
|
Shift
|
<< >> >>>
|
Relational
|
< > <= >= instanceof
|
Equality
|
== !=
|
bitwise AND
|
&
|
bitwise exclusive OR
|
^
|
bitwise inclusive OR
|
|
|
logical AND
|
&&
|
logical OR
|
||
|
Ternary
|
? :
|
Assignment
|
= += -= *= /= %= &= ^= |= <<= >>=
>>>=
|
Example of Precedence:
public class OperatorPrecedence {
public static void main(String[] args)
{
int i = 40;
int j = 80;
int k = 40;
int l = i + j / k;
System.out.println("value of L
:"
+ l);
int m = (i + j) / k;
System.out.println("Value of
M:"
+ m);
}
}
Output:
value of L :42
Value of M:3
Good to see your after a long time.
ReplyDeleteThank you
ReplyDelete