Date post: | 09-Apr-2018 |
Category: |
Documents |
Upload: | aditya-kapoor |
View: | 220 times |
Download: | 0 times |
of 57
8/8/2019 Resource Material for JAVA
1/57
JAVA
Java is an object oriented language (OOPL). An OOPL reflects the real world
situation. Hence compilation involved in project development is simplified. The
fractures of OOPL are class, object, encapsulation, abstraction, inheritance,
polymorphism, dynamic binding and message passing. . As far as application
development is concerned, following are the important object oriented features.
1. Encapsulation2. Inheritance3.
Polymorphism
Encapsulation: The act of combining data and eligible code that acts upon
data is known as encapsulation. Encapsulation allows us to hide information
from ineligible code of the application and there by data processing is secure.
In an object oriented system (application), encapsulation is realized through
class & object. In a class, we combine variables and eligible functions (methods
in java). Total application is divided into classes. Variables and methods
(functions) of one class are not accessible in other classes unless access
permissions are granted. By defining a class in an application, we are defining a
user defined data type. In order to store data and process it, we have to
instantiate the class. An instance of a class is nothing but an object. An object
holds data and code that acts upon the data. An object oriented system is a
collection of objects.
Inheritance: Creating new classes from already existing classes through is-a
relationship is known as inheritance. Already existing classes are known as
super classes and newly created classes are known as a sub classes. Sub classes
inherit variables and methods from super classes. Therefore, inheritance offers
reusability of code. Code reusability improves productivity and consequently
software can be developed at competitive prices.
8/8/2019 Resource Material for JAVA
2/57
Polymorphism: An object behaving differently in different situations is nothing
but the object is exhibiting polymorphism. Oneinterface, multiple forms is the
keyfeature of polymorphism. Here, interface means method of the object. With
same method name, multiple definitions will be there in a class. Each definition
performs one task. With same method call we can get multiple services from the
object. Polymorphism offers flexibility and extensibility of code.
Data TypesJava language has 8 primitive data types.
int short byte long float double char Boolean
int, short, byte and long are integral data types. All these data types are used to
declare variables that can store non-decimal numbers.
Data type Memory in bytes Range of values
int 4 -21474883648 to 21474883647
short 2 -32768 to 32767
Byte 1 -128 to 127
Long 8 -9223372036854775808 to 9223372036854775807
8/8/2019 Resource Material for JAVA
3/57
Numeric values that are not integral are stored in floating-point numbers. Float
and double are used to store decimal numbers. If we need accuracy up to 7
digits after decimal point, we use float type. If we need accuracy up to 17 digits
after decimal point, we use double type.
Floating-point literals are by default double type. If we want to specify a
floating point literal, we should explicitly mention f or F. For example,
Float a=45.6F;
Char primitive type variable occupy 2 bytes of memory in Java. In C & C++
languages it takes only 1 byte of memory. Java supports Unicode characters.
While assigning a character literal to a variable in Java, we have to enclose it in
single quotes (similar to C and C++). For example,
char grade=A;
We can use arithmetic on char variables.
grade +=1;//Earlier grade holds A and now it holds B.
Variables of type Boolean can have only one of two values, true or false.
For example,
Boolean ismanager=false;//ismanager variable holds false literal now.
Operators in Java
Almost all the operators in Java are similar to that of C & C++ programming
languages with very few exceptions. Their meaning and functionality is similar
in Java as well.
Arithmetic Operators: +, -, *, /, %
Relational Operators: ==, !=, >, < , >=,
8/8/2019 Resource Material for JAVA
4/57
8/8/2019 Resource Material for JAVA
5/57
sum=n1+n2;
System.out.println(The sum of two numbers is:+sum);
}
}
CONTROL STATEMENTS:
IF STATEMENT: The java IF statement works much like IF statement in any
other language. Its simplest form is
If(condition) Statements;
1. Decision making in a Java program is similar to C programming. 2. All kinds of if conditions are available in Java. I.e. simple if, if else, if
else ladder, nested if etc.
Example:
Program to display the bigger of the two numbers
Source code: - bigger.java
*/
class Bigger Number
{
public static void main(String args[])
{
int n1=23;
int n2=32;
if(n1>n2)
System.out.println(n1+ is bigger than +n2);
8/8/2019 Resource Material for JAVA
6/57
else
System.out.println(n2+ is bigger than +n1);
}
}
LOOPS:
1. All kinds of loops in Java are similar to that of C as far as syntax isconcerned.
2. If we write a for loop in C, the loop counter will be declared beforewe write the loop. In Java, within the for loop itself we can declare it
and initialize it.
3. Variable declared within for loop is available in that loop only. Thereforewe could declare a variable i again.
Syntax Of FOR Loop Is As Follows:
FOR(Intialization;Condition;Iteration)
Statements;
Example:
/*Program that prints a multiplication table of 5 up to 10 multiples.
Source code:- table.java */
class Multiplication Table
{
public static void main(String args[])
{
int n=5;
int product;
for(int i=1;i
8/8/2019 Resource Material for JAVA
7/57
{
product=n*i;
System.out.println(n+" X "+i+" = "+product);
}
}
}
Arrays in Java
An array is a collection of homogeneous elements referred by the same name.
An array is also known as sub-scripted variable. An array is created in Java with
the following syntax.
datatype arrayriable[]=new datatype[size];
For example,
int a[]=new int[10];
The above syntax creates an integer array of size 10. In Java, arrays areinternally represented as objects. Every array has property known as length that
gives the size of the array.
Example:
Q) Write a program to store first 5 natural numbers in an array and display
them.
/*
Source code:- ArrayExample.java
*/
class Array Example
{
public static void main(String[] args)
{
int arr[]=new int[5];
8/8/2019 Resource Material for JAVA
8/57
for(int i=0;i
8/8/2019 Resource Material for JAVA
9/57
8/8/2019 Resource Material for JAVA
10/57
A method without return statement is called void. Methods can have objects as parameters and return back objects. When variables are passed as parameters to methods, it is passed by
value.
When object is passed as parameter to methods, then it is passed byreference.
Methods can be nested. if method is directly called by main, then is method is qualified as static.
Static methods can call other static methods and make use of static
variables which are declared out of scope.
if a class contains methods with same names but different prototypes, it iscalled method overloading.
if a data member/method is qualified static, then can be accessed directlyusing class name without need of object creation.
recursive methods are allowed in java. When a method is qualified as final, then it cannot be overridden .
Example: Write a program to represent 2 books information.
class Book
{
String title;
String author;
float price;
void giveDataToBook(String t,String a, float p)
{
title=t;
author=a;
price=p;
}
8/8/2019 Resource Material for JAVA
11/57
void displayBookDetails()
{
System.out.println("Book Title:"+title);
System.out.println("Author of the Book:"+author);
System.out.println("Book price:Rs."+price);
}
}
class Execute Book
{
public static void main(String args[])
{
Book b1=new Book();
b1.giveDataToBook ("CompleteReference, HerbertSchildt",310);
System.out.println("The first book details");
b1.displayBookDetails();
Book b2=new Book();b2.giveDataToBook("Thinking inJava, Bruce Euckle",350);
System.out.println("The second book details");
b2.displayBookDetails();
}//main
}//class
Method Overloading
If we define multiple methods with the same name with different signatures in a
class, such concept is known as method overloading. We implement
polymorphism in Java using this concept.
For example,
class A
8/8/2019 Resource Material for JAVA
12/57
{
void add(int a, float b)
{
}
void add(float a, int b)
{
}
}
In class A add method is overloaded. In a class, signatures of methods with
same name are said to be different if at least any one of the following criteria
mismatches.
1. number of parameters2. order of parameters3. type of parameters
Access specifiers in Java
private, protected and public are the access specifiers in Java. We apply these
access specifiers to the members of the class. I.e. variables and methods of the
class. If a member is not associated with these three keywords, it will have
default accessibility mode in Java.
If a member of a class has private accessibility mode, it is accessible onlyfrom the methods of the same class.
If a member of a class has default accessibility mode, it is accessible toall the methods of those classes that are present in the same package.
If a member of a class has protected accessibility mode, it is accessible toall the methods of those classes that are present in the same package plus
all child class methods.
8/8/2019 Resource Material for JAVA
13/57
If a member of a class has public accessibility mode, it is accessible to allthe methods of the entire java environment.
Note: - In Java, a class can also be declared public.
Class A
{
Private int a;
A(int a)
{
this.a=a;
}
void display()
{
System.out.println(a=+a);
}
}
class Main
{
public static void main(String args[])
{
A o=new A(10);o.a=30;//error
o.display();
}
}
The above program raises compilation error as follows.
a has private access in A
8/8/2019 Resource Material for JAVA
14/57
Modifiers in Java
Static, abstract and final are three important modifiers in Java. When weapply them to the members of a class their meaning will be changed.
Static variables
These are used to represent the whole class level information rather than
individual object information. Per class only one copy of static variables is
created. A static variable can be referred by class name.
Q) Example program on static variable usage.
class Employee
{
static int count;
Employee()
{
count++;
System.out.println("Employee appointed");
}
void getEmpCount()
{
System.out.println("No. of employees appointed:"+count);
}
}class StaticExample
{
public static void main(String args[])
{
System.out.println("No. of employees
appointed:"+Employee.count);
Employee e1=new Employee();
8/8/2019 Resource Material for JAVA
15/57
e1.getEmpCount();
Employee e2=new Employee();
e2.getEmpCount();
}//main()
}//class
When the program is executed the following output comes.
No. of employees appointed: 0
Employee appointed
No. of employees appointed: 1
Employee appointed
No. of employees appointed: 2
Static methods
If a method of a class is declared static, it becomes the class method. We can
call that method directly on the class.
ClassName.method();
In the previous example, if count variable is made private, we cannot
access it directly from main method. In such a case, getEmpCount() should
have been made static.
Q) Static method example
class Employee
{private static int count;
Employee()
{
count++;
System.out.println("Employee appointed");
}static void getEmpCount()
8/8/2019 Resource Material for JAVA
16/57
{
System.out.println("No. of employees appointed:"+count);
}//static method definition
}
class StaticExample
{
public static void main(String args[])
{
Employee.getEmpCount();//static method call
Employee e1=new Employee();
e1.getEmpCount();
Employee e2=new Employee();
e2.getEmpCount();
}
}
Note:- Without a reference we should not reference an instance variable or aninstance method in a static method. If object is available, a static method can be
called using object reference also.
Final modifier
We can associate this modifier with variables, methods and classes also.
Final variables: - We declare constants in java using final. Final variables must
be defined. Their value cannot be changed once they are defined.
For example,
class A
{
final int a=10;
}
Final methods:- If a method is declared final, it can be inherited but it cannot
be overridden.
8/8/2019 Resource Material for JAVA
17/57
8/8/2019 Resource Material for JAVA
18/57
If a method is declared abstract, the class in which it is declared also must
declared abstract. In a hierarchy of classes the most generalized class is
generally declared abstract. Every sub class of an abstract class must implement
all the abstract methods of its super class.
For example,
class Square extends Diagram
{
void draw()
{
System.out.println(square is drawn);
}
}
class Rectangle extends Diagram
{
void drawSquare()
{
}
}
When we compile the source code, Compiler reports an error saying that
Rectangle class should be declared abstract. It is inheriting from an abstract
class Diagram, but not overriding the draw() method. To rectify the error,
either we have to declare the Rectangle class abstract OR implement the draw()
method.
Constructors in Java
A constructor is a specialized method in Java whose name and class nameis the same and is called implicitly as soon the object is created.
Primary purpose of a constructor is object initialization.
8/8/2019 Resource Material for JAVA
19/57
Constructors are used to initialize instance variables of class at the time ofinstance creation.
The visibility mode of a constructor can be either public or no modifier. Constructors can never be private. A constructor always has the class name as its name. A class can have any number of constructors with same name but with
different prototypes. This is called constructor overloading.
A constructor with no parameter is called default constructor. Objects can be passed as parameters to constructors. The constructors will not have return type. The reserve word ' super ' is used to invoke a super class constructor from
sub class constructor. Java does not have the concept of destructors because of its mark and
sweep concept.
Example:
class Student
{
int regno; String name;
Student(int rno,String n)
{
regno=rno;
name=n;
}//Parameterized constructor
Student()
{
regno=1001;
name="Rama";
}//zero argument constructor
void displayStudentDetails()
{
System.out.println("Student Registration No:"+regno);
8/8/2019 Resource Material for JAVA
20/57
System.out.println("Name:"+name);
}
}
Implementing inheritance in Java
Adopting the features of one class by another class i.e., re-usability ofcode is the concept of Inheritance.
A class ' extends ' the features of existing class. 3. The existing class is called ' base class ' and the class which derives the
features of base class is called ' derived class '.
The base class is also called ' Super class ' and the derived class is alsocalled ' Sub class '.
Java supports only Single inheritance, Multi level inheritance andHierarchical inheritance.
Java does not support Multiple inheritances and hence Hybridization isnot possible to the fullest extent.
The private instance variables and methods cannot be inherited. When the super class and sub class methods have methods with same
name, then ' method over riding ' takes place.
In this over riding concept, the methods of sub class will dominate themethods of super class i.e., the methods of
Super class become dormant. To resolve method over riding, the reserve word ' super ' is used before
the methods of super class.
8/8/2019 Resource Material for JAVA
21/57
When super class and sub class methods have same names but withdifferent prototypes, then method over loading takes place.
To invoke the constructor of super class from sub class, the reserve word 'super ' is used.
While invoking the super class constructor from sub class constructor, thereserve word ' super ' should be used as very first line of sub class.
We can pass arguments to super class constructor from sub classconstructor.
When an instance is created for sub class, then the corresponding superclass constructor is invoked prior to sub class constructor.
A super class instance can refer to its sub class. Through the super class instance, we can only refer to those methods of
sub class whose signatures are available in super class.
We can attain polymorphism through the concept of a super classinstance referring to a sub class.
TYPES OF INHERITANCE:
1. SINGLE INHERITANCE:
If there is only one super class and one sub class then that type of inheritanceis called Single inheritance.
2. MULTI LEVEL INHERITANCE:
Here a sub class acts as super class for another class.
3. HIERARCHIAL INHERITANCE:
8/8/2019 Resource Material for JAVA
22/57
8/8/2019 Resource Material for JAVA
23/57
}
}//sub class
class Main
{
public static void main(String args[])
{
Car c=new Car();
c.move();//inherited method
c.display();
}
}
Method overriding
Changing the definition of the parent class method in the sub class is known as
method overriding. To implement method overriding we have to follow the
given rules.
Super class method and sub class method signatures should be the same. Their return type should be the same. sub class method should not have weaker access privileges than that of
super class method
Sub class method should not have more number of checked exceptions inthe throws clause list.
Note: - After implementing method overriding, if we call the method on the
sub class object, sub class version only is called.
Q) Example program on method overriding.
8/8/2019 Resource Material for JAVA
24/57
8/8/2019 Resource Material for JAVA
25/57
void move()
{
super.move();
System.out.println("As a car I want to move in my own way");
}//overriding method
}
When we execute the above program, the following output comes.
Every vehicle moves this way
As a car I want to move in my own way
Note: - super keyword must be used from sub class only.
Dynamic Method Dispatch
When super class reference is referring to sub class object and method
overriding is implemented, making a method call is nothing but dynamic
method dispatch.
Q) Example program on dynamic method dispatch
class Vehicle
{
void move()
{
System.out.println("Every vehicle moves this way");
}//overridden method
}
class Car extends Vehicle
{
void move()
{
System.out.println("As a car I want to move in my own way");
8/8/2019 Resource Material for JAVA
26/57
}//overriding method
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
Vehicle v=new Car();
v.move();
}
}
When the above program is executed the following output comes.
As a car I want to move in my own way
Observations to be made
1. Reference is of type super class2. v is referring to sub class object3. Using the super class reference, the call is made.
Constructors in inheritance
Whenever sub class object is created, super class zero argument constructors
is executed first and then sub class one executed. Whenever the sub class
object is created, its constructor is called first. From there an implicit call is
made to the super class zero argument constructors. If it is found, it will beexecuted. If not found, error will be reported. Sub class object creation fails.
Q) What is the output of the following program?
class A
{
A()
{
System.out.println("super cnstr");
8/8/2019 Resource Material for JAVA
27/57
}
}
class B extends A
{
B()
{
System.out.println("sub cnstr");
}
}
class C
{
public static void main(String args[])
{
B b=new B();
}
}
When the above program is executed, the following output is displayed.
super cnstr
sub cnstr
POLYMORPHISM:
If a statement exhibits more than one form in different situations then it is
called Polymorphism.
Polymorphism is of 2 types:
a. Compile time polymorphism - Ex: Function overloading
b. Run time polymorphism
8/8/2019 Resource Material for JAVA
28/57
Run time polymorphism is called Dynamic binding or late binding.
Run time polymorphism can be attained in 3 ways:
1. Super class instance referring to a sub class.
2. Abstract classes.
3. Interfaces.
INTERFACES:
Interfaces contain methods with prototypes but no definitions. An interface can have data members which by default are static and
public.
An interface always starts with reserve word "interface" followed byinterface name.
interface An interface cannot have methods with definitions. A class can "extend" another class. Similarly a class "implements" an
interface.
The class which "implements" the interface should give definitions to allthe methods of that interface otherwise it should be declared abstract.
A class can implement a number of interfaces but can extend only oneclass.
Priority for extending class is more than implementing an interface i.e.,in cases where a class should extend another class and implement an
interface, it first extends the class and then implements the interface An interface can extend another interface. An interface cannot extend a class. Interfaces are used to exhibit dynamic method dispatch ( Run time
polymorphism )
The concept of multiple inheritance can be attained to some extentusing interfaces.
Accessing of methods of a class can be restricted using interfaces.
8/8/2019 Resource Material for JAVA
29/57
An object cannot be created for an interface or abstract class but it canbe given a reference.
Example on interface:
interface I1
{
void y();
}
class A implements I1
{
public void y()
{
System.out.println(Somefunctionality);
}
}//sub class
class InterfaceExample
{
public static void main(String args[])
{
I1 i=new A();
i.y();
}
}
Observations to be made
1. I1 is acting as the parent type of class A.2. Parent type reference can refer to the sub class object.3. In the interface I1, y() is public and abstract. Therefore, we must override
it in the sub class A
8/8/2019 Resource Material for JAVA
30/57
ABSTRACT CLASSES:
An Abstract method is a method with prototype but no definition.
Any class with Abstract methods is declared to be Abstract. An Abstract class can have methods with only prototypes as well as
methods with definitions.
The class which extends an abstract class should give definitions to allthe abstract methods of super class.
If the sub class does not give definitions to all the abstract methods of
super class then this sub class should be declared abstract.
We cannot create an instance to an Abstract class but it can beassigned a reference.
Dynamic binding can be attained by using the concept of Abstractclass.
PACKAGES:
Packages are used to compartmentalize the classes as per their nature. A package is nothing but a folder (sub directory) with related classes.
The classes in packages should be registered to the package with thestatement
package Packages can be nested i.e., a package can have internally another
package.
The classes of one package can be used in another package using"import" statement.
8/8/2019 Resource Material for JAVA
31/57
8/8/2019 Resource Material for JAVA
32/57
8/8/2019 Resource Material for JAVA
33/57
Application developers cannot handle Java.lang.Error class and its sub classes
representing abnormal conditions. Java.lang.Exception class has 2 kinds of sub
classes.
1.
Checked exception classes2. Unchecked exception class
Java.lang.RuntimeException and its sub classes are unchecked exception
classes. Except this class, all other sub classes of Exception class are checked
exceptions. Javas exception handling mechanism has provided 5 keywords to
deal with exceptions.
1. try2. catch3. throw4. throws5. finally
Try keyword is used to keep the doubtful code under observation. Catch is the
exception handler. Throw is used to explicitly throw exceptions. Throws
keyword is used to announce that a method has doubtful body. Finally
keyword is used to create a block of statements that execute definitely in boththe cases. I.e. in exception generated case and non-generated class also.
Q) Example program on exception handling.
//source code: - ArithmeticExample.java
class ArithmeticExample
{
public static void main(String[] args){
int numerator,denominator,quotient;
Numerator=Integer.parseInt(args[0]);
denominator=Integer.parseInt(args[1]);
try
{
quotient=numerator/denominator;
8/8/2019 Resource Material for JAVA
34/57
System.out.println(The result of division is:+quotient);
}
catch(ArithmeticException e)
{
System.out.println(please ensure that second argument is a non-
zero);
e.printStackTrace();
}
}//main
}//class
Observations to be made
1. At the command prompt we give the following command to run thisprogram. >java ArithmeticExample 12 2
2. Because of the proper input, no exceptions is raised and hence output ofthe program will be The result of division is 6
3. If exception is not raised, catch is not at all executed.4. If we supply the second command line argument 0, ArithmeticException
is raised in the try block and control comes to the catch block.
5. When the exception is raised, instead of program getting terminated, tryblock gets terminated.
6. The message in the catch block will be displayed to the end user.7. printStackTrace() displays the error type, error message and its originated
place.
Q) Example program on multiple catch blocks for a single try block.
//source code: - MultiCatchExample.java
class MultiCatchExample
{
public static void main(String[] args)
8/8/2019 Resource Material for JAVA
35/57
{
int numerator,denominator,quotient;
try
{
numerator=Integer.parseInt(args[0]);
denominator=Integer.parseInt(args[1]);
quotient=numerator/denominator;
System.out.println(The result of division is:+quotient);
}
catch(ArithmeticException e)
{
System.out.println(please ensure that second argument is a non-
zero);
e.printStackTrace();
}
catch(NumberFormatException e){
System.out.println(Only digits as arguments please.);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(Supply 2 arguments please);}
}//main
}//class
Observations to be made
1.
Whenever try block has doubtful code that may raise different kinds ofexceptions, we go for multiple catch blocks.
8/8/2019 Resource Material for JAVA
36/57
2. Even though multiple catch blocks are there, only one catch block isexecuted.
User defined exceptions
Our own created exceptions are known as user defined exceptions as we have
said earlier. In case of user defined exceptions, we have to define our own
exception class that extends java.lang.Exception or its sub class. Whenever our
application rule is failed, we treat it as an abnormal event and throw the user
defined exception.
Q) Example program on user-defined exception
class Voting Exception extends Exception
{
Voting Exception(String s)
{
super(s);
}
}
class Voting
{
static void diplayCandidateEligibilityForVoting(int age) throws
VotingException
{
if(age
8/8/2019 Resource Material for JAVA
37/57
int age=Integer.parseInt(args[0]);
try
{
Voting.diplayCandidateEligibilityForVoting(age);
}
catch(VotingException e) {
System.out.println(e.getMessage());
} }//main() }//class
Multithreading
A thread is said to be a sub process. As we know, a process is nothing but a
program under execution. If a process (application) has multiple sub processes
(threads), such application is known as a multithreaded application. How (and
why) to develop multithreaded Java applications is the goal of multithreading.
A single sequential flow of control OR an independent path of execution in a
process is known as a thread.
In Java, a thread is an instance of a class that extends java.lang.Thread class
or that implements java.lang.Runnable interface. Sometimes we create a thread
by directly instantiating the Thread class.
Thread Life cycle
Thread life cycle is described by the following four states.
1. new state2. active state (running/ready to run state)3. blocked state (suspended state)4. dead state
When a thread is created, it is said to be in new state. When the thread is in new
state, it will not have body. If we call start method on the thread object it
becomes active. If it is the only thread, it gets CPU cycles and it becomes
running. If multiple threads are there it becomes ready to run. If a thread is
8/8/2019 Resource Material for JAVA
38/57
taken out of service temporarily by calling sleep (), join() or wait(), it assumes
the blocked state. At that time it will not get CPU cycles. If the body of thread is
completely executed, the thread dies. Also, we can explicitly kill the threads.
To implement multithreaded applications, we define a class that extendsjava.lang.Thread class or implements java.lang.Runnable interface. If our class
is already extending some other class, we implement multithreading by
implementing Runnable interface.
To develop a multithreaded application we identify the number of concurrent
tasks our application has to perform and create as many number of threads.
Once we activate them, multiple independent paths are created and multiple
tasks are performed concurrently.
Q) Write a program that performs the following two tasks concurrently (at the
same time).
1. Printing hello 20 times2. Printing hai 20 times
/*
Source code: - MultiThreadingEXample.java
*/
class MyThreadOne extends Thread
{
public void run()
{
for(int i=1;i
8/8/2019 Resource Material for JAVA
39/57
System.out.println("hai");
}
}
class MultiThreadingExample
{
public static void main(String[] args)
{
MyThreadOne t1=new MyThreadOne();
MyThreadTwo t2=new MyThreadTwo();
t1.start();
t2.start();
}
}
The above program prints hello for few times and hai few times. Again
hello few times and hai few times.
Observations to be made1. We write task performing code in the run method. It acts as the body of
the thread.
2. When we called start method on the two threads, the threads are activatedand run method is called. Concurrently two flows are executed.
Q) Modify the above program using Runnable interface.
/*Source code: - MultiThreadingEXampleTwo.java
*/
class MyThreadOne implements Runnable
{
public void run()
{
for(int i=1;i
8/8/2019 Resource Material for JAVA
40/57
System.out.println("hello");
}
}
class MyThreadTwo implements Runnable
{
public void run()
{
for(int i=1;i
8/8/2019 Resource Material for JAVA
41/57
8/8/2019 Resource Material for JAVA
42/57
8/8/2019 Resource Material for JAVA
43/57
if(name.equals("one"))
a.x();
else
a.y();
}
}
class MultiThreadingExampleFour
{
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.setName("one");
t2.setName("two");
t1.start();
t2.start();
}
}
Thread Priorities
All threads have a priority that determines which thread is executed when
several threads are waiting for their turn. The possible values for thread priority
are defined as public static final integer values in Thread class.
1. MIN_PRIORITY (its value is 1)2. MAX_PRIORITY (its values is 10)3. NORM_PRIORITY (its value is 5)
The value of the default priority that is assigned to the main thread in a program
is 5. When we create a thread, its priority will be same as that of the thread that
created it. We can modify the priority of a thread by calling the setPriority()
method on the thread object. This method takes an argument of type int that
8/8/2019 Resource Material for JAVA
44/57
defines the new priority for the thread. This method will throw an
IllegalArgumentException if we supply a value beyond the range between 1 and
10. To know the priority of a thread we can call the method getPriority().
Actual priority of a thread that we set by calling setPriority() depends uponthe mapping between Java thread priorities and the underlying operating system
priorities. The thread-scheduling algorithm that the Operating System uses also
affects how our application threads execute and what proportion of the process
time they are allocated.
If we want to set the priority for a thread we have to do so before it is
activated.
For example,
MyThread t=new MyThread();
t.setPriority(6); t.start();
Q) Example program in which priority is set for a particular thread.
/*
Source code: - MultiThreadingExampleFive.java
*/
class MyThreadOne extends Thread
{
public void run()
{
for(int i=1;i
8/8/2019 Resource Material for JAVA
45/57
e.printStackTrace();
}
}//for
}//run
}
class MyThreadTwo extends Thread
{
public void run()
{
for(int i=1;i
8/8/2019 Resource Material for JAVA
46/57
MyThreadTwo t2=new MyThreadTwo();
t2.setPriority(7);
t1.start();
t2.start();
}
}
Observations to be made
1. The thread t1 has the priority of 5. 2. We have set the priority of t2 as 7.3. Even though t1 is activated first, thread scheduler assigns CPU cycles for t2
first as its priority is more than that of t1.
4. If priority of all the threads is the same, CPU cycles are allotted on firstcome first serve basis.
5. We are suspending t1 and t2 for 500 milliseconds in each iteration of theloop by calling the static method sleep().
6. As sleep() method throws a checked exception, we must handle it.
Thread synchronization
Whenever multiple threads are trying to access the same resource, allowing only
thread at a time is called Synchronization. Synchronization makes multithreaded
applications thread-safe. We can implement synchronization in two ways.
1. Method level synchronization2. Block level synchronization.
In both the cases we make use of the modifier synchronized.
We define whole method as synchronized in case of method level
synchronization. For example,
synchronized void withdraw(float balance)
{
//code
8/8/2019 Resource Material for JAVA
47/57
}
Once withdraw method is called on one object in one thread, the object is
locked. No other thread can call the withdraw method on that object unless
withdraw method is completely executed.We can apply synchronization at block level also.
synchronized(Object)
{
//code
}
When we implement block level synchronization, unless the code in that block
is completely executed, no other thread can access that objects synchronized
code.
Dead Lock
Whenever multiple threads have circular dependency on synchronized objects, a
nasty bug called deadlock occurs. Improper synchronization leads to dead locks.
Dead locks have to be prevented by designing the multithread application
properly. Once they occur, fixing them is very difficult.
Interthread Communication
Threads communicate one another using 3 methods of java.lang.Object class.
All these methods can be called only in the synchronized context.
1. wait()2. notify()3. notifyAll()
wait():-Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object. The current thread
must own this object's monitor. The thread releases ownership of this monitor
and waits until another thread notifies threads waiting on this object's monitor to
wake up either through a call to the notify method or the notifyAll method. The
http://e/jdk1.6docsdocsapijavalangObject.html%23notify()http://e/jdk1.6docsdocsapijavalangObject.html%23notifyAll()http://e/jdk1.6docsdocsapijavalangObject.html%23notifyAll()http://e/jdk1.6docsdocsapijavalangObject.html%23notify()8/8/2019 Resource Material for JAVA
48/57
thread then waits until it can re-obtain ownership of the monitor and resumes
execution.
notify(): - Wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be awakened.The choice is arbitrary and occurs at the discretion of the implementation. A
thread waits on an object's monitor by calling one of the wait methods. The
awakened thread will not be able to proceed until the current thread relinquishes
the lock on this object. The awakened thread will compete in the usual manner
with any other threads that might be actively competing to synchronize on this
object; for example, the awakened thread enjoys no reliable privilege or
disadvantage in being the next thread to lock this object. A thread that is the
owner of this objects monitor should only call this method. A thread becomesthe owner of the object's monitor in one of three ways:
1. By executing a synchronized instance method of that object.2. By executing the body of a synchronized statement that synchronizes on
the
object.
3. For objects of type Class, by executing a synchronized static method of
that class.
Only one thread at a time can own an object's monitor.
notifyAll(): -Wakes up all threads that are waiting on this object's monitor. A
thread waits on an object's monitor by calling one of the wait methods. The
awakened threads will not be able to proceed until the current thread
relinquishes the lock on this object. The awakened threads will compete in the
usual manner with any other threads that might be actively competing to
synchronize on this object; for example, the awakened threads enjoy no reliableprivilege or disadvantage in being the next thread to lock this object. A thread
that is the owner of this objects monitor should only call this method.
8/8/2019 Resource Material for JAVA
49/57
IOStreams
Java programs perform input and output operations through streams. A stream is
an object that takes information from the Java program or that gives information
to the Java program. A stream is attached to a physical device. All streamsbehave in the same manner, even though they are connected to different
devices. Therefore, we can develop device independent programs. We have 2
kinds of streams.
1. Byte streams2. Character streams
Byte streams are used to handle input and output of binary data and hence they
are also known as binary streams. Java.io.InputStream and
java.io.OutputStream are the top level classes that represent binary or byte
streams.
Character streams are used to handle input and output of characters. They use
Unicode and hence internationalization is possible. Java.io.Reader and
java.io.Writer are the top level classes that represent character streams.
Reading data from the keyboard
Java.io.DataInputStream and java.io.BufferedReader classes can be used to
accept input from the keyboard in convenient way.
Q) Program to read data from keyboard.
/*
Source code: - Keyboard.java
*/
Import java.io.*;
Class Keyboard
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
8/8/2019 Resource Material for JAVA
50/57
System.out.print("Enter your name:");
String name=dis.readLine();
System.out.println("Hello !"+name);
dis.close();
}
}
Observations to be made
1. System.in represents the keyboard2. This program gives warning about deprecation of readLine(). Even then it
works.
3. DataInputStream is a binary stream4. Instead of handling the IOException, we are passing it.
Q) Program to read data from the keyboard using character oriented streams.
import java.io.*;
class Keyboard
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in);
System.out.println("Enter book title:");
String name=br.readLine();
System.out.println("Enter author:");
String author=br.readLine();
System.out.println(Enter price:);
float price=Float.parseFloat(br.readLine());
System.out.println("Book details....");
System.out.println("Title:"+name);
8/8/2019 Resource Material for JAVA
51/57
System.out.println("Author:"+author);
System.out.println(Price:Rs.+price);
br.close();
}
}
Observations to be made
1. System.in cannot be directly supplied as argument to the BufferedReaderconstructor.
2. InputStreamReader converts the binary stream System.in into character-oriented stream.
3. readLine() method returns String.4. By calling the Float.parseFloat(), we are translating the string
representation of float value into actual float value.
Reading from the file
To perform reading operation from the files we have FileInputStream and
FileReader. To perform reading operation, first of all we create the streamobject.
FileInputStream fis=new FileInputStream(filename);
OR
FileReader fr=new FileReader(filename);
When we perform read operation on the stream, we get the file contents. Once
read operation is done, we need to close the stream.
Q) Program to read the contents of a disk file and display the contents.
Import java.io.*;
class FileReading
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream(args[0]);
8/8/2019 Resource Material for JAVA
52/57
int c=fis.read();
While(c !=-1)
{
System.out.println((char)c);
c=fis.read();
}
fis.close();
}//main()
}//class
Observations to be made
1. File name is supplied as command line argument to the FileInputStreamconstructor.
2. read() method reads the next byte of data from the input stream. Thevalue byte is returned as an int in the range 0 to 255. If no byte is
available because the end of the stream has been reached, the value -1 is
returned. This method blocks until input data is available, the end of the
stream is detected, or an exception is thrown.
3. To print the character of the corresponding int value we are type casting itto char so that the character is printed on the screen.
Q) Program to read the contents of a disk file using character oriented stream.
/*
Source code: - FileReading.java
*/
import java.io.*;
class FileReading
{
public static void main(String[] args) throws IOException
{
8/8/2019 Resource Material for JAVA
53/57
FileReader fr=new FileReader(args[0]);
int c=fr.read();
while(c !=-1)
{
System.out.println((char)c);
c=fr.read();
}
fr.close();
}//main()
}//class
Observations to be made
1. FileReader is used instead of FileInputStream.2. Reading logic remained the same when compared to FileInputStream.
Reading a file efficiently
To improve the performance of reading we make use of BufferedInputStream incase of byte streams. Where as in case of Character oriented streams,
BufferedReader is used.
Q) Example program that reads the contents of a disk file efficiently
/*
Source code: - ReadEfficiently.java
*/
import java.io.*;
class ReadEfficiently
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader(args[0]);
BufferedReader br=new BufferedReader(fr);
8/8/2019 Resource Material for JAVA
54/57
String line=br.readLine();
while(line !=null)
{
System.out.println(line);
line=br.readLine();
}
br.close();
}//main()
}//class
Observations to be made
1. readLine( ) method returns one line of text. If it encounters the end of file,it returns null.
2. Once the outer stream is closed, inner stream also will be closed.
Writing into the file
In order to store some information into the file from the Java program, we make
use of either FileOutputStream or FileWriter.FileOutputStream fos = new FileOutputStream(filename);
OR
FileWriter fw = new FileWriter(filename);
In both the cases, if file already exists, its contents will be overwritten. If the
specified file is not there, a new file with that name is created.
Ex: Write a program to store some information into a disk file using byte
oriented stream.
/*
source code: - StoringIntoFile.java
*/
import java.io.*;
class StoringIntoFile
{
8/8/2019 Resource Material for JAVA
55/57
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("one.txt");
String s="This will be stored into file";
byte b[]=s.getBytes();
fos.write(b);
fos.close();
}//main()
}//class
Observations to be made
1. write() method of the FileOutputStream does not take String as the argument.
It takes byte array as the argument. Therefore, by calling getBytes() method of
the String class, the string is converted into byte array and is supplied as
argument to it.
2. After writing operation is over, the stream is closed.
Ex: Write a program to store some information into a disk file using character
oriented stream.
/*
source code: - StoringIntoFile.java
*/
import java.io.*;
class StoringIntoFile
{
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("one.txt");
String s="This will be stored into file";
fw.write(s);
fw.close();
8/8/2019 Resource Material for JAVA
56/57
}//main()
}//class
Observations to be made
1. Being a character-oriented stream, FileWriter class takes String as theargument directly.
2. If we want to append the content of the file rather than overwriting itscontents, we have to supply appendability indicating true value as the
second argument to the constructor of the FileWriter OR
FileOutputStream
8/8/2019 Resource Material for JAVA
57/57