CP-2 Notes (Java) Mumbai University
CP-2 Notes (Java) Mumbai University
Computer Programming II
Computer
Programming2
For F.E All
Branches By
Shalini Puri
Prof. Shalini Puri 1
Ramrao Adik Institute of Technology F.E.Computer Programming II
INDEX
1. Introduction to Java ................................................................................................. 7
1.1 Why is java popular for the Internet ................................................................... 7
1.2 Features of Java: ................................................................................................. 7
1.3 How Java program runs ...................................................................................... 9
2. Object Orientation .................................................................................................. 11
2.1 Features of Object Oriented Language: ............................................................ 11
3. Java Language Basics ............................................................................................. 13
3.1 Introduction:...................................................................................................... 13
3.2 Basic Building Blocks: ..................................................................................... 13
4. Control Structures .................................................................................................. 20
4.1 Simple If statement: .......................................................................................... 20
4.2 If-Else Statement:.............................................................................................. 20
4.3 Switch-Case Statement: .................................................................................... 21
5. Loops ........................................................................................................................ 23
5.1 For Loop: .......................................................................................................... 23
5.2 While Loop: ...................................................................................................... 24
5.3 Do-While Loop: ................................................................................................ 25
5.4 Break and Continue Statement: ........................................................................ 25
5.5 Exercise:............................................................................................................ 27
6. Functions.................................................................................................................. 28
6.1 Methods in Java: ............................................................................................... 28
6.2 Recursive Functions:......................................................................................... 28
6.3 Exercise:............................................................................................................ 29
7. Arrays....................................................................................................................... 32
7.1 Creating an Array:............................................................................................. 32
7.2 Array Index Checking:...................................................................................... 32
7.3 SystemArraycopy():.......................................................................................... 33
7.4 Multidimensional Arrays: ................................................................................. 34
7.5 Exercise:............................................................................................................ 34
8. Introduction Classes: .............................................................................................. 41
8.1 General form of a Class: ................................................................................... 41
8.2 Declaring and Creating Objects:....................................................................... 41
8.3 Accessing Members:......................................................................................... 42
8.4 Introducing Methods:........................................................................................ 42
8.5 Constructors: ..................................................................................................... 44
8.6 Array of Objects:............................................................................................... 45
8.7 Static Variables and Static Methods: ................................................................ 46
9. Wrapper Classes ..................................................................................................... 48
9.1 Introduction:...................................................................................................... 48
9.2 Class Integer: .................................................................................................... 48
1. Introduction to Java
Java was developed at Sun Microsystems in 1991, by a team comprising James
Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan as its members.
The language was initially called as Oak. It was later termed as Java. Java was launched
on 23 May, 1995. The Java software was released as a development kit. The first two
versions were named as JDK1.0 and JDK1.1. In 1998 while releasing the next version
Sun Microsystems changed the name from Java Development Kit JDK) to Software
Development Kit (SDK) and the version was referred as Java 2 SDK 1.2. Now we are
using JDK 6.
1.2.1 Simple:
Java is simple to learn and use. In Java it is easy to write and debug programs because
certain complex features like operator overloading, multiple inheritance, pointers, and
explicit memory de allocation are not present in Java language.
1.2.3 Multithread
Java is a programming language designed for the distributed environment of the internet
and helps to write interactive programs where in multiple tasks can be performed
simultaneously thus making it a robust programming language. Java is inherently multi-
threaded as there can be multiple executing threads in a single Java program. For
example Java program can run three applets on the same page, provided that each applet
gets equal time from the CPU.
1.2.4 Interpreted:
Java is an interpreted language. When we write a program it is compiled into a class file.
The interpreter executes this class file. However the interpreters 30 years ago were
interpreting the statement in textual form. It was a very slow process. Java interprets byte
code hence it is considerably fast. Java gets all the advantages of interpretation without
suffering from major disadvantages..
binary files are also platform-independent and can run on multiple problems without the
need to recompile the source. How does this work? Java binary files are actually in a
form called byte codes. Byte codes are a set of instructions that looks a lot like some
machine codes, but that is not specific to any one processor. Normally, when you compile
a program written in C or in most other languages, the compiler translates your program
into machine codes or processor instructions. Those instructions are specific to the
processor your computer is running—so, for example, if you compile your code on a
Pentium system, the resulting program will run only on other Pentium systems. If you
want to use the same program on another system, you have to go back to your original
source, get a compiler for that system, and recompile your code.
1.2.7 Distributed
Java is a distributed language as it can be used to create applications to communicate
over the network. Java can communicate over the network because it supports TCP/IP
(Transmission Control Protocol/Internet Protocol). The TCP/IP is a network
communication protocol.
1.2.8 Dynamic
During run time of a Java program, the relevant information is required that is used to
verify and resolve access to objects. This concept of providing run time information is
referred to as dynamically linking the code. This feature of Java adds strength to the
applet environment in which all fragments of bytecode are dynamically updated on a
running system.
Because the Java VM is available on many different operating systems, the same .class
files are capable of running on Microsoft Windows, the Solaris TM Operating System
(Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java Hotspot virtual
machine, perform additional steps at runtime to give your application a performance
boost. This includes various tasks such as finding performance bottlenecks and
recompiling (to native code) frequently used sections of code
Compilation in Java:
2. Object Orientation
2.1 Features of Object Oriented Language:
2.1.1 Encapsulation:
The process of binding code and data together in the form of a capsule is Encapsulation.
It is the mechanism that binds together code and data. It manipulates, and keeps it safe
from outside interference and misuse. The data is not accessible to the outside world and
only those functions that are wrapped in the class can access it. These functions provide
the interface between the object’s data and the program. The insulation of the data from
the direct access by the program is called data hiding.
In OOP, code and data are merged into an object so that the user of an object can never
peek inside the box. This is defined as encapsulation (Object is a capsule encapsulating
data and behavior). All communication to it is through messages (function calls which we
use to communicate to the object). Messages define the interface to the object.
Everything an object can do is represented by its message interface. Therefore, we need
not know anything about what is in the object when we use it.
2.1.4 Inheritance
The feature by which one class acquires the properties and functionalities of another
class is Inheritance. Inheritance is the process by which one class acquires the properties
and functionalities of another class. This is important because it supports the concept of
hierarchical classification.. Inheritance provides the idea of reusability of code and each
sub class defines only those features that are unique to it.
2.1.5 Polymorphism:
The feature that allows the same interface to be used for a general set of actions
Polymorphism is a feature that allows one interface to be used for a general class of
actions. An operation may exhibit different behavior in different instances. The behavior
depends on the types of data used in the operation. It plays an important role in allowing
objects having different internal structures to share the same external interface.
Polymorphism is extensively used in implementing inheritance.
Ex:
add(int a, int b)
add(int a, float b, int c)
add(int a, int b, float c, double d)
Here different datatypes are being added using the same interface.
3.1 Introduction:
In our first program, we will find the area of a circle with radius 5.
class area
{
public static void main(String args[])
{
int r;
r=5;
System.out.println(3.14*r*r);
}
}
If you run the program, you will get the following output:
/*78.5*/
The structure of a very simple Java program can be explained as follows:
1. A program is written in a file named area.java
2. The file contains a class name as area by rule.
3. The class contains the main. It has to be declared with String arguments.
4. The method main contains declaration and program statements.
5. Java application begins execution at method main.
Integer Constant:
Integer can be expressed in three possible notations i.e. in octal, decimal and
hexadecimal. We use integer constants in decimal form. These constants are either
positive or negative. Plus sign is optional.
In decimal: 23, -55, +2367.
In Octal: 023, 055, 02367
In Hexdecimal : 0x23, 0x5B, 0XXFF23
Real Constant:
The Real and floating point constants are written in either fixed point or scientific
notation. Following are examples of valid real constants:
In Fixed: 2.3, -5.54, 236.7
In Scientific: 0.2e3, -5E5, 2E67
Here for both mantissa and exponent sign is optional. Use of capital “E” is allowed in
place of small “e”.
Character Constant:
If we enclose a single character in single quotes it forms simple character constants.
Example: ‘A’,,’B’,’*’
String Constant:
A collection of characters is known as string. If we put characters in a pair of double
quotes it forms a string constant. Example: “Hello”, “World”.
3.2.1 Variables:
The variables are used to store values of constants. Any programming language allows us
to change, manipulate the values stored in a variable. There are some rules that are to be
followed while creating a variable name:
1. A variable name is a combination of 1 to 31 alphabets, digits or underscores. Do not
write unnecessary long names as it adds up to your typing effort.
2. The first character in a variable name should be an alphabet.
3. No commas or blanks are allowed in the variable name.
4. No special symbols other than underscores are allowed in a variable name.
5. Try giving some relevant variable names.
Example: si_int,m_hra,pop_e_89
Declaration of Variable:
Variables are declared with the help of a data type . a declaration int j tells the compiler
that j is a variable of type int (integer). If we have more than one variable of type int then
they are separated by commas. int i, j, k; Java or any other programming language aso
allows us to assign values to the variables. int marks = 100;
3.2.2 Keywords:
abstract const Finally implements public this case Switch
boolean continue For instanceof throw transient do While
break float If null short void False Catch
byte default Import int super volatile return Interface
char else Long private static true final New
class extends Goto protected try native throws
3.2.3 Operators:
Operators can perform operations on operands. Operands may be one, two or three.
Operands are either variables or constants. The operands which take single operand are
called unary operator. Those taking two are known as binary operators and one having
three operands is called as ternary operator. Most of the operators are binary operators
few are unary while there is only one ternary operator.
a*b =250
a/b =2
a%b =5*/
{
int a =5,b=5;
System.out.println("a++ = "+(a++));
System.out.println("++b = "+(++b));
System.out.println("a-- = "+(a--));
System.out.println("--b = "+(--b));
}
}
/*a++ = 5
++b = 6*/
a-- = 6
--b = 5*/
}
}
/*a =25
b =10
c =67
a < b =false
a > b =true
a==c =false
a<=c =true
a>=b =true
a+b!=c =true
a+b==c =false*/
5*/
4. Control Structures
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program. Java’s program control
{
if(a>c)
{
System.out.println("a ="+a);
}
else
{
System.out.println("c="+c);
}
}
else
{
System.out.println("b="+b);
}
}
}
/*Largest value is :
b=712*/
statement is encountered execution branches to the first line of code that follows the
entire switch statement. This has effect of jumping out of the switch.
The switch statement is used for designing menu driven interactive programs.
class Switch
{
public static void main(String args[])
{
int x=Integer.parseInt(args[0]);
int y= Integer.parseInt(args[1]);
String s =args[2];
char op =s.charAt(0);
switch(op)
{
case '+': System.out.println(x +"+" + y +"="+ (x+y));
break;
case '-': System.out.println(x +"-" + y +"="+ (x-y));
case '/': System.out.println(x +"/" + y +"="+ (x/y));
break;
case '%': System.out.println(x +"%" + y +"="+ (x%y));
break;
}
}
}
/*C:\ava\jdk1.5.0_04\bin>java Switch 23 45 +23+45=68
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 -
23-45=-22
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 /
23/45=0
C:\Java\jdk1.5.0_04\bin>java Switch 23 45 %
23%45=23*/
5. Loops
Java‘s iteration statements are for, while, do-while. These statements create what we
commonly call loops.
}
System.out.println("Sum ="+(sum));
}
}
/*Sum =145*/
break;
System.out.print(i +" ");
}
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Break.java
C:\Java\jdk1.5.0_04\bin>java Break
123456789 */
5.5 Exercise:
1. Write a program display table for 15.
2. Write a program for calculating the squares and cubes of the first 10 numbers.
3. Write a program to find the number of and sum of all integers greater than 100 and
less than 200 that are divisible by 7.
4. Write a program to find out first 10 prime numbers.
5. Write a program to find out whether a number is an Armstrong number or not.
6. Write a program to find out whether a number is a palindrome or not.
7. Write a program to find out the factorial of first 10 numbers.
8. Write a program to calculate the Permutation and Combination.
Pr = (n!/r!)
Cr =(n!/r!(n-r)!
9. Write a program to implement x raise to n.
10. Write a program to find out sine series
11. Write a program to find out cosine series
12. Generate Pascal’s triangle.
13. Find the sum of sequence 1 – ½+ 1/3 -1/4+ 1/5.
14. Find the sum of sequence 1 + 1/1! + ½! + 1/3!
6. Functions
Functions are small pieces of code doing a particular task. Functions are called
methods in Java.
class Recursive
{
public static void main(String args[])
{
int n=5;
int f;
f=fact(n);
System.out.println("Factorial is = "+ f);
}
public static int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Recursive.java
C:\Java\jdk1.5.0_17\bin>java Recursive
Factorial is = 120*/
6.3 Exercise:
1. Write a program to print the Fibonacci series using recursive function.
class Fibonacci
{
public static void main(String args[])
{
int n=8;
System.out.print("The fibonacci series is :");
for(int i=0;i<n;i++)
{
System.out.print(fib(i)+" ");;
}
}
public static int fib(int n)
{
if(n==0 || n==1)
return(1);
else
return(fib(n-1)+fib(n-2));
}
}
C:\Java\jdk1.5.0_17\bin>javac Fibonacci.java
C:\Java\jdk1.5.0_17\bin>java Fibonacci
The fibonacci series is :1 1 2 3 5 8 13 21
2. Write a program to print the Reverse and sum of integers using recursive
function.
class Parameter
{
public static void main(String args[])
{
int n=1234,s=0;
System.out.print("The reverse of number is :");
s=reverse(n,0);
System.out.println();
System.out.println("Sum of Digits is = "+ s);
}
public static int reverse(int x,int y)
{
int d;
if(x==0)
return(y);
else
{
d=x%10;
System.out.print(d+" ");
y=y+d;
}
return(reverse(x/10,y));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Parameter.java
C:\Java\jdk1.5.0_17\bin>java Parameter
The reverse of number is :4 3 2 1
Sum of Digits is = 10*/
if(a<b)
System.out.println(gcd(b,a));
else
System.out.println(gcd(a,b));
}
}
/*C:\Java\jdk1.5.0_17\bin>javac GCD.java
C:\Java\jdk1.5.0_17\bin>java GCD
27*/
7. Arrays
An array is a group of contiguous or related data items that share a common name. For
instance we can define an array name salary to represent a set of salaries of a group of
employees. A particular value is indicated by writing a number called index number or
subscript in brackets after the array name. For example, salary[10]
represents the salary of the 10th employee. While the complete set of values is referred to
as an array, the individual values are called elements. Arrays can be of any variable type.
The ability to use a single name to represent a collection of items and to refer to an item
by specifying the item number enables us to develop concise and efficient programs. For
example, a loop with the subscript as the control variable can be used to read the entire
array, perform calculations and print out the results.
int n=num.length;
System.out.println("The List is :");
for(int i=0;i<n;i++)
{
System.out.println(num[i]+" ");
sum+=num[i];
}
System.out.println("Sum ="+(sum));
}
}
/*The List is :
55 40 80 65 71
Sum =311*/
7.3 SystemArraycopy():
If we want to make a true copy of an array we must make a new array of the same
length as the original and copy overall values:
double [] prices = new double[data.length];
for(int i=0;i<data.length;i++)
prices[i] = data[i];
Instead of the for loop you can also use the static System.arrayCopy method. The
method can be used to copy any portion of an array into another array.
System.arrayCopy (from,fromStart,to,toStart,count);
To copy the entire data array into the prices array we say:
System.arrayCopy(data,0,prices,0,data.length);
class ArrayCopy
{ public static void main(String[] args)
{ int x[] = {11,22,33,44,55};
int y[] = new int[5];
System.arraycopy(x,0,y,0,5);
System.out.println("Array y after copying is :");
for(int i=0;i<5;i++)
{System.out.print(" " + y[i]);
}
}
}
/*C:\Java\jdk1.6.0_05\bin>javac ArrayCopy.java
C:\Java\jdk1.6.0_05\bin>java ArrayCopy
Array y after copying is :
11 22 33 44 55 */
The table contains a total of 12 values three in each line. We can think of this table as a
matrix consisting of four rows and three columns. Each row represent the value of sales
by a particular salesgirl and each column represents the value of sales of a particular item.
Java allows us to define such tables of items using two dimensional arrays. The table
discussed above can be represented in Java as v[4][3]. For creating two dimensional
arrays we must follow the same steps as a single dimensional array.
int myArray [ ] [ ] = new int [3][4];
7.5 Exercise:
7.5.1 Linear Search:
class search
{
public static void main(String args[])
{
int x[]= {23,55,14,18,67};
int r, n = 5,i;
r=Integer.parseInt(args[0]);
System.out.print("List of elements : ");
for(i=0;i<n;i++)
{
System.out.print(x[i]+ " ");
}
System.out.println();
for(i=0;i<n;i++)
{
if(r==x[i])
{
System.out.println("Element " +r+" found at " + i +" position");
break;
}
}
if(i==n)
System.out.println("Element not found");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac search.java
C:\Java\jdk1.5.0_17\bin>java search 18
List of elements : 23 55 14 18 67
Element 18 found at 3 position
C:\Java\jdk1.5.0_17\bin>java search 17
List of elements : 23 55 14 18 67
Element not found*/
int ROWS=4,COLS=4;
int x[][]=new int[ROWS][COLS];
int y[][]=new int[ROWS][COLS];
int z[][]=new int[ROWS][COLS];
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
x[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
y[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
z[i][j]=(x[i][j]+y[i][j]);
}
}
System.out.println("The X array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+x[i][j]);
}
System.out.println();
}
System.out.println("The Y array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+y[i][j]);
}
System.out.println();
}
System.out.println("The Z array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+z[i][j]);
}
System.out.println();
}
}
}
/*C:\Java\jdk1.5.0_17\bin>javac matadd.java
C:\Java\jdk1.5.0_17\bin>java matadd
The X array is :
1234
5678
9 10 11 12
13 14 15 16
The Y array is :
1234
5678
9 10 11 12
13 14 15 16
The Z array is :
2468
10 12 14 16
18 20 22 24
26 28 30 32*/
{
for(int j=0;j<COLS;j++)
{
y[i][j]=k+1;
k++;
}
}
for(int i=0,k=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
z[i][j]=0;
for(k=0;k<ROWS;k++)
{
z[i][j]+=(x[i][k]*y[k][j]);
}
}
}
System.out.println("The X array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+x[i][j]);
}
System.out.println();
}
System.out.println("The Y array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+y[i][j]);
}
System.out.println();
}
System.out.println("The Z array is :");
for(int i=0;i<ROWS;i++)
{
for(int j=0;j<COLS;j++)
{
System.out.print(" "+z[i][j]);
}
System.out.println();
}
}
}
/*The X array is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The Y array is :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
The Z array is :
90 100 110 120
202 228 254 280
314 356 398 440
426 484 542 600*/
8. Introduction Classes:
Class can be considered as a user defined data type. It is a template for the object to be
created. It holds some data. Let us take an example of time. It consists of hours, minutes
and seconds. To store these quantities, we need three different fields (variables). But
together they constitute a single object.
hour=a;
minute=b;
second=c;
}
void putdata()
{
System.out.println("Hour = " +hour);
System.out.println("Minute = " +minute);
System.out.println("Second = " +second);
total=hour*60*60+minute*60+second;
System.out.println("Total Seconds = "+total);
}
}
class TDetail
{
public static void main(String args[])
{
Time T =new Time();
T.getdata(2,25,56);
T.putdata();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TDetail.java
C:\Java\jdk1.5.0_17\bin>java TDetail
Hour = 2
Minute = 25
Second = 56
Total Seconds = 8756*/
void convert(int n)
{
hour=n/60;
minute=n%60;
}
void display()
{
System.out.println(hour + " " +minute);
}
}
class TDetails
{
public static void main(String args[])
{
Time T =new Time();
T.convert(384);
T.display();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TDetails.java
C:\Java\jdk1.5.0_17\bin>java TDetails
6 24*/
{
System.out.println(hour + " " +minute+ " "+second);
}
}
class TMDetail
{
public static void main(String args[])
{
Time T1 =new Time();
Time T2=new Time();
T1.getdata(3,54,45);
T1.display();
T2.getdata(2,44,23);
T2.display();
Time T3=new Time();
T3=T1.convert(T2);
T3.display();
}
}
/*C:\Java\jdk1.5.0_17\bin>javac TMDetail.java
C:\Java\jdk1.5.0_17\bin>java TMDetail
3 54 45
2 44 23
6 39 8*/
8.5 Constructors:
All objects that are created must be given initial values. There are two ways of
initializing the variables of objects. The first approach uses the dot operator to access the
instance variables and then assign values to them individually. It can be tedious approach
to initialize all the variables of all the objects. The second approach takes the help of a
method like getdata to initialize each object individually
class Rectangle
{
int length,width;
Rectangle(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
return(length*width);
}
}
class RectangleArea
{
public static void main(String args[])
{
Rectangle Room=new Rectangle(10,20);
System.out.println("Area ="+Room.rectarea());
}
}
/*Area =200*/
x=Integer.parseInt(obj.readLine());
System.out.println("Enter Name :");
str=obj.readLine();
System.out.println("Enter Salary :");
f=Float.parseFloat(obj.readLine());
a[i].get(x,str,f);
}
for(i=0;i<2;i++)
{
a[i].put();
}
}
}
/*E:\\Java\jdk1.5.0_16\bin>javac EmpDetail.java
E:\Java\jdk1.5.0_16\bin>java EmpDetail
Enter Rollno :1
Enter Name :shalini
Enter Salary :5000
Enter Rollno :2
Enter Name :ajay
Enter Salary :6000
1 shalini 5000.0
2 ajay 6000.0*/
class. One of the most common examples is to have a variable that could keep a count of
how many objects of a class have been created. Java creates only one copy for a static
variable which can be used even if the class is actually instantiated. Like static variables
static methods can be called without using the objects. They are also available for use by
other classes, methods that are of general utility but do not directly affect an instance of
that class are usually declared as class methods. The static methods are called using class
names. No objects have been created for use. Static methods have several instructions:
1. They can call only call other static methods.
2. They can access only static data.
3. They cannot refer to this or super in any way.
class MathOperation
{
static int mul(int x,int y)
{
return(x*y);
}
static int divide(int x,int y)
{
return(x/y);
}
}
class MathApplication
{
public static void main(String args[])
{
int a = MathOperation.mul(3,5);
int b = MathOperation.divide(a,2);
System.out.println("b ="+b);
}
}
/*C:\Java\jdk1.6.0_05\bin>javac MathApplication.java
C:\Java\jdk1.6.0_05\bin>java MathApplication
b =7*/
9. Wrapper Classes
When we give gifts, we wrap them nicely in a box. The gift may be a doll or a toy car or
something else. The box and the glossy paper round it make it attractive. We have
worked with simple data types. Now java will wrap them and make it attractive. For this
Java provides an interesting concept of wrapper classes.
9.1 Introduction:
We have studied the basic data type float. It holds the floating-point number. Now Java
provides a class Float. As identifiers are case sensitive float and Float are different. The
new class Float is for storing floating-point. Similarly an int is wrapped in a class Integer.
It also has methods that work within this class. The other wrapper classes are Byte, Short,
Integer, Long and Double.
/*C:\Java\jdk1.5.0_17\bin>javac BWrapper.java
C:\Java\jdk1.5.0_17\bin>java BWrapper
Value of Boolean object is =true*/
10. Strings
Strings are very important part of the programming language as they are used to process
long textual/symbolic information. For example when we visit a bank to open an account
then we are asked for information such as name, address. The information we provide is
in the form of ordered sequence of characters and symbols. The ordered sequence of
characters and symbols is known as String.
S1.lastindexOf(‘x’) Give the position of the last occurrence of ‘x’ in the string s1.
class DString
{
public static void main(String args[])
{
String Name =new String("Shalini");
System.out.println("Name = " +Name);
int len=Name.length();
System.out.println("Length = "+len);
String N1=new String();
N1=Name.toLowerCase();
System.out.println("Lower Case of Name = " +N1);
String N2=new String();
N2=Name.toUpperCase();
System.out.println("Upper Case of Name = " +N2);
String N3=new String();
N3=Name.replace('i','b');
System.out.println("Upper Case of Name = " +N3);
System.out.println("Name equals N1 = " +Name.equals(N1));
System.out.println("Name equals N1 = " +Name.equalsIgnoreCase(N1));
System.out.println("Name compares N1 = " +Name.compareTo(N1));
System.out.println("N1 compares Name = " +N1.compareTo(Name));
System.out.println("Concatenate Name with string = " +Name.concat("Puri"));
System.out.println("Substring of Name = " +Name.substring(3));
System.out.println("Substring of Name = " +Name.substring(2,5));
System.out.println("Index of i in Name = " +Name.indexOf('i'));
}
}
/*Name = Shalini
Length = 7
Lower Case of Name = shalini
Upper Case of Name = SHALINI
Upper Case of Name = Shalbnb
Name equals N1 = false
Name equals N1 = true
Name compares N1 = -32
N1 compares Name = 32
Concatenate Name with string = ShaliniPuri
Substring of Name = lini
Substring of Name = ali
Index of i in Name = 4*/
10.5 Vector:
Java provides a feature of a vector class contained in the java.util package. This class
can be used to create generic dynamic array known as vector that can be used to hold
objects of any type & any number. The objects do not have to be homogeneous. Arrays
can be easily implemented as vectors. Vectors can be created like arrays as follows:
Vector intVect = new Vector( ); // Declaring without size.
Vector list = new Vector(3). // Declaring with size.
Note that a vector can be declared without specifying any size explicitly. A vector can
accommodate an unknown number of items. Even when a size is specified it can be
overlooked and a different number of items may be put into the vector. But if we
compare it with an array the size of the array has to be specified. Vectors possess a
number of advantages over arrays.
It is convenient to use vectors to store objects.
A vector can be used to store a list of objects that may vary in size.
We can add and remove objects from the list as and when required.
Important vector methods:
Method call Task Performed
list.addElement(item) Add the item specified to the list at the end
list.elementAt(10) Gives the name of the 10th object
list.size() Gives the number of objects present
list.removeElement(item) Removes the specified item from the list
list.removeElementAt(n) Removes the item stored in the nth position of the list
list.removeAllElements() Removes all elements in the list.
list.copyInto(array() Copies all items from the list to array
List.insertElementAt(item,n) Inserts the item at nth position
The above program illustrates the use of arrays, strings and vectors. This program
converts a string vector into an array of strings and displays the strings.
import java.util.*;
class LanguageVector
{
public static void main(String[] args)
{
Vector list =new Vector( );
int length = args.length;
for(int i=0;i<length;i++)
{
list.addElement(args[i]);
}
list.insertElementAt("COBOL",2);
int size =list.size( );
String listArray[] = new String[size];
list.copyInto(listArray);
System.out.println("List of languages :");
for(int i=0;i<length;i++)
{
System.out.println(listArray[i]);
}
}
}
/*C:Java\jdk1.6.0_05\bin>javac LanguageVector.java
C:\Java\jdk1.6.0_05\bin>java LanguageVector Ada Basic C++ FORTRAN Java
List of languages :
Ada
Basic
COBOL
C++
FORTRAN
Java
C:\Java\jdk1.6.0_05\bin>*/
data is being read from the standard input device, the System.in should be wrapped in the
DataInputStream object. This wrapping of the DataInputStream object allows users to
obtain the byte stream attached with the console. The following code is used to wrap the
System.in in the DataInputStream. And further a read () method is used to read the data.
import java.io.*;
class ReadChar
{
public static void main(String args[])
{
DataInputStream obj=new DataInputStream(System.in);
char ch =' ';
try
{
System.out.println("Enter Q to exit ");
while(ch!='Q')
{
ch=(char)obj.read();
System.out.println(ch);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/* C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java
C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar
Enter Q to exit
ShaliniQ
ShaliniQ*/
int i;
for(i=0;i<10;i++)
{
str[i]=obj.readLine();
if(str[i].equals("Q"))
break;
}
System.out.println("Text entered by is :");
for(i=0;i<10;i++)
{
if(str[i].equals("Q"))
break;
System.out.println(str[i]);
}
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac ReadChar.java
C:\Program Files\Java\jdk1.5.0_17\bin>java ReadChar
Enter some text, Q to quit
Welcome to the World of Java
Q
Text entered by is :
Welcome to the World of Java*/
12. Inheritance
In object oriented programming the term Inheritance refers to the fact that one class can
inherit part or all of its structure and behavior from another class. The class that does the
inheriting is said to be a subclass of the class from which it inherits. If class B is a
subclass of A we also say that class A is a super class of class B. A subclass can add to
the structure and behavior that it inherits .It can also modify inherited behavior. The
relationship between subclass and super class is shown by the below diagram.
Class A
(superclass)
Class B
(subclass)
Java uses the ‘extends’ keyword to set the relationship between a child class and a parent
class. For example to create a class named “B” as a subclass of class named “A” we
would write:
Class B extends A
{
………………..
}
B
A program that illustrates Single level Inheritance:
class Room
{
int length,breadth;
Room(int l,int b)
{
length=l;
breadth=b;
}
int area()
{
return(length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class InherTest
{
public static void main(String args[])
{
BedRoom Room1=new BedRoom(10,20,30);
int area1=Room1.area();
int volume1=Room1.volume();
System.out.println("Area = "+area1);
System.out.println("Volume = "+volume1);
}
}
/*Area = 200
Volume = 6000*/
B C D
Prof. Shalini Puri 60
Ramrao Adik Institute of Technology F.E.Computer Programming II
}
class HITest
{
public static void main(String args[])
{
Triangle T = new Triangle();
Rectangle R = new Rectangle();
T.getdata(3.5,7.5);
T.display();
R.getdata(4,4);
R.display();
}
}
/*Area of triangle is 13.125
Area of triangle is 16.0*/
12.1.1 Super:
A sub class can call a constructor method defined by its super class by the use of
the following form of super:
super(parameter list);
Here parameter list specifies any parameters needed by the constructor in the super class.
super( ) must always be the first statement executed inside a sub class’s constructor. To
see how super is used consider the following program:
Vehicle
class Vehicle
{
private String Make;
private double Milage;
Vehicle(String m,double d)
{
Make=m;
Milage=d;
}
void display()
{
System.out.println("Name of the company :"+Make);
System.out.println("Milage of the Vehicle :"+Milage);
}
}
class TwoWheeler extends Vehicle
{
private char clutch;
TwoWheeler(String m,double d,char c)
{
super(m,d);
clutch=c;
}
void display()
{
super.display();
System.out.println("Clutch present :"+clutch);
}
}
class FourWheeler extends Vehicle
{
private char Ac;
{
Result R = new Result(1,"Shalini",50,67);
R.display();
R.show();
R.showRes();
}
}
/*Roll No = 1
Name = Shalini
Marks 1 = 50.0
Marks 2 = 67.0
Result = 117.0*/
12.2.1 Protected:
The access specifier works as private for the outside world but works as public
for derived classes. Let us take the following example:
class Student
{
protected int RollNo;
protected String Name;
Student(int a,String n)
{
RollNo=a;
Name=n;
}
}
class Test extends Student
{
protected float m1,m2;
Test(int a,String m,float x,float y)
{
super(a,m);
m1=x;
m2=y;
}
void show()
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+Name);
}
}
class Result extends Test
{
float total;
Result(int a,String m,float x,float y)
{
super(a,m,x,y);
}
void showRes()
{
System.out.println("Marks 1 = "+m1);
System.out.println("Marks 2 = "+m2);
System.out.println("Result = "+(m1+m2));
}
}
class MulTest
{
public static void main(String args[])
{
Result R = new Result(1,"Shalini",50,67);
R.show();
R.showRes();
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>javac MulTest.java
C:\Program Files\Java\jdk1.5.0_17\bin>java MulTest
Roll No = 1
Name = Shalini
Marks 1 = 50.0
Marks 2 = 67.0
Result = 117.0*/
12.4 Interface:
The object oriented programming languages such as C++ allows a class to extend two or
more super classes. This is called multiple inheritance. But Multiple Inheritance is not
allowed in Java so it provides an alternate approach as interfaces to support it.
Interface is basically a kind of class. The difference is that interfaces do not specify any
code to implement these methods and data fields contain only constants. Therefore it is
the responsibility of the class that implements an interface to define the code for
implementation of these methods. The syntax for defining an interface is very similar to
that for defining a class. The general form of an interface definition is:
interface InterfaceName
{
Variable declaration;
Method declaration;
}
Here interface is the keyword and InterfaceName is any valid Java variable (just like the
class names). Variables are declared as follows:
interface Area
{
float pi =3.142F;
float compute (float x, float y);
void show( );
}
}
}
/*C:\Java\jdk1.6.0_05\bin>javac InterfaceTest.java
C:\Java\jdk1.6.0_05\bin>java InterfaceTest
Area of Rectangle :200.0
Area of Circle :314.0*/
}
void display()
{
total=part1+part2+sportWt;
putNumber();
putMarks();
System.out.println("Total Score ="+total);
}
}
class Hybrid
{
public static void main(String[] args)
{
Result student1 = new Result();
student1.getNumber(234);
student1.getMarks(27.5F,33.05F);
student1.display();
}
}
/*C:\Java\jdk1.6.0_05\bin>javac Hybrid.java
C:\Java\jdk1.6.0_05\bin>java Hybrid
Roll No :234
Marks obtained :
Part 1 =27.5
Part 2 =33.05
Total Score =66.55*/
13. Packages
The main feature of OOP is its ability to reuse the code already created. One way of
achieving this is by extending classes and implementing the interfaces but it creates a
limitation of reusing the classes within a program. What if we need to reuse classes from
other programs without physically copying them into the program under development?
This can be accomplished in Java by using what is known as packages a concept similar
to “class libraries” in other languages.
Packages area way of grouping a variety of classes and/or interfaces together. The
grouping is usually done according to the functionality. By organizing our classes into
packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused
2. In packages classes can be unique compared with classes in other packages. That is
two classes in two different packages can have the same name. They are anyways
referred by package name and the class name.
String Name;
protected String DOB;
public String Add;
public Student(int x,String n,String d,String a)
{
RollNo=x;
Name=n;
DOB=d;
Add=a;
}
public void display()
{
System.out.println("Display called from Student :");
System.out.println("Roll No :" + RollNo);
System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
}
}
package Report;
class Test extends Student
{
int m1,m2;
Test(int x,String n,String d,String a,int y,int z)
{
super(x,n,d,a);
m1=y;
m2=z;
}
public void display()
{
super.display();
System.out.println("Display called from Test :");
System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
System.out.println("Marks 1 :" + m1);
System.out.println("Marks 2 :" + m2);
}
}
package SReport;
import Report.Student;
public class Sports extends Student
{
int score;
public Sports(int x,String n,String d,String a,int s)
{
super(x,n,d,a);
score=s;
}
public void display()
{
super.display();
System.out.println("Display called from Sports :");
//System.out.println("Roll No :" + RollNo);
//System.out.println("Name :" + Name);
System.out.println("Date of Birth :" + DOB);
System.out.println("Address :" + Add);
System.out.println("Sports score :" +score);
}
}
package Report;
class Result extends Test
{
int total;
Result(int x,String n,String d,String a,int y,int z)
{
super(x,n,d,a,y,z);
}
public void display()
{
super.display();
System.out.println("Display called from Result :");
System.out.println("Name :" + Name);
System.out.println("Address :" + Add);
System.out.println("Marks 1 :" + m1);
System.out.println("Marks 2 :" + m2);
System.out.println("Total Marks :" + (m1+m2));
}
}
package Report;
import SReport.Sports;
class Demo
{
public static void main(String args[])
{
Result R =new Result(1,"Shalini","01/01/1975","Vashi",65,75);
R.display();
Sports s =new Sports(2,"Amar","01/01/1972","NaviMumbai",60);
S.display();
}
}
atan(double) Returns the arc tangent of a, in the range of -Pi/2 through Pi/2.
atan2(double,do Converts rectangular coordinates (a, b) to polar (r, theta).
uble)
ceil(double) Returns the "ceiling" or smallest whole number greater than or equal
to a.
cos(double) Returns the trigonometric cosine of an angle.
exp(double) Returns the exponential number e(2.718...) raised to power of a.
floor(double) Returns the "floor" or largest whole number less than or equal to a.
log(double) Returns the natural logarithm (base e) of a.
max(int, int) Takes two int values, a and b,& returns the greater number of the two.
max(long, long) Takes two long values, a & b & returns the greater number of the two.
max(float, float) Takes two float values, a & b& returns the greater number of the two.
max(double, Takes two double values, a & b, & returns the greater number of the
double) two.
min(int, int) Takes 2 int values, a & b, & returns the smallest number of the two.
min(long, long) Takes 2 long values, a & b, and returns the smallest number of the two
min(float, float) Takes 2 float values, a &b, and returns the smallest number of the two.
min(double, Takes two double values, a and b, and returns the smallest number of
double) the two.
pow(double, Returns the number a raised to the power of b.
double)
random() Generates a random number between 0.0 and 1.0.
Random number generators are often referred to as pseudorandom
number generators because the numbers produced tend to repeat
themselves after a period of time.
copyInto(Object[]) Copies the elements of this vector into the specified array.
elementAt(int) Returns the element at the specified index
13.2.5 java.util.hashtable,:
Hashtable class.maps keys to values. Any object can be used as a key and/or
value. To sucessfully store and retrieve objects from a hash table the object used as the
key must implement the hashCode() and equals() methods. This example creates a
hashtable of numbers. It uses the names of the numbers as keys:
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
To retrieve a number use:
Integer n = (Integer)numbers.get("two");
if (n != null)
{
System.out.println("two = " + n);
}
Hashtable(int, float) Constructs a new, empty hashtable with the specified initial
capacity and the specified load factor.
Hashtable(int) Constructs a new, empty hashtable with the specified initial
capacity.
Hashtable() Constructs a new, empty hashtable.
clear() Clears the hash table so that it has no more elements in it.
isEmpty() Returns true if the hashtable contains no elements
put(Object, Object) Puts the specified element into the hashtable, using the specified
key.
keys() Returns an enumeration of the hashtable's keys.
rehash() Rehashes the content of the table into a bigger table.
remove(Object) Removes the element corresponding to the key.
size() Returns the number of elements contained in the hashtable.
class. In addition a public variable is accessible from any class inside and outside the
package it is declared. If the members of a superclass are public then they are accessed
from a sub class either inside or outside a package without any difficulty. The protected
members are those members that are accessible from all the sub classes of the same
package and also from the subclasses of another package. The private access modifier is
the most restrictive of all the access modifiers. The private members are not accessible
outside their class. They cannot be accessed by their sub classes either from the current
package or from another package. Thus the private members cannot be inherited
Access Location Public Protected Default private
Same class Yes Yes Yes Yes
Sub class in same
Yes Yes Yes No
package
Other classes in
Yes No Yes No
same package
Subclass in another
Yes Yes No No
package
Non-subclass in
Yes No No No
other packages
14.2 Exceptions:
An exception is a condition that is caused by a run time error in the program. When the
Java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
If the exception object is not caught and handled properly, the interpreter will
display an error message as shown in the output of program and will terminate the
program. If we want the program to continue with the execution of the remaining code,
then we should try to catch the exception object thrown by the error condition and then
display an appropriate message for taking corrective actions. This is called as exception
handling.
The purpose of exception handling mechanism is to provide a means to detect and
report an “exceptional circumstance” so that appropriate action can be taken. The
mechanism suggests incorporation of a separate error handling code that performs the
following tasks:
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred (Throws the exception)
3. Receive the error information (Catch the exception)
4. Take the corrective actions (Handle the exception)
The error handling code basically consists of two segments one to detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions. While
writing programs we must always be on the look out for places in the program where an
exception could be generated. Some common exceptions that we must watch out for
catching are listed in the table:
Exception type Cause of Exception
ArithmeticException Caused by Math errors such as divide by zero
ArrayIndexOutOfBoundException Caused by error indexes
ArrayStoreException Caused when a program tries to store wrong data in
array
FileNotFoundException Caused by an attempt to access a nonexistent file
IOException Caused by general I/O failures such as inability to
read from a file
NullPointerException Caused by referencing a null object
NumberFormatException Caused when conversion between strings and
number fails
OutOfMemoryException Caused when there is not enough memory to
allocate a new object
SecurityException Caused when an applet tries to perform action not
allowed by browser’s security
StackOverflowException Caused when the system runs out of stack space
StringIndexOutOfBoundsException Caused when a program attempts to access a
nonexistent character position in a string
try Block
{
Statement that causes the exception
}
Catch Block
{
Statement that handles the exception
}
Java uses a keyword try to prefer a block of code that is likely to cause an error
condition and “throw” an exception. A catch block defined by the keyword catch
“catches” the exception “thrown” by the try block and handles it appropriately. The catch
block is added after the try block.
for(int i=0;i<args.length;i++)
{
try
{
num=Integer.parseInt(args[i]);
}
catch(NumberFormatException e)
{
invalid++;
System.out.println("Invalid arguments :"+args[i]);
continue;
}
count++;
}
System.out.println("Valid arguments :"+count);
System.out.println("InValid arguments :"+invalid);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac ClineInput.java
C:\Java\jdk1.5.0_04\bin>java ClineInput Java 10 17.5 18 you
Invalid arguments :Java
Invalid arguments :17.5
Invalid arguments :you
Valid arguments :2
InValid arguments :3*/
{
statement;
}
…………………
………………..
When an exception in a try block is generated, Java treats the multiple catch
statements like cases in switch statement. The first statement whose parameter
matches with the exception object will be executed and the remaining statements will
be skipped.
class Error
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division byb zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Datatype");
}
int y=a[1]/a[0];
System.out.println("y= "+y);
}
}
/*C:\Java\jdk1.5.0_04\bin>javac Error.java
C:\Java\jdk1.5.0_04\bin>java Error
Array Index Error
y= 2*/
used to handle any exception generated within a try block. It may be added immediately
after the try block or after the last catch block shown as follows:
try
{
……………
}
catch(………..)
{
……………..
}
catch(………..)
{
……………..
}
finally
{
……………..
}
15. Multithreading
Multithreading is a conceptual programming paradigm where a program is divided into
two or more subprograms (processes) which can be implemented at the same time in
parallel. For example one subprogram can display an animation on the screen while
another may build the next animation to be displayed. This is something similar to
dividing a task into subtasks and assigning them to different people for execution
independently and simultaneously.
Multithreading is a powerful programming tool that makes java distinctly different from
its fellow programming languages. Multithreading is useful in a number of ways. It
enables programmers to do multiple things at one time. They can divide a long program
(containing operations that are conceptually concurrent) into threads and execute them in
parallel. For example we can send tasks such as printing into the background and
continue to perform some other task in the foreground. This approach would considerably
improve the speed of other programs.
responsible for executing the main routine of the program. The main thread can in turn
create other threads that can continue even after the main thread has terminated.
The above figure illustrates four threads one main thread and three others. The main
thread is designed to create other three threads namely A,B and C. Once initiated by the
main thread the threads A,B and C run currently and share the resources jointly. The
ability of a language to support multithreads is referred to as concurrency. Since threads
in java subprograms of a main application program and share the same memory space
they are known as lightweight threads or light weighted processes.
thread’s behavior can be implemented. The run( ) method can call other methods use
other classes and declare variables just like the main thread can. We must perform the
steps listed below:
Step 1: Declare the class as implementing the Runnable interface.
Step 2: Implement the Run( ) method.
Step 3: Pass an object that implements the Runnable interface as a parameter to the
constructor of an object of type Thread.
Step 4: Call the thread’s start( ) method to run the thread.
When the thread’s start( ) method is called the thread will execute a call to run( ) method
in the Runnable object. Following program illustrates implementation of the above steps:
class NamedRunnable implements Runnable
{
private String Name;
NamedRunnable(String name)
{
this.Name=name;
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Greetings from "+Name);
}
System.out.println("End of Child thread");
}
}
class RunnableTest
{
public static void main(String args[])
{
NamedRunnable greetings = new NamedRunnable("Child thread");
Thread greetingsThread = new Thread(greetings);
greetingsThread.start();
for(int i=1;i<=10;i++)
{
System.out.println("Main Thread");
}
System.out.println("End of Main thread");
}
/*C:\Java\jdk1.5.0_04\bin>javac RunnableTest.java
C:\Java\jdk1.5.0_04\bin>java RunnableTest
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
Greetings from Child thread
End of Child thread
Main Thread
Main Thread
Main Thread
Main Thread
End of Main thread*/
New Thread
start() New Born
stop()
Dead
Runnable
State
State
Runnable state: The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is the thread has joined the queue of
threads that are waiting for execution. If all the threads have equal priority then they are
given time slots for execution in round robin fashion i.e. first come first serve. The thread
relinquishes control joins the queue at the end and again waits for its turn. The process of
assigning time to threads is known as time slicing. However if we want a thread to
relinquish control to another thread of equal priority before its turn comes we can do so
by using the yield( ) method.
Running state: Running means that the processor has given its time to the thread for
execution. The thread until it relinquishes control on its own or it is preempted by a
higher priority thread. A running thread may relinquish its control in one of the following
situations.
1. It has been suspended using suspend ( ) method. A suspended thread can be revived
by using the resume ( ) method. This approach is useful when we want to suspend a
thread for some time due to certain reason but do not want to kill it.
2. It has been made to sleep. We can put a thread to sleep for a specified time period
using the method sleep (time) where time is in milliseconds. This means that the
thread is out of the queue during this time period. The thread re-enters the runnable
state as soon as this period is elapsed.
3. It has been made to wait until some event occurs. This is done using the wait ( )
method. The thread can be scheduled to run again using the notify () method.
Blocked state: A thread is said to be blocked when it is prevented from entering into the
runnable state subsequently the running state. This happens when the thread is
suspended, sleeping or waiting in order to satisfy certain requirements. A blocked thread
is considered “not runnable” but not dead and therefore fully qualified to run again.
Dead state: Every thread has a life cycle. A running thread ends its life when it has
completed executing its run() method. It is natural death. However we can kill it by
sending the stop message to it at any state thus causing a premature death to it. A thread
can be killed as soon it is born or while it is running or even when it is in “not runnable”
condition
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread’s priority is set. The thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 and 10. note
that the default priority is NORM_PRIORITY. Most user level processes should use
NORM_PRIORITY. Background processes such as network and I/O and screen
repainting should use a value MIN_PRIORITY. By assigning priorities to threads we can
ensure that we give them the attention they deserve. Whenever multiple threads are ready
for execution the Java stream chooses the highest priority thread and executes it. The use
of priority threads can be explained
15.5 Synchronization:
We have seen threads that use their own data and methods provided inside their run( )
methods. What happens when they try to use data and methods outside themselves? On
such occasions they may compete for same resources they may lead to serious problem.
For example one thread may try to read a record from a file while another is trying to
read a record from a file while another is still writing to the same file. Depending on the
situation we may get strange results. Java enables us to overcome the problem using a
technique known as synchronization. The keyword synchronized helps us in keeping the
watch on such locations. When we declare a method synchronized, Java creates a
“monitor” and hands it over to the thread that calls the method first time. As long as the
thread holds the “monitor” and hands it over to the thread that calls the first time. As long
as the threads hold the monitor, no other thread can enter the synchronized section of the
code. A monitor is like a key and the thread that holds the key can only open the lock. It
is also possible to mark a block of code as synchronized as shown below:
synchronized (lock object)
{……………..
……………….}
Whenever a thread has completed its work of using synchronized method (or block of
code), it will hand over the monitor to the next thread is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain control
of a resource. Due to some reason, the condition on which the waiting threads rely on to
gain control does not happen. This results in a deadlock. For example assume that the
threadA must access Method1 before it can release Method2 but the threadB cannot
release Method until it gets hold of Method2. Because they are mutually exclusive
conditions a deadlock occurs. The code below illustrates this:
Thread A
synchronized method2 ( )
{
synchronized method1( )
{
……………………
……………………..
}
}
Thread B
synchronized method1 ( )
{
synchronized method2( )
{
……………………
……………………..
}
}
The paint( ) method of the Applet class when it is called actually displays the result of
the applet code on the screen. The output may be text, graphics or sound. The paint ( )
method which requires a Graphics object as argument, is defined as follows:
public void paint (Graphics g)
This requires that the applet code imports the java.awt package that contains the
Graphics class. All output operations of an applet are performed is using the methods
defined in the Graphics class. The general form of applet code is shown below:
import java.awt.*;
import java.applet.*;
………………
public class appletclassname extends Applet
{
…………………………
………………………
public void paint(Graphics g)
{
………………………..
……………………..
}
……………………….
}
The appletclassname is the main class for the applet. When the applet is loaded, Java
creates an instance of this class and the n series of Applet class methods are called on
that instance to execute the code. The program shows a simple Hello.java applet.
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello Java",10,100);
}
}
<HTML>
<APPLET
CODE ="HelloJava.class"
WIDTH = 400
HEIGHT = 200>
</APPLET>
</HTML>
Born Initialization
start()
Running
Destroyed End
Dead
Exit of Browser
Initialization state:
Applet enters the initialization state when it is first loaded. This is achieved by calling the
init( ) method of Applet class. The applet is born. At this stage, we may do the following
if required.
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
The initialization occurs only once in the applet’s life. To provide any of the behaviors
mentioned above, we must override the init( ) method:
public void init( )
{
……………….
……………….
}
Running state:
Applet enters the running state when system calls the start( ) method of Applet class.
This occurs automatically after the applet is initialized. Starting can also occur if the
applet is already in “stopped” (idle) state. For ex: we may leave the web page containing
the applet temporarily to another page and return back to the page. This again starts the
applet running. Note that unlike init( ) method, the start ( ) method may be called more
than once. We may override the start() method to create a thread to control the applet.
public void start( )
{
……………….
……………….
}
Idle or Stopped State:
An applet becomes idle when it is stopped from running. Stopping occurs automatically
when we leave the page containing the currently running applet. We can also do so by
calling the stop( ) method explicitly. If we use a thread to run the applet then we must use
stop( ) method to terminate the thread. We can achieve this by overriding stop( ) method
public void stop( )
{
……………….
……………….
}
Dead state:
An applet is said to be dead when it is removed from memory. This occurs automatically
by invoking the destroy() method when we quit the browser. Like initialization
destroying stage occurs once in the applet’s life cycle. If the applet has created any
resources like threads we may override the destroy() method to clean up these resources.
public void destroy( )
{
……………….
……………….
}
Display State:
Applet moves to display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The
paint() is called to accomplish this task. Almost every applet will have a paint() method.
Like other methods in the life cycle the default version of paint() method does
absolutely nothing. We must therefore override this method if we want anything to be
displayed on the screen.
public void paint( )
{
……………….
……………….
}
and the other two represent the width and height of the oval itself. If the width and height
is the same then the oval turns into a circle. The drawOval() method draws the outline of
the Oval and the fillOval() method draws a solid oval.
g.drawOval(20,20,200,120);
g.fillOval(70,30,100,100);
Drawing arcs:
An arc is part of an Oval. The drawArc() designed to draw arcs takes six
arguments. The first four are the same as the arguments of the oval and the next two
arguments specify the starting angle of the arc and the number of degrees around the arc.
In drawing arcs, Java actually formulates the arc as an Oval and then draws only part of it
as dictated by the last two arguments. Java considers the three O’ clock position as zero
degree position and degrees increase in anti-clockwise direction. So to draw an arc
from12.00 O’clock position to 6.00 o’clock position, the starting angle would be 90 and
the sweep angle would be 180. We can also draw an arc in backward direction by
specifying the sweep angle as negative. We can use fillArc() method to fill the arc.
if(num1<num2)
{
int temp=num1;
num1=num2;
num2=temp;
}
int r=1;
while(r>0)
{
r=num1%num2;
num1=num2;
num2=r;
}
return(num1);
}
void putdata()
{
System.out.println(num1+ " " +num2+ " "+gcd());
}
}
class GCD
{
public static void main(String args[])
{
great g =new great();
g.getdata(35,25);
g.putdata();
}
}
/*E:\Java\jdk1.5.0_16\bin>javac GCD.java
E:\Java\jdk1.5.0_16\bin>java GCD
35 25 5*/
b) Develop a Java program that determines the number of days in a given semester.
Input data to the program consists of the year, month and day information of the first and
last days of a semester. The program should accept the date information as a single string
instead of accepting the year, month and day information separately. The input string
must be in MM/DD/YYYY.
Ans: import java.util.Calendar;
class Demo
{
public static void main(String args[])
{
3. a) Write a Java program to compute the distance S fallen by an object in freefall. The
formula is : S=S0+V0*t+1/2*a*t2
Ans: class Distance
{
public static void main(String args[])
{
int S0=Integer.parseInt(args[0]);
int V0=Integer.parseInt(args[1]);
int a=Integer.parseInt(args[2]);
int i=0,t;
for(t=5;t<=100;i++)
{
System.out.println();
System.out.print("S"+i+":");
S0=S0+V0+(1/2)*a*(t*t);
System.out.print(S0);
t=t+5;
}
}
}
/*C:\Java\jdk1.5.0_17\bin>javac Distance.java
C:\Java\jdk1.5.0_17\bin>java Distance 7 5 6
S0:12 S1:17 S2:22 S3:27 S4:32 S5:37
S6:42 S7:47 S8:52 S9:57 S10:62 S11:67
S12:72 S13:77 S14:82 S15:87 S16:92 S17:97
S18:102 S19:107 */
b) Write an object oriented program to arrange names of students in descending order of
their total marks. Input data consists of student details such as name, Id no and marks
obtained in Mathematics, Physics and Chemistry. Use the concept of array of objects.
Ans: import java.io.*;
class Student
{
int RollNo;
String Name;
float maths,physics,chem,marks;
void get(int a,String n,float m,float p,float c)
{
RollNo=a;
Name=n;
physics=p;
maths=m;
chem=c;
marks=physics+chem+maths;
}
void put()
{
System.out.println(RollNo+ " "+Name+ " "+marks);
}
}
class StudDetail
{
public static void main(String args[])throws IOException
{
Student s[]=new Student[5];
Student temp=new Student();
BufferedReader obj =new BufferedReader(new InputStreamReader(System.in));
String str;
int x; float fp,fc,fm;
int i,j;
for(i=0;i<3;i++)
{
s[i]=new Student();
}
for(i=0;i<3;i++)
{
System.out.println("Enter Rollno :");
x=Integer.parseInt(obj.readLine());
System.out.println("Enter Name :");
str=obj.readLine();
System.out.println("Enter Physics :");
fp=Float.parseFloat(obj.readLine());
System.out.println("Enter Chemistry :");
fc=Float.parseFloat(obj.readLine());
System.out.println("Enter Maths :");
fm=Float.parseFloat(obj.readLine());
s[i].get(x,str,fp,fc,fm);
}
System.out.println("Student Details:");
for(i=0;i<3;i++)
{
s[i].put();
}
System.out.println("Student Details in the descending order of marks:");
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if(s[i].marks<s[j].marks)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
for(i=0;i<3;i++)
{
s[i].put();
}
}
}
/*C:\Program Files\Java\jdk1.5.0_17\bin>java StudDetail
Enter Rollno :
1
Enter Name :
shalini
Enter Physics :
45
Enter Chemistry :
46
Enter Maths :
33
Enter Rollno :
2
Enter Name :
ajay
Enter Physics :
46
Enter Chemistry :
45
Enter Maths :
44
Enter Rollno :
3
Enter Name :
abhi
Enter Physics :
45
Enter Chemistry :
49
Enter Maths :
49
Student Details:
1 shalini 124.0
2 ajay 135.0
3 abhi 143.0
Student Details in the descending order of marks:
3 abhi 143.0
2 ajay 135.0
1 shalini 124.0*/
4. With the help of a suitable Java program describe the following:
1. Overloading of functions
2. Overriding functions
3. Final methods and classes
4. Abstract methods and classes:
Ans: Abstract class is a class that has no direct instances, but whose descendants may
have direct instances. There are cases in which it is useful to define classes for which the
programmer never intends to instantiate any objects; because such classes normally are
for(int j=0;j<3;j++)
{
System.out.print(x[i][j]+ " ");
}
System.out.println();
}
}
public void addMatrix(int y[][])
{
int z[][]= new int[3][3];
System.out.println("Displaying Addition Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
z[i][j]=x[i][j]+y[i][j];
System.out.print(z[i][j]+ " ");
}
System.out.println();
}
}
public void multMatrix(int y[][])
{
int z[][]= new int[3][3];
System.out.println("Displaying Multiplicated Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
for(int k=0;k<3;k++)
{
z[i][j]+=x[i][k]+y[k][j];
}
System.out.print(z[i][j]+ " ");
}
System.out.println();
}
}
public void transposeMatrix()
{
System.out.println("Displaying Transposed Matrix :");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(x[j][i]+ " ");
}
System.out.println();
}
}
}
class abc1
{
public static void main(String args[])
{
abc a =new abc();
a.readMatrix();
a.displayMatrix();
a.transposeMatrix();
int k=1;
int z[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
z[i][j]=k;
k++;
}
}
a.addMatrix(z);
a.multMatrix(z);
}
}
/*E:\Java\jdk1.5.0_16\bin>javac abc1.java
E:\Java\jdk1.5.0_16\bin>java abc1
Displaying Matrix :
123
456
789
Displaying Transposed Matrix :
147
258
369
Displaying Addition Matrix :
246
8 10 12
14 16 18
Displaying Multiplicated Matrix :
18 21 24
27 30 33
36 39 42*/
7. Write notes on the following with the help of suitable program segments in Java:
Vectors: Already explained in Section 10.5.
Strings: Already explained in Section 10-.1 and 10.2.
Packages: Already explained in Section 13.1 and 13.2.
Interfaces: Already explained in Section 12.4.
17.2 Dec-2008
1. a) Explain life cycle of a thread.
Ans: Already explained in Section 12.4.
b) Write a program in java to find nCr and nPr.
Ans: class PComb
{
static int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
int r=Integer.parseInt(args[1]);
int P,C;
P=fact(n)/fact(n-r);
C=fact(n)/fact(r)*fact(n-r);
System.out.println("P ="+P);
System.out.println("C ="+C);
}
}
/*C:\Java\jdk1.5.0_17\bin>javac PComb.java
C:\Java\jdk1.5.0_17\bin>java PComb 7 5
P =2520
C =84*/
c) Explain JVM in brief.
Ans: The JVM stands for Java Virtual Machine. An abstract computing machine, or
virtual machine, JVM is a platform-independent execution environment that converts
Java byte code into machine language and executes it. Most programming languages
compile source code directly into machine code that is designed to run on a specific
if(palindrome.equals(reversePalindrome))
System.out.println("palindrome");
else
System.out.println("not a palindrome");
}
}
/*C:\Java\jdk1.5.0_17\bin>javac StringDemo.java
C:\Java\jdk1.5.0_17\bin>java StringDemo MADAM
palindrome
C:\Program Files\Java\jdk1.5.0_17\bin>java StringDemo MADAMA
not a palindrome*/
m=m+1;
n=n+2;
}
Ans: The program will compile but will get into an infinite state.
i = 8 sum = 2.7178574
i = 9 sum = 2.8289685
i = 10 sum = 2.9289684*/