Java Unit-2
Java Unit-2
[Link]. II Semester IV
Paper - I
UNIT – 2
1 Control Structure:
2.1.1 if Statement:
The “if statement” is also called as conditional branch statement.
Syntax:
if (condition)
{
Statement 1; Statement 2;
...
}
else
{
Statement 3;
Statement 4;
... }
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
If the condition is true then statement block will be executed. If the condition is false then statement
block will omit and statement-a will be executed.
{
Statement block-B;
}
Statement-a;
If the condition is true then Statement Block-A will be executed. If the condition is false then Statement
Block-B will be executed. In both cases the statement-a will always executed.
import [Link].*;
class NumTest
{
public static void main (String[] args) throws IOException
{
int Result=11;
[Link]("Number is"+Result);
if ( Result < 0 )
{
[Link]("The number "+ Result +" is negative");
}
else
{
[Link]("The number "+ Result +" is positive");
}
}
}
For example: write a program to check whether the number is divisible by 2 or not.
import [Link].*;
class divisorDemo
{
public static void main(String[] args)
{
int a =11;
if(a%2==0)
{
[Link](a +" is divisible by 2");
}
else
{
[Link](a+" is not divisible by 2");
}
}
}
Output:
{
If(condition2)
{
Statement block-A;
}
else
{
Statement block-B;
}
}
else
{
Statement block-C;
}
Statement- a;
If the condition1 is true then it will be goes for condition2. If the condition2 is true then statement block-
A will be executed otherwise statement block-B will be executed. If the condition1 is false then
statement block-C will be executed. In both cases the statement-a will always executed.
// Nested IF For example:Write a program to find out greatest number from three numbers.
[Link]("Enter C ? ");
text= [Link]();
c= [Link](text);
if (a>b)
{
if (a>c)
[Link]("a is gratest");
else
[Link]("c is gratest");
}
else
{
if (b>c)
Shivaji Science College, Nagpur
BSC-II Semester-IV
[Link]("b is gratest");
else
[Link]("c is gratest");
}
}
}
default:
statement block-default;
break;
}
statement a;
The condition is byte, short, character or an integer. value-1,value-2,value-3,…are constant and is called
as labels. Each of these values be compared with condition. Statement block1, Statement block2,
Statement block3,..are list of statements which contain one statement or more than one statements. Case
label is always end with “:” (colon).
-Check balance
-withdraw amount
-deposit amount
For example:
//program to demonstrate switch statment
import [Link].*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=[Link](args[0]);
[Link]("Menu");
[Link]("1:check balance");
[Link]("2:withdraw amount... plz enter choice and amount");
[Link]("3:deposit amount... plz enter choice and amount");
[Link]("4:exit");
switch(ch)
{
case 1:[Link]("Balance is:"+bal);
break;
case 2:int w=[Link](args[1]);
if(w>bal)
{
[Link]("Not sufficient balance");
}
bal=bal-w;
[Link]("Balance is"+bal);
break;
case 3:int d=[Link](args[1]);
bal=bal+d;
[Link]("Balance is"+bal);
break;
default:break;
}
}
}
/*d=-d;
r1=-b+[Link](d)/(float)2*a;
r2=-[Link](d)/(float)2*a;
[Link]("Root1 = "+r1+" Root2 = "+r2);*/
break;
}
}
}
{
InputStreamReader reader = new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
int n, fact=1;
[Link]("Enter the number? ");
import [Link].*;
class series1
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=0;
[Link]("Summation of the Sequence :");
[Link](" 1 - 1/2 + 1/3 - 1/4...... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter number of terms required ?");
String minput=[Link]();
n=[Link](minput);
j=1;
for(i=1;i<=n;i++)
{
sum=sum+j*(1.0/(float)i);
j=-j;
}
[Link]("Sum of sequence upto "+n+"terms is "+sum);
}
}
import [Link].*;
class series2
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=0;
[Link]("Summation of the Sequence :");
[Link](" 2/9 - 5/13 + 8/17 - 11/21...... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
j=-j;
}
[Link]("Sum of sequence upto "+n+"terms is "+sum);
}
}
import [Link].*;
class series3
{
public static void main(String args[]) throws IOException
{
int i,j,k,n;
double sum=1;
[Link]("Summation of the Sequence :");
[Link]("1 + 1/1! + 1/2! + 1/3! + ..... ?");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
// Program to find sum of digits and reverse of digits using while loop
import [Link].*;
import [Link].*;
class sumofdigit
{
public static void main(String args[]) throws IOException
{
int num, rev=0,digit,sum=0,temp;
[Link]("sum of digit :");
[Link]("e.g. 1234=10");
BufferedReader in;
in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter Number ?");
String ainput=[Link]();
num=[Link](ainput);
temp=num;
while (num!=0)
{
digit= num-(num/10)*10;
sum=sum+digit;
rev=rev*10+digit;
num=num/10;
}
[Link]("Inputted number is "+ temp);
[Link]("Sum of digit is "+sum);
Syntax:
do
{
Statement block;
}
Shivaji Science College, Nagpur
BSC-II Semester-IV
While(condition);
In program,when we use the do-while loop, then in very first attempt, it allows us to get enter in loop and
execute that loop and then check the condition.
Loops perform a set of operations continually until the control variable will not satisfy the condition. But
if we want to break the loop, then Java provides command to jump from one statement to end of loop or
beginning of loop as well as jump out of a loop.
“break” keyword use for exiting from loop and “continue” keyword use for continuing the loop.
Following statements shows the exiting from loop by using “break” statement.
do-while loop:
do
{
………………
………………
if(condition)
{
break;//exit from if loop and do-while loop
}
……………..
……………..
}
While(condition);
Following statements shows the continuing the loop by using “continue” statement.
do-while loop:
do
{
………………
………………
if(condition)
{continue;//continue the do-while loop
}
Shivaji Science College, Nagpur
BSC-II Semester-IV
……………..
……………..
}
While(condition);
Output:
$
$$
$$$
$$$$
$$$$$
$$$$$$
$$$$$$$
$$$$$$$$
$$$$$$$$$
End of program
2.5 Classes
A class is a set of objects with similar properties (attributes), common behavior (operations), and common
link to other objects. The objects are variable of type class. A class is a collection of objects of similar type.
Classes are user defined data . Once the class has been defined, we can make any number of objects
Shivaji Science College, Nagpur
BSC-II Semester-IV
belonging to that class. Each object is related with the data of type class with which they are formed. As we
learned that, the classification of objects into various classes is based on its properties (States) and behavior
(methods).
Objects are instances of the Class. Classes and Objects are very much related to each other. Without objects
you can't use a class.
Class Declaration
class classname
{
// variable declaration
dataType1 fieldName1;
dataType2 fieldName2;
.
returnDataType1 methodName1(arguments)
{
//body of method…
}
returnDataType2 methodName2(arguments)
{
//body of method…
}
.
}
Class Rectangle
{
int length;
int breadth;
}
2.5.2 Methods Declaration :Methods are declared inside the class immediately after the instance variable
declaration. It describes the operations to be performed on data.
returnDataType1 methodName1(arguments)
{
//body of method…
}
Example :
Class Rectangle
{
int length, breadth;
void getData(int x, int y) //method declaration
{
length=x;
breadth=y;
}
Shivaji Science College, Nagpur
BSC-II Semester-IV
Example :
Rectangle rect1; // declare the object
rect1 = new Rectangle(); // create object
OR
Rectangle rect1 = new Rectangle();
In program,
DemoAddMethod obj1=new DemoAddMethod ();
[Link]();
[Link]();
obj1.show_data();
In the first line we created an object.
Shivaji Science College, Nagpur
BSC-II Semester-IV
The three methods are called by using the dot operator. When we call a method the code
inside its block is executed.
The dot operator is used to call methods or access them.
class DemoAddMethodParameter
{
private int a,b,c;
public void read(int x, int y)
{
a=x;
b=y;
}
public void add()
{
c=a+b;
}
public void show_data()
{
[Link]("C =" +c);
}
}
class DemoAddMethodParameter1
{
public static void main(String args[])
{
DemoAddMethodParameter obj1=new DemoAddMethodParameter ();
[Link](30,35);
[Link]();
obj1.show_data();
}
}
class DemoAddMethodReturn1
{
public static void main(String args[])
{
int c;
DemoAddMethodReturn obj1=new DemoAddMethodReturn ();
[Link](30,35);
c=[Link]();
[Link]("C =" +c);
}
}
2.5.8 Method Overloading
Method overloading means method name will be same but each method have different parameter lists and
different definations
class DemoAddMethodOverloading
{
int a=10,b=35,c;
}
public void add(int x, int y)
{
a=x;
b=y;
c=a+b;
[Link]("C =" +c);
}
class DemoAddMethodOverloading1
{
public static void main(String args[])
{int k;
DemoAddMethodOverloading obj1=new DemoAddMethodOverloading ();
[Link]();
[Link](24,25);
[Link]("Sum =" +[Link](45));
}
}
2.5.9 Passing Objects as Parameters
class DemoAddMethodPassingObject
{
private int a,b,c,m;
public void read1(int x, int y)
{
a=x;
b=y;
}
public void add()
{
c=a+b;
[Link]("Sum =" +c);
}
class DemoAddMethodPassingObject1
{
public static void main(String args[])
{
DemoAddMethodPassingObject obj1=new DemoAddMethodPassingObject();
DemoAddMethodPassingObject obj2=new DemoAddMethodPassingObject();
obj1.read1(30,35);
Shivaji Science College, Nagpur
BSC-II Semester-IV
[Link]();
obj2.read2(obj1);
[Link]();
}
}
Example :
we are creating the no argument constructor in the Bike class. It will be invoked at the time of object
creation.
class Bike1
{
Bike1()
{
[Link]("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
void display()
{
[Link](id+" "+name+" "+age);
}
Student6(Student6 s)
{
id = [Link];
name =[Link];
}
void display()
{[Link](id+" "+name);
}
id = i;
name = n;
}
Student7()
{
}
void display()
{
[Link](id+" "+name);
}
[Link]();
[Link]();
}
}
Student9(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[])
{
[Link]();
Student9 s1 = new Student9 (1 ,"Vijay");
Student9 s2 = new Student9 (2 ,"Ganesh");
Student9 s3 = new Student9 (3 ,"Samay");
[Link]();
[Link]();
[Link]();
}
}
2.6 Array : The array, is a fixed-size sequential collection of elements of the same data type.
Example:
double[] salary;
or
double salary[];
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:
Syntax :
Example:
Following statement declares an array variable, salary, creates an array of 10 elements of double type and
assigns its reference to salary:
double[] salary= new double[10];
Example:
How to create, initialize and process arrays:
public class TestArray
{
public static void main(String[] args) {
double[] salary = {1.9, 2.9, 3.4, 3.5};
void show_sum()
{ int sum=0;
for(int i=0;i<sz;i++)
sum=sum+a[i];
[Link](" Array sum is "+sum);
}
}
class srarray1
{
public static void main(String args[]) throws IOException
{ SrArray a1;
a1=new SrArray();
int count;
InputStreamReader reader=new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text;
[Link]("\n Enter the number of elements ? ");
text= [Link]();
count= [Link](text);
[Link](count);
[Link]();
a1.show_sum();
{
int a[];
static int sz;
void bubble_sort()
{
int temp;
for(int i=0;i<sz;i++)
{
for(int j=1;j<sz-i;j++)
{ if (a[j-1]>a[j])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}
void show()
{
[Link](" Array is ");
for(int i=0;i<sz;i++)
[Link](a[i]+" ");
[Link]();
}
}
class SrarrayBubbleSort
{
public static void main(String args[]) throws IOException
{ SrArray a1;
Shivaji Science College, Nagpur
BSC-II Semester-IV
a1=new SrArray();
int count;
InputStreamReader reader=new InputStreamReader([Link]);
BufferedReader in = new BufferedReader(reader);
String text;
[Link]("\n Enter the number of elements ? ");
text= [Link]();
count= [Link](text);
[Link](count);
[Link]();
[Link]();
a1.bubble_sort();
[Link]();
}
}
You can also pass arrays to methods. For example, the following method displays the elements in array:
A method may also return an array. For example, the method shown below returns an array that is the
reversal of another array:
This two-dimensional array will have two rows and four columns. This table can store 8 integer values.
2.6.7 Initialization of two dimensional array:
We can declare a two dimensional array and directly store elements at the time of its declaration as:
int marks[][]={{80,89,65,90,87},{69,45,77,88,97},{55,66,77,88,99}};
or
int[][] A = { { 10,20,30,40 },
{ 11,22,-33,66 },
{ 55,-56,78,-45 }
};
2.6.8 Variable Size Arrays :
Java treats multidimensional array as “Arrays of Arrays”. It is possible to declare two dimensional array as
follows :
int x[][] = new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[7];
These statements creates two dimensional array having different lengths for each row.
2.7 Java String Handling :
2.7.1 Java String provides methods that can be performed on a string such as compare, concat, equals,
split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
1. char[] ch={'n','a','g','p','u','r' };
2. String s=new String(ch);
is same as:
1. String s="nagpur";
Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of
characters. String class is used to create string object.
There are two ways to create String object:
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists
in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
2) By new keyword
1. String s=new String("Welcome"); In such case, JVM will create a new string object in normal(non pool) heap
memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
Java String Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
Output :
java
strings
example
Press any key to continue . . .
2.7.1 Java String Methods : The [Link] class provides a lot of methods to work on string. By the
help of these methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
i) toUpperCase() and toLowerCase() method:
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
String s="Sachin";
[Link]([Link]());//SACHIN
[Link]([Link]());//sachin
[Link](s);//Sachin(no change in original)
ii) trim() method :
The string trim() method eliminates white spaces before and after string.
String s=" Sachin ";
[Link](s);// Sachin
[Link]([Link]());//Sachin
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
vii) concat() method
The java string concat() method combines specified string at the end of this string. It returns combined
string. It is like appending another string.
Example :
//Java String replace(char old, char new) method example
public class ReplaceExample1{
public static void main(String args[]){
x) length() method :
This method returns the length of this string.
Syntax : public int length()
import [Link].*;
public class Test{
public static void main(String args[]){
String Str1 = new String("Welcome");
String Str2 = new String("Sunil" );
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer is the subclass and Employee is the superclass. Relationship between two classes is
Programmer IS-A Employee. It means that Programmer is a type of Employee.
1) Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below flow diagram
shows that class B extends only one class A. Here A is a parent class of B and B would be a child class of
A.
Class B extends A
{
public void methodB()
{
[Link]("Child class method");
}
public static void main(String args[])
{
B obj = new B();
[Link](); //calling super class method
[Link](); //calling local method
}
}
2) Multilevel Inheritance
In Multilevel inheritance , a new class can inherit from a derived class, thereby making this derived class
the base class for the new class. As you can see in flow diagram C is subclass or child class of B and B is a
child class of A.
Example :
Class Y extends X
{
Shivaji Science College, Nagpur
BSC-II Semester-IV
Class Z extends Y
{
public void methodZ()
{
[Link]("class Z method");
}
3) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In diagram, class B,C and D inherits
the same class A. A is parent class (or base class) of B,C & D.
4) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) from more than one base
class. The problem with “multiple inheritance” is that the derived class will have to manage the dependency
on two base classes. Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritance is supported in C++.
5) Hybrid Inheritance
Hybrid inheritance is a combination of Single and Multiple inheritance. By using interfaces you can
have multiple as well as hybrid inheritance in Java.
class InherDemoVariable
{
public static void main(String args[] )
{
C c1=new C();
c1.i=100;
c1.j=200;
c1.k=300;
[Link]("Value of i in class C = "+c1.i);
[Link]("Value of j in class C = "+c1.j);
[Link]("Value of k in class C = "+c1.k);
}
}
//Program to demonstrate the inheritance of variables hiding
class A
{
int i=11;
}
class B extends A
{
class C extends B
{
int i=33;
}
class InherDemoVariableHiding
{
public static void main(String args[] )
{
C c1=new C();
[Link]("Value of i in class C = "+c1.i);
}
}
class B extends A
{
class C extends B
{
String z="Good Evening ";
void show()
{
[Link](super.z);
[Link](z);
}
}
class InherDemoVariableSuper
{
public static void main(String args[] )
{
C c1=new C();
[Link]();
}
}
Output :
Good Morning
Good Evening
Press any key to continue . . .
class Box
{
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
[Link]("Volume is : " + width * height * depth);
}
}
}
class C extends B
{
void show3()
{
[Link]("Good Evening ");
}
}
class InherDemoMethod
{
public static void main(String args[] )
{
C c1=new C();
c1.show1();
c1.show2();
c1.show3();
}
}
Output:
Good Morning
Good Afternoon
Good Evening
Press any key to continue . . .
2.8.3 Overriding : It will take place when method in subclass and the corresponding method in super
class have the same signature and should have the same return type. Otherwise the complier will display
error message. The compiler picks an overloaded method during the compilation stage itself. This is
called early binding. In overridden method, java virtual machine dynamically select the correct version
of an overridden method to be executed. This is called as late binding(Run time Polymorphism).
Syntax :
super.method_name(argument lists);
{
void show(String s)
{
[Link]("Class A : "+s);
}
}
class B extends A
{
void show(String s)
{
[Link](s);
[Link]("Class B : "+s);
}
}
class InherDemoOverridingMethod
{
public static void main(String args[] )
{
A a1=new A();
[Link]("Hello");
B b2=new B();
[Link]("Hi");
}
}
Output :
Class A : Hello
Class A : Hi
Class B : Hi
Press any key to continue . . .
Each non-abstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations
for the draw and resize methods:
void draw() {
...
}
void resize() {
...
}
}
2.8.6 FINAL classes : A class that is declared with the final modifier can not be extended.
2.8.7 this keyword : This is a reference variable that refers to the current object.
2.9 Interfaces :
Interface is just like class. The difference is that interface define only abstract methods and constants.
Syntax
Interface InterfaceName
{
//variable declaration
static final dataType VariableName = value
//method declaration
returnType methodName1(parameter list)
}
Example :
interface Area
{
final static float pi=3.142f;
float compute(float x, float y)
void show();
}
Class Interface
1. The members of class can be constant or The members of interface are always declared
variables. as constant.
2 The class definition can contain code All methods in an interface are abstract. Which
Shivaji Science College, Nagpur
BSC-II Semester-IV
for each of its methods means all methods must be empty; no code
implemented.
Interfaces are used as “super classes” whose properties are inherited by classes.
Syntax:
class ClassName implements InterfaceName
{
Body of classname
}
Syntax:
class ClassName extends superclass implements InterfaceName1,…
{
Body of classname
}
Example :
//Program to demonstrate the Interface concept
interface Area
{
static final float pi=3.14F;
float compute(float x, float y);
}
class InterfaceTest
{
public static void main(String args[] )
{
Rectangle rect = new Rectangle();
Circle cir= new Circle();
Area area;
area=rect;
[Link]("Area of Rectangle is "+ [Link](10,20));
area=cir;
[Link]("Area of Circle is "+ [Link](10,0));
}
}
class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void putNumber()
{
[Link]("Roll No. : "+ rollNumber);
}
}
paper2=m2;
}
void putMarks()
{
[Link]("Marks Obtained ");
[Link]("Paper 1 : "+ paper1);
[Link]("Paper 2 : "+ paper2);
}
}
Roll No. : 10
Marks Obtained
Paper 1 : 45.5
Paper 2 : 55.8