Java Unit-2
Java Unit-2
Operators in Java:
Java provides a rich set of operators environment. Java operators can be divided
into following categories:
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are
used in algebra.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
Example Program:
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
Output :
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27
Relation operators:
The following table shows all relation operators supported by Java.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Example Program:
public class Test {
public static void main(String args[]) {
int a = 10,b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Example:
public class Test {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
This will produce the following result −
a && b = false
a || b = true
!(a && b) = true
Bitwise operators:
Java defines several bitwise operators that can be applied to the integer
types long, int, short, char and byte
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> left shift
<< right shift
Now lets see truth table for bitwise &, | and ^
A B a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shift the bit value. The left operand specifies the value
to be shifted and the right operand specifies the number of positions that the bits in
the value are to be shifted. Both operands have the same precedence.
Example:
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
}
}
This will produce the following result −
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
Assignment Operators
Assignment operator supported by Java are as follows:
Operator Description Example
= assigns values from right side operands to left side a=b
operand
+= adds right operand to the left operand and assign the a+=b is same
result to left as a=a+b
-= subtracts right operand from the left operand and a-=b is same as
assign the a=a-b
result to left operand
*= mutiply left operand with the right operand and a*=b is same
assign the result to left operand as a=a*b
/= divides left operand with the right operand and a/=b is same
assign the result to left operand as a=a/b
%= calculate modulus using two operands and a%=b is same
assign the result to left operand as a=a%b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3
If epr1 Condition is true? Then value expr2: Otherwise value expr3
Example:
instanceOf operator
This operator is used for object reference variables. The operator checks whether
the object is of particular type (class type or interface type)
Java Expressions
Expressions consist of variables, operators, literals and method calls that evaluates
to a single value. Example are shown below
Control Statements
A Control statement is a statement that controls the flow of execution of the
program. Java‟s program control statements are divided into 3 categories
● Selection Statements
● Iteration Statements
● Jump Statements
1)Selection Statements:
Selection statement controls the flow of the program depending on the result of
the conditional expression or the state of a variable. There are two selection
statements: if and switch
a. if statement:
„if‟ is a selection statement that is used to choose two choices in a program.
Syntax: Example
if(condition) if(condition)
statement1; System.out.println(“if block”);
else else
statement2; System.out.println(“else block”);
„condition‟ is any expression that returns a Boolean value (i.e.,
true/false). Statement is a single or multiple statements.
If the condition is true then the control goes to the statement1 and it is
executed. Otherwise, the statement2 is executed.
b. Nested if statement:
It means an if statement under another if statement.
Syntax:
if(condition)
{
if(condition)
statement;
}
c. If - else- if ladder:
if-else-if statement is a sequence of if-else statements.
Syntax:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
statement3;
. …..
else statementn;
In if-else-if ladder if a condition is not met then the control flows from
top to bottom until the last if statement.
d. switch statement: It provides more than one choice to choose. It‟s a better
alternative to if-else-if ladder.
Syntax:
switch(expression) public class Test {
{ public static void main(String args[]) {
case value1: statement1; // char grade = args[0].charAt(0);
break; char grade = 'C';
case value2: statement2; switch(grade) {
break; case 'A' :
case value3: statement3; System.out.println("Excellent!");
break; break;
. case 'B' :
. case 'C' :
case valueN: statementN; System.out.println("Well done");
break; break;
default : statement; case 'F' :
} System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Here, the expression may be of type byte, short, int or char only. the case
values must be of type expression and each value should be unique. when
control comes to the switch statement then the value of the expression is
compared with the case values, if a match is found then the statement(s)
corresponding to that case is executed. If none of the case is matched then the
default statement is executed.
2) Iteration Statements:
These statements allow the part of the program to repeat one or more times
until some condition becomes true. There are 3 iteration statements: while, do-while
and for.
a. while statement:
„while‟ is an iteration statement, that repeats a statement or block of
statements until some condition is true.
Syntax:
Syntax Example
while(condition) public class Test {
{ public static void main(String args[]) {
int x = 10;
// body of the loop while( x < 20 ) {
} System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
where the condition may be any boolean expression. The body of the
loop will be executed as long as the condition is true. Once the condition
becomes false, the control passes to the statement immediately after the
while loop.
b. do-while statement:
„do-while‟ statement is very much similar to while statement with little
difference. In while statement, if the condition is initially false then the body
of loop will not be executed at all. Where as in do-while statement, body of
the loop will be executed at least once since the condition of do-while is at the
bottom of the loop.
Syntax Example
Do public class Test {
{ public static void main(String args[]) {
// body of the loop int x = 10;
do {
} while(condition);
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Each iteration of do-while executes the body of loop first and evaluates
the condition later. If condition is true, the loop repeats. Otherwise, the loop
terminates.
c. for statement:
„for‟ statement also repeats the execution of statements while its condition is
true.
Syntax:
Syntax Example
for(initialization; public class Test {
condition; iteration) public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) {
{ System.out.print("value of x : " + x );
// body of the loop System.out.print("\n");
} }
}
}
Where initialization portion of the loop sets the value of the variable
that acts as a counter. This portion is executed first when the loop starts. And
it is executed only once. when the control goes to condition, condition is
evaluated. If condition is true, the body of loop is executes. Otherwise the loop
terminates. Next iteration portion is executed. This helps to increment or
decrement the control variable.
The loop then iterates evaluating condition, then executing the body
and then executing the iteration portion each time it iterates.
2) Jump Statements:
Jump statements allow the control to jump to a particular position. There are
3 types of jump statements.
a. break statement:
In java, there are 3 uses of break statement.
i. It helps to terminate a statement sequence in switch statement.
ii. It can be used to exit or terminate the loop
iii. It can be used as another form of goto
Example:
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
if(i==10)
break; // terminates loop if i is 10
System.out.println(“i :”+i);
}
}
}
b. continue statement: The continue statement starts the next iteration of the
immediately enclosing iteration statements (while, do-while or for). When the
control goes to continue statement, then it skips the remaining statements
and starts the next iteration of enclosing structure. Example shown below.
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
System.out.println(“i :”+i);
if(i%2==0)
continue;
System.out.println(“ “);
}
}
}
c. return statement: This is used to return from a method. When the control
reaches to return statement, it causes the program control to transfer back to
the caller of the method. Example shown below.
class A
{
public static void main(String arg[])
{
boolean t=true;
if(t)
return;
System.out.println(“Hi”); // This won‟t execute
}
}
Classes & objects
Concept of Classes
A class is defined as an encapsulation of data and methods that operate on
the data. When we are creating a class we are actually creating a new data type.
This new data type is also called ADT.
------diagram---
When we define a class we can easily create a no of instances of that class
Creating class in java:
In java, a class can be defined through the use of class keyword. The general
definition of a class is given below:
class classname
{
type instance_variable1;
type instance_variable1;
………
returntype methodname(parameter list)
{
// body of method
}
……………………..
}
Here,
● class is a keyword used to define class
● class name is the identifier that specifies the name of the class
● type specifies the datatype of the variable
● instance_variable1, . . . are the variable defined in the class
● method name is the method defined in the class that can operate on the
variables in the class
Example:
class Sample
{ int x, y;
setXY()
{
x=10; y=20;
}
}
The variables defined in the class are called member variables/data members
The functions defined in the class are called member functions/member
methods.
Both data members and member methods together called members of class.
Concept of Objects
Objects are instances of a class. Objects are created and this process is called
“Instantiation”. In java objects are created through the use of new operator. The
new operator creates an object and allocates memory to that object. Since objects
are created at runtime, they are called runtime entities.
In java object creation is a two step process.
Step1: create a reference variable of the class. When this declaration is made
a reference variable is created in memory and initialized with null.
Example: Sample s;
Step2: create the object using the new operator and assign the address
of the object to the reference variable created in step1.
Example: Sample s=new Sample();
The step2 creates the object physically and stores the address of the object in
the reference variable.
Accessing members of an object:
Once an object of a class is created we can access the members of the class through
the use of object name and „.„ (dot) operator.
Syntax: objectname. member;
Example:
class sample
{ int x, y;
setXY()
{
x=10; y=20;
}
printXY()
{ System.out.print(“=”+x);
System.out.print(“=”+y);
}
}
class Demo
{ public static void main(String ar[])
{ sample s;
s=new sample();
s.setXY();
s.printXY();
}
}
Constructors
A constructor is a special kind of method that has the same name as that of
class in which it is defined. It is used to automatically initialize an object when the
object is created. Constructor gets executed automatically at the time of creating the
object. A constructor doesn‟t have any return type.
Example: // program to demonstrate constructor
class Student
{
int number;
String name;
Student() // default constructor
{
number=569;
name=”satyam”;
}
Student(int no, String s) // parameterized constructor
{
number=no;
name=s;
}
void showStudent()
{
System.out.println(“number =”+number);
System.out.println(“name =”+name);
}
}
class Demo
{
public static void main(String ar[])
{
Student s1=new Student();
Student s2=new Student(72,”raju”);
s1.showStudent();
s2.showStudent();
}
}
Static Methods:
● A static method can call other static methods only
● A static method can access static variables only
● Static methods can‟t have access to this/ super keyword.
Static Blocks:
Just like static variables and static methods we can also create a static block . this
static block is used to initialize the static variables.
Example program:
class UseStatic
{ static int a=3;
static int b;
static void meth(int x)
{
System.out.println(“x=” + x);
System.out.println(“a=” + a);
System.out.println(“b=” + b);
}
static
{
System.out.println(“static block initialized”);
}
public static void main(String args[])
{
meth(69);
}
}
s.setStudent(69,81,”ramu”);
s.showStudent();
}
}
Output: number=1
marks=89
name=rama
number=69
marks=81
name=ramu
Overloading Constructors:
Just like member methods constructors can also be overloaded. the following
example demonstrates this,
class Student
{ int no;
String name;
Student()
{ no=70;
name=”ram”;
}
Student(int n, String s)
{ no=n; name=s;
}
void show()
{ System.out.println(“Number=”+no);
System.out.println(“Name=”+name);
}
}
class Display
{ public static void main(String ar[])
{
Student s1= new Student();
Student s2= new Student(69,”satya”);
s1.show();
s2.show();
}
}
Output: number=70
name=ram
number=69
name=satya
Parameter passing
There are two ways that a computer language can pass an argument to a
subroutine (method).
1. call by value
2. call by reference
In the first way, the change made to the parameter of the subroutine has no
effect on the argument.
In the second way, the changes made to the parameter will affect the
argument used to call the subroutine.
In java when you pass a primitive type it is pass by value. when you pass an
object(reference) to a method, it is done through pass by reference
Example:
// call by value
class Test
{
void meth(int i , int j)
{
i+=2; //i=i+2;
j*=2; //j=j*2;
}
}
class CallByValue
{
public static void main(String arg[])
{ Test ob= new Test();
int a=10 , b=20;
System.out.println(“a and b before call: ”+a+” ”+b);
ob.meth(a,b);
System.out.println(“a and b after call: ”+a+” ”+b);
}
}
Output:
a and b before call: 10 20
a and b after call: 10 20
Recursion:
Java supports recursion. It is the process of defining something interms of
itself. It is the attribute that allows a method to call itself. The method that calls
itself is said to be recursive method.
The classic example of recursion is the computation of the factorial of a number.
class Factorial
{ int fact(int n)
{
if(n==1) return 1;
return (fact(n-1)*n);
}
}
class Recursion
{
public static void main(String ar[])
{
Factorial f=new Factorial();
System.out.println(“Factorial of 5 is”+ f.fact(5));
}
}
Output above program: Factorial of 5 is 120
Nested & inner classes:
It is possible to define a class with in another class. Such classes are known as
nested classes. The scope of nested class is bounded by the scope of its enclosing
class. Thus, if class B is defined with in class A, then B is known to A, but not
outside of A. A nested class has access to the members, including private members,
of the class in which it is nested. However, the enclosing class does not have access
to the members of the nested class.
There are two types of nested classes: static and non-static. A static nested
class is one which has the static modifier applied. Because it is static, it must access
the members of its enclosing class through an object. That is, it can not refer to
members of its enclosing class directly.
The most important type of nested class is the inner class. An inner class is a non-
static nested class. It has access to all of the variable and methods of its outer class
and may refer to them directly.
Example:
class Outer
{
int outer_x=10;
void outerMethod()
{
System.out.println(“In Outerclass Method”);
Inner in=new Inner();
In.innerMethod();
}
class Inner
{
void innerMethod()
{
System.out.println(“In Innerclass Method”);
System.out.println(“outer class variable:”+outer_x);
}
}
}
class Display
{
public static void main(String ar[])
{
Outer out=new Outer();
Out.outerMethod();
}
}
Output:
In Outerclass Method
In Innerclass Method
outer class variable: 10
String Handling
A String is a sequence of characters. In java, Strings are class objects and
implemented using two classes, namely, String and StringBuffer. A java string is an
instantiated object of the String class. A java String is not a character array and is
not NULL terminated. Strings may be declared and created as follows:
String stringname= new String(“string”);
String name=new String(“kanth”); is same as
String name=”kanth”;
like arrays, it is possible to get the length of string using the length method of the
String class.
int len = name.length();
Java string can be concatenated using the + operator.
eg: String firstname = ”sri”;
String lastname = ”kanth”;
String name = firstname+lastname;
( or )
String name = ”sri”+”kanth”;
String Arrays:
we can also create an use arrays that contain strings. The statement,
String names[]=new String[3];
will create an names array of size 3 to hold three string constants.
String Methods: (Methods of String class)
The String class defines a number of methods that allow us to accomplish a variety
of string manipulation tasks.
Method Task
s2=s1.toLowerCase() converts the String s1 to all lowecase
s2=s1.toUpperCase() converts the String s1 to all Uppercase
s2=s1.replace(„x‟,‟y‟); Replace all appearances of x with y
s2=s1.trim(); Remove white spaces at the beginning and end of String s1
s1.equals(s2); Returns „true‟ if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns „true‟ if s1=s2, ignoring the case of characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns –ve if s1<s2, positive if s1>s2, and zero if s1 is equal s2
s1.concat(s2) Concatenates s1 and s2
s1.indexOf(„x‟) Gives the position of the first occurrence of „x‟ in string s1
s1.indexOf(„x‟,n) Gives the position of „x‟ that occurs after nth position in the-
string s1
//Alphabetical ordering of strings
class StringOrdering
{
public static void main(String args[])
{
String names[]={“india”,”usa”,”australia”,”africa”,”japan”};
int size=names.length;
String temp;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(names[j].compareTo(names[i])<0)
{
temp=names[i];
names[i]=name[j];
names[j]=temp;
}
}
}
for(int i=0;i<size;i++)
System.out.println(names[i]);
}
}
above program produces the following result
africa
australia
india
japan
usa