UnitII-Java Notes (New Syllabus)
UnitII-Java Notes (New Syllabus)
UNIT II NOTES
1. ELEMENTS
1.1) Constants
1.2) Variables
1.3) Scope of Variables
1.4) Data types
1.5) Symbolic Constants
1.6) Type Casting
2. OPERATORS
2.1) Operators
2.2) Expressions
2.3) Evaluation of Expressions
3. DECISION MAKING & BRANCHING
3.1) Branching or Selection or conditional statement
4. DECISION MAKING & LOOPING
4.1) Iterative or looping statement
4.2) Jumps in loops
4.3) Difference between while & do-while loop
4.4) Additional features of for loop
5. ARRAYS
5.1) Arrays
5.1.1) One Dimensional Array
5.1.2) Multi Dimensional Array
5.2) Vectors
5.3) Array List in Java
5.4) Advantages of Array List over Array
5.5) Wrapper classes
1
JAVA NOTES UNIT - II
1. ELEMENTS
1.1) Constants:
Constant means fixed value. When constant values are used in the program we cannot
change the value during execution.
Types of constants:
1) Integer Constants.
2) Real Constants.
3) Single Character Constants.
4) String Constants.
5) Backslash Character Constants.
1) Integer Constants:
Integer Constants refers to a Sequence of digits which includes only negative or positive
values .
An integer constant must have at least one digit.
It must not have a decimal value.
It could be either positive or negative.
If no sign is specified then it should be treated as positive.
Eg. 123,-34
2) Real Constants:
A real constant must have at least one digit.
It must have a decimal value.
It could be either positive or negative.
If no sign is specified then it should be treated as positive.
Eg. 234.89
In The Exponential Form of Representation, the Real Constant is Represented in the two
Parts. The part before appearing e is called mantissa whereas the part following e is called
Exponent.
In Real Constant The Mantissa and Exponent Part should be Separated by letter e.
The Mantissa Part have may have either positive or negative Sign.
Default Sign is Positive.
3) Single Character Constants:
A character is a single alphabet or a single digit or a single symbol that is enclosed within
2
JAVA NOTES UNIT - II
1.2) Variables:
A variable is used for storing a value and may take different values during the execution of
the program. It is usually defined by the user. It uses letters, underscores, or a dollar sign as
the first character.
Argument variables:
These are the variables that are defined in the header oaf constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The lifetime
is limited to the time for which the method keeps executing. Once the method finishes
execution, these variables are destroyed.
Local Variables:
The Variables those are declared in Method of class are known as Local Variables
They are Called Local because they are not used from outside the method The Accessibility
of Variables Through out the program is called is Known as the Scope of Variables.
Class Variables:
The Variables that are declared inside a class are called as Class variables or also
called as data members of the class .They are friendly by default means they are accessible to
main Method or any other Class Which inherits.
Class
Interface
Java defines four integer types: byte, short, int, and long. All of these are signed, positive
and negative values. Java does not support unsigned, positive-only integers.
4
JAVA NOTES UNIT - II
Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision. For example, calculations such as square root, sine and
cosine, result in a value whose precision requires a floating-point type. Java supports two
types of floating point data types namely float and double. Float type data specifies a single
precision value. Double type data specifies a double precision value.
1.3 Characters:
Char is the data type used to store characters in java. The size of character type data is 2
bytes. Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages.
1.4 Boolean:
Boolean type is used when we want to test a particular condition during the execution of the
program. There are only two values that a Boolean type can take; true or false. Boolean type
is denoted by the keyword boolean and uses only one bit of storage
2.2 Arrays:
Arrays in Java are homogeneous data structures implemented in Java as objects. Arrays store
one or more values of a specific data type and provide indexed access to store the same. A
specific element in an array is accessed by its index.
2.3 Classes:
A class in Java is a blueprint which includes all your data. A class contains fields(variables)
and methods to describe the behaviour of an object.
2.4 Interface:
Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).
5
JAVA NOTES UNIT - II
Syntax :
final type symbolic_name= value;
Rules :
Symbolic names take the same form as variable names, but they are written in
capitals letters.
They can’t be declared inside a method. They should be used only as class data
members in the beginning of the class.
Examples:
int m=5;
byte n= (byte)m;
long count=(long)m;
Four integer types can be cast to any other type except Boolean. Casting into a smaller type
may result in a loss of data.
6
JAVA NOTES UNIT - II
From To
byte Short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int Long, float, double
long float, double
float double
Automatic Conversion:
It is possible to assign a value of one data type to a variable of a different data type without a
cast. Java does the conversion of the assigned value automatically. This is known as
automatic type conversion. Automatic type conversion is possible only if the destination type
has enough memory space to store the source value. For example, int is large enough to hold
a byte value.
Therefore,
byte b = 75;
int a = b;
are valid statements.
The process of assigning a smaller data type to a larger data type is known as widening or
promotion and that of assigning a larger data type to a smaller data type is known as
narrowing. Note that narrowing may result in loss of information
Program:
class typewrap
{
public static void main(String args[])
{
char c = ‘x’;
byte b = 50;
short s = 1996;
int i = 123456789;
short s1= (short) b;
short s2= (short) i; // Produces incorrect result
System.out.println(“ (short) b = ” + s1);
System.out.println(“ (short) i = ” + s2);
}
}
Output of Program:
(short)b = 50
(short)i = -13035
7
JAVA NOTES UNIT - II
2. OpEraTOrS
2.1) Operators:
Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
Types of operators:
i. Arithmetic operators.
ii. Relational operators.
iii. Logical operators.
iv. Assignment operators.
v. Increment and decrement operators.
vi. Conditional operators.
vii. Bitwise operators.
viii. Special operators.
i) Arithmetic operators:
An operator that performs an arithmetic operation is called arithmetic operator. Arithmetic
operation requires two or more operands. Therefore these operators are called binary
operators.
Instanceof Operator:
The instanceof is an object reference operator and returns true if the object on the left-hand
side is an instance of the class given on the right-hand side. This operator allows us to
determine whether the object belongs to a particular class or not.
Example:
person instanceof student
Returns true if the object person belongs to the class student; otherwise it is false.
Dot Operator:
The dot operator (.) is used to access the instance variables and methods of class objects.
Example:
person.age
person.salary()
2.2) Expressions:
An expression is a combination of operators, constants and variables. An expression is
a sequence of operands and operators that produces a value.
Types of Expressions:
i) Constant expressions:
Constant expressions consists of only constant values. A constant value is one that doesn’t
change.
Examples:
10 + 5 / 6.0
'x’
10
JAVA NOTES UNIT - II
v) Logical expressions:
Logical Expressions combine two or more relational expressions and produces boolean type
results.
Examples:
x > y && x == 10
x == 10 || y == 5
variable is any valid Java variable name. When the statement is encountered, the expression
is evaluated first and the result then replaces the previous value of the variable on the left-
hand side. All variables used in the expression must be assigned value before evaluation is
attempted.
When these statements are used in program, the variables a,b,c and d must be defined before
they are used in the expressions.
An arithmetic expression without any parentheses will be evaluated from left to right
using the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in Java:
The basic evaluation procedure includes two left-to-right passed through the
expression. During the first pass, the high priority operators (if any) are applied as they are
encountered.
High priority * / %
Low priority + –
During the second pass, the low priority operators (if any) are applied as they are
encountered. Consider the following evaluation statement:
x = a–b/3 + c*2–1
Second pass
Step3: x = 5+6–1 (9–4 evaluated)
Step4: x = 11–1 (5+6 evaluated)
Step5: x = 10 (11–1 evaluated)
Whenever the parentheses are used, the expressions within parentheses assume highest
12
JAVA NOTES UNIT - II
priority. If two or more sets of parentheses appear one after another as shown above, the
expression contained in the left-most set is evaluated first and the right-most in the last.
Second pass
Step3: 9–2*1
Step4: 9–2
Third pass
Step5: 7
This time, the procedure consists of three left-to-right passes. However, the number of
evaluation steps remain the same as 5
i) if statement:
Syntax:
if (expression)
{
Statements;
}
Explanation:
If the condition is true, statement is executed. If it is false, statement is not executed and the
program continues after this conditional structure.
Example:
if (a<b)
System.out.println(”a is less than b”);
13
JAVA NOTES UNIT - II
Explanation:
If test expression is true then block1 statements are executed otherwise block2 statements are
executed.
Example:
if (a>b)
System.out.println(“A is greater than B”);
else
System.out.println (“B is greater than A”);
Explanation:
If the test expression-1 condition is true, then its corresponding test expression-2 statements
are executed, otherwise it is skipped and next else test expression-3 statements are evaluated.
Example:
if (a>b)
{
if(a>c)
System.out.println("A is largest among three numbers");
14
JAVA NOTES UNIT - II
else
System.out.println("C is largest among three numbers");
}
else
{
if(b>c)
System.out.println("B ia largest among three numbers");
else
System.out.println("C ia largest among three numbers");
}
if(condition1)
statement1;
else if(condition2)
statement 2;
else if(condition3)
statement 3;
else
default statement.
statement-x;
Explanation:
The condition is evaluated from top to bottom. If a condition is true then the statement
associated with it is executed. When all the conditions become false then final else part
containing default statements will be executed.
Example:
if (percentage>=80)
System.out.println(”Distinction”);
else if (percentage>=60)
System.out.println(”First class”);
else if (percentage>=50)
System.out.println(”Second class”);
else if (percentage>=40)
System.out.println(”Third class”);
else
System.out.println(”Fail”);
}
15
JAVA NOTES UNIT - II
v) Switch statement:
Syntax:
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
--------
--------
default:
default block;
}
Explanation:
Here, expression is the condition that is being evaluated. If the case 1 condition is true,
block-1 statements are executed. otherwise case 2 condition is checked and so on....If none
of case expressions is true then the statements of default case body is executed.
Example:
switch(power)
{
case 0:
System.out.println(”Power is off”);
break;
case 1:
System.out.println(”Power is on”);
break;
default:
System.out.println(”Give the power value as either 0 or 1”);
}
Explanation:
It is an entry controlled loop. The condition is evaluated and if it is true then body of loop is
executed. After execution of body the condition is once again evaluated and if is true the
body is executed once again. This goes on until the test condition becomes false.
Example:
import java.io.*;
class num
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream d = new DataInputStream(System.in);
System.out.println("Enter the number");
n=Integer.parseInt(d.readLine());
while (n>0)
{
System.out.println(n);
n--;
}
}
}
Explanation:
The do…while is an exit controlled loop and its body is executed at least once. It evaluates
its test – expression at the bottom of the loop after executing its loop-body statement.
Example:
import java.io.*;
17
JAVA NOTES UNIT - II
class num
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream d = new DataInputStream(System.in);
do
{
System.out.println("Enter any number (type 0 to exit)");
n=Integer.parseInt(d.readLine());
System.out.println( "You entered"+n);
}
while (n != 0);
}
}
Explanation:
Initialization expression is used to initialize the variables
If the condition is true, then the program control flow goes inside the loop and
executes the block of statements associated with it .If test expression is false, loop
terminates.
Increment/decrement expression consists of increment or decrement operator. This
process continues until the test condition satisfies.
Example:
import java.io.*;
class num
{
public static void main(String args[]) throws IOException
{
for (int n=10; n>0; n--)
{
System.out.println( n) ;
}
}
}
18
JAVA NOTES UNIT - II
Statements that transfers control from one part of the program to another part of the program
unconditionally.
i. break
ii. continue
iii. Labeled Loops
i) break statement:
The break statement is used to terminate the execution of the loop program. It terminates the
loop in which it is written and transfers the control to the immediate next statement outside
the loop. The break statement is normally used in the switch conditional statement.
Example:
for (n=5; n>0; n--)
{
System.out.print( n +", ");
if (n==3)
{
System.out.println("countdown aborted!");
break;
}
}
Output: 5, 4, 3, countdown aborted!
19
JAVA NOTES UNIT - II
ii) Continue:
It is used to continue the iteration of the loop statement by skipping the statements after the
continue statement. It causes the control to go directly to the test condition and then to
continue the loop.
Example:
for (int n=5; n>0; n--)
{
if (n==3)
continue;
System.out.print( n +", ");
}
System.out.println("FIRE!");
Output: 5, 4, 2, 1, FIRE!
Example:
//A Java program to demonstrate the use of labeled for loop
import java.io.*;
class labelloop
{
public static void main(String args[])
{
outer:
for(int i=1;i<=3;i++)
{
inner:
for(int j=1;j<=3;j++)
{
if(i==2 && j==2)
{
break outer;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
21
JAVA NOTES UNIT - II
while Do-while
It is a looping construct that will execute It is a looping construct that will execute
only if the test condition is true. atleast once even if the test condition is
false.
It is an entry-controlled loop It is an exit-controlled loop.
It is generally used for implementing It is used for implementing menu-based
common looping solutions. programs.
1) More than one variable can be initialized at a time in the for statement
Eg. for(n=1, m=5; n<=m; n++,m--)
3) The compiler will not give an error message if we place a semicolon at the
end of the for statement. The semicolon will be considered as an empty
statement and the program may produce some nonsense.
Eg. for(i=1;i<=5;i++);
Output
22
JAVA NOTES UNIT - II
1 1
1 2
2 1
2 2
Example
The following code displays all the elements in the array myList −
class TestArray {
Output
1.9
2.9
3.4
3.5
5. arraYS
5.1) Arrays:
An array is a group of similar data typed variables that shares a common name. The
elements of the array are accessed by the array index. The array index should be a positive
integer value.
23
JAVA NOTES UNIT - II
Types:
1.One dimensional array
2. Two dimensional array or Multi dimensional array
dataType[] arrayname;
or
dataType arrayname[];
Creating Arrays
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
In the above example a is an integer array of size 10, n is a double type array of size 5 and s
is a String array of size 7.
Example:
int a[ ] = { 10, 34,22,56,21};
In the above example the integer values are assigned as a[0]=10, a[1]=34, a[2]=22, a[3]=56
and a[4]=21.
String s[ ] = { “Anand”, “Bala”, “Jhon Samuel”, “Hayes”};
In the above example the String objects are assigned as s[0]=”Anand”; s[1]=”Bala”,
s[2]=”Jhon Samuel”, s[3]=”Hayes”
24
JAVA NOTES UNIT - II
Example
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
System.out.println(a[i]);
}
}
}
Output:
Enter the total number of elements
5
Enter the elements
30
23
56
12
65
Sorted Numbers
12
23
30
56
65
Declaration:
type array-name[ ][ ] = new type[ rowsize][columnsize];
Example:
int m[ ][ ] = new int[3 ] [4];
double d[ ][ ] = new double[2] [3];
String name[ ][ ]= new String[3][20];
In the above example m is an integer type matrix of 3 rows and 4 columns, d is a double type
matrix of 2 rows and 3 columns and name is a String array of size 3 rows and 20 columns.
Input:
The matrix elements can be assigned directly along with the declaration. This is called
initialization of arrays. The values can also be assigned during execution by the user.
Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
In the above example the integer values are assigned as a[0][0]=1, a[0][1]=2,
a[0][2]=3, a[1][2]=4 ….a[2][2]=9.
26
JAVA NOTES UNIT - II
Output:
The elements of the matrix can be printed in the matrix format array index and two loop
statements.
Example:
int a[ ][ ]= { {1,2,3},{4,5,6},{7,8,9}};
System.out.println(“ Matrix);
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j]+” “]);
System.out.println(“ “);
}
}
System.out.println("Enter Matrix B elements");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
b[i][j]=Integer.parseInt(d.readLine());
}
}
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Addition of two matrix");
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println(" ");
}
}
}
Output:
Enter the number of rows and columns
2
2
Enter Matrix A elements
1
2
3
4
Enter Matrix B elements
2
3
4
5
Addition of two matrix
3 5
7 9
28
JAVA NOTES UNIT - II
5.2) Vectors:
Creation of Vectors:
Vector V = new Vector(); //declaring without size or
Vector V = new Vector(3); // declaring with size
Advantages:
Vectors can be used to store objects.
It can be used to store a list of objects that may vary in size.
We can add and delete objects from the list, when required.
Disadvantages:
It cannot directly store simple data type.
Conversion of simple data type to objects is required. This is done by
using thewrapper classes.
addElement (item) Add the item specified to the list at the end
{
Vector v = new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("Number Names",0);
System.out.println("Size="+v.size());
System.out.println("Element at"+v.elementAt(2));
}
}
Output:
Number Names
one
two
three
Size=4
Element at two
The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed. Array lists are created with an
initial size. When this size is exceeded, the collection is automatically enlarged. When
objects are removed, the array may be shrunk.
indexOf(value) returns first index where given value is found in list (-1 if not
found)
Advantages:
ArrayList is initialized by the size. However, the size is increased automatically if the
collection grows or shrinks if the objects are removed from the collection.
Java ArrayList allows us to randomly access the list.
ArrayList cannot be used for primitive types, like int, char, etc. We need a wrapper
class for such cases.
ArrayList in Java is equivalent to vector in C++.
import java.util.*;
class example
{
public static void main( String args[] )
{
ArrayList shapes = new ArrayList();
shapes.add("square");
shapes.add("triangle");
shapes.add("rectangle ");
shapes.add("circle");
System.out.println(shapes);
System.out.println(shapes.get(2));
shapes.remove(2);
System.out.println(shapes);
shapes.set(2,"polygon");
System.out.println(shapes);
System.out.println(shapes.size());
shapes.clear();
System.out.println(shapes);
}
}
31
JAVA NOTES UNIT - II
Output
[square, triangle, rectangle, circle]
rectangle
[square, triangle, circle]
[square, triangle, polygon]
3
[]
Vectors cannot handle primitive data types like int, float, long, char and double. Primitive
data types may be converted into object types by using the wrapper classes contained in the
java.lang package.
Converting String objects to Numeric objects using the method valueOf ():-
Autoboxing:
The automatic conversion of primitive data type into its corresponding wrapper class
is known as autoboxing.
Example:
import java.util.ArrayList;
class Autoboxing
{
public static void main(String args[])
{
ArrayList<Integer> arr = new ArrayList<Integer>();
Output:
25
Unboxing:
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing.
34
JAVA NOTES UNIT - II
Example:
import java.util.ArrayList;
class Unboxing
{
public static void main(String args[])
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(24);
Output:
24