Core Java Book by Paresh Bhavsar Version 3.0
Core Java Book by Paresh Bhavsar Version 3.0
Core JAVA
Paresh Bhavsar
(BE - DDIT, SCJP-Sun Inc., MBA)
www.j2eetrainer.com / [email protected]
Table of Contents
Chapter 3 : OOP - Object Oriented Programming (Inheritance, Encapsulation and polymorphism) ... 21
Appendix : Differences
Exercise
4. Create a java program which will print number between 100 to 200
using for loop, do while loop and while loop
Computer understands machine language meaning that it understands only binary (0s and 1s). And
human can not instruct computer As you are a programmer and human being it is impossible to give
instruction to computer in 0s and 1s. So we need a programming language by which we create
English type instructions. To covert english instruction into binary instructions we need compiler. So
basic job of compiler to concert english instructions into binary instruction called machine language.
Compiler is required only when we create source file. In c language source file is created with .c
extension while in java source file is created using .java extension. C compiler will convert .c program
in machine language (.exe file for windows machine) while java compiler convert .java file into .class
file called as byte code.
From the diagram 1.1 it is clear that we have c compiler which takes .c source file and generates .exe
file. This executable file can be run by the OS directly. There is no need to have compiler once we
have executable file.
From the diagram 1.2 it is clear that java compilation process takes .java file and if no compilation
table it generates .class file. This .class file is NOT executable code. We CAN NOT run .class file
directly on the OS. We would require JRE (Java RunTime Environment) for running .class file.
So it is clear that .class file will require run time env. named as JRE to run byte code. Byte code is
interpreted and converted into the OS code on the fly using JRE.
Above figure states that java byte code can run on any operating system. Meaning that we do not
need again re-compile the code each OS. For example, if we need to run C language code on
windows and Linux operating system, we require to compile the source code (.c file) on each
operating system and so there will be two different executable code. One for Windows and one for
Linux.
In case of java, to run byte code on mac operating system, we will have ‘MAC JVM’ installed on the
mac OS. Mac JVM will convert byte code into the executable code of the mac os. So using JVM we
are able to run byte code (which was created using compilation on Windows OS). This way java is
“Compile Once Run Anywhere” language (platform indepdent).
b. Java is Portable – Java code can be transferred from one machine to another machine
d. Network Centric – Using network classes java.net package (e.g. Socket & ServerSocket)
classes) java programmer can very easily write program for network application. It is
unbelievably easy to write any network related application using java.
e. Security – Java is designed and created with security features in mind. It allows user to
download un trusted code from internet and run in on the machine without any harm. It
cannot infect the machine with virus etc.
f. Dynamic and Extensible – Java Code is extensible and dynamic as java is object oriented
language. Classes are stored in separate files and they are loaded only when need using
JRE.
g. Performance – Java language allows programmer to write thread based program which
essentially allow better utilization of resources (i.e. CPU, memory etc.). Java consume
much lesser resource due to light weight thread concepts. As java’s bytecode is
interpreted by JRE at run time, its performance is slightly slower compare to other
language e.g. C / C++.
h. Java is Open Source – Development cost of creating java based software is much lower
compare to other languages like .net as java is freely downloaded and most of the tools
around developing java based application are free. Programmer can also get benefit of
looking at the java code as java source code is accessible to programmers.
JDK is having bin directory having javac.exe and java.exe files inside it
JRE is having bin directory and it will NOT have javac.exe file
If you type javac on the command prompt and get below mentioned screen meaning
that windows path variable is not pointing to your java directory. Below mentioned will
help you out in adding path variable from mycomputer -> right click -> system
properties -> advance ->enviournment variable -> user variables ->new . Variable name
will be path and variable value will be upto bin directory of jdk installation. E.g.
(C:\Program Files\Java\jdk1.6.0_11\bin)
Once you add path variable ,existing command should be closed and restarted.
To check the version of java please type java –version on command prompt
Command prompt should display below mentioned when we type javac now.
This Test.class is called as byte code and to run Test.class we require JVM as discussed
earlier.
class Test {
for(int y=0;y<10;y++){
System.out.println(y);
}
} // method ends
} // class ends
double random = Math.random(); // Math class is java defined class having random
// function which return double.
int randomInt = (int) random; // we are explicitly converting double number into int so
// our random number will be between 0 to 50 now.
5. Create a java program which will print number between 100 to 200
using for loop, do while loop and while loop
public class Test {
for(int x=100;x<=200;x++){
int x = 100;
while(x<=200){
x++;
int x = 100;
do {
x++;
int x = 23;
if(x<=50){
System.out.println("Value is less than or equal to 50");
} else if(x<=100){
System.out.println("Value is between 50 to 100.");
} else {
System.out.println("Value is greater than 100");
}
} // end of main method
Exercise
1. Create a class of type Box which will have three attributes width,
height and depth of type double. Create two object of the Box class.
Assign the values using setValues method and print using printValues
method.
Fundamentals
Simplest definition of class is “Class is blueprint from which individual Objects are created”.
For example, in below mentioned example, We have Student class. Student class is having
two instance variable name as String type and rollno as integer type.
class Student {
Int rollno;
String name;
}
Each student object will have its own rollno and name. For example, if we will create 60
student objects from the Student class created above, each student object can access its
own copy of instance variable named as rollno and name.
Below mentioned class creates two object of the Student class. Each object is referred using
s1 and s2.
class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student(); // s1 is called reference which is pointing to object
Student s2 = new Student(); // another object created pointed by s2
Student s3 = null;
} // end of main method
} // end of class
In above example we are created three references of the student class (s1,s2 and s3). S1 and
s2 points to valid objects while s3 does not point to any object. S3 is just reference pointing
to null memory location.
rollno = 0
S1
name = null
rollno = 0
S2
name = null
Above image makes it clear that each object is having its own copy of instance variable. As name is
String type and we have not assigned any value it is null. But rollno is of integer type so its default
value is 0. It is important to note that ‘new ‘ keyword in java creates object. We are creating object
of class Student which is pointed by reference of Student class (e.g. s1).
Note:
_______________________________________________________
Java Primitive types (int, short, long, double, char, boolean, float byte etc. will have default value
which is assigned to instance variable while creating an object.. String is a java class so it is
pointing to null.
Each object can be pointed by more than one reference. e.g. in below example we are creating only
one object but it is pointed by two references.
class StudentDemo {
} // end of class
rollno = 0
S1 S2
name = null
From above example we have two references pointing to the same object. If we try to modify value
using one reference, all references pointing to that object will be updated. This is because r1.rollno
and r2.rollno both points to same object .
Object is instance of class, created using new keyword. It can have attributes (instance variable) and
functions / methods. Below mentioned Student class is having now printData function which is
printing the values of the rollno and name on the console.
class Student {
Int rollno;
String name;
void printData() {
System.out.println(“Roll no is “ + rollno);
System.out.println(“Name is “ + name);
} // end of method
void setValues(int rollno, String name) {
this.rollno = rollno;
this.name = name;
} // end of method
} // end of class.
Now it is possible to call the print method from the reference s1 and s2 we have defined earliest. We
can call s1.printData() which will print the values. setValues function accepts two parameters
defined as rollno and name, these two parameters are called local variables because these variables
are created at the time of function call. As soon as method is finished these variables are destroyed.
This is how stack memory works (LIFO – Last In First Out).
Note:
________________________________________________________
__
Local variables are always created on stack memory. Stack memory is part of RAM. Objects are
created on HEAP memory. Heap memory is also part of RAM. In our case instance variables rollno
and name are created on Heap memory while local variables rollno and name (which defined in
the arguments of setValues method are created on RAM memory.
Let’s understand the statement ‘this.rollno=rollno’. We have java keyword ‘this’ which helps us out
in pointing to the instance variable. As we have rollno defined as the local variable as well as rollno
defined as instance variable and we want to pass value from instance variable to local variable we
are using this keyword.
Below is complete example of creating two objects, assigning values using method and calling
method to print instance variable values.
class Student {
int rollno;
String name;
void printData() {
System.out.println (“Roll no is “ + rollno);
System.out.println (“Name is “ + name);
} // end of method
void setValues(int rollno, String name) {
this.rollno = rollno;
this.name = name;
} // end of method
} // end of class.
class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student (); // s1 is called reference which is pointing to object
Student s2 = new Student (); // another object created pointed by s2
s1.setValues (10,”Sachin”);
s2.setValues (20,”John”);
s1.printValues ();
s2.printValues ();
} // end of main method
} // end of class
Constructor has two major characteristics. One it does not have return type. Second constructor
name and class name is always same. If method does not return any value we declare method return
type as void. We will take Student class example and understand the constructor for Student.
class Student {
Int rollno;
String name;
Student(){
rollno = 1;
name = ”-”;
}
void printData() {
System.out.println(“Roll no is “ + rollno);
System.out.println(“Name is “ + name);
} // end of method
void setValues(int rollno, String name) {
this.rollno = rollno;
this.name = name;
} // end of method
} // end of class.
In the above code we have created a Student class constructor. This constructor objective is to
initialize the default values of the Student instance variables. This constructor is called default
constructor as it does not accept any parameters. We can also create a parameterized constructor
which can accept parameters (local variables) as arguments. For example,
This constructor is called parameterized constructor. One class can have one or more constructor.
When our Student class declares one default constructor and one parameterized constructor it is
called constructor overloading.
Constructors are used for initialization of the object parameters (state). As method can be called any
number of times using dot (.) operator with the reference, we can call constructor only during the
object creation time. Below example creates object using default constructor and parameterized
constructor.
Student s1 = new Student() ; // s1 will have rollno = ‘1’ and name as ‘-‘
Student s2 = new Student(24 , ”John”); // s2 will have rollno = ‘24’ and name ‘John’
Within the same class constructor can call another constructor using this. For example we can call
parameterized constructor from default constructor and initialize values.
Student() {
this (1 , ” – “);
It is important to note that constructor can be called only from the first statement. Meaning that
one constructor can NOT call two constructor using this. Object can be initialized any of the below
mentioned way.
Below mentioned example initialize the values of the object using constructor, we do not require to
have setValues method.
class Student {
int rollno;
String name;
Student() { // default constructor
rollno = 1;
name = “-“;
}
Student( int rollno, String name) { // paramerized constructor
this.rollno = rollno;
this.name = name;
}
void printData() {
System.out.println (“Roll no is “ + rollno);
System.out.println (“Name is “ + name);
} // end of method
} // end of class.
class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student (); // s1 is called reference which is pointing to object
Student s2 = new Student (24,”John”); // another object created pointed by s2
s1.printValues ();
s2.printValues ();
} // end of main method
} // end of class
The benefit of above example is we are reducing no. of statement. Our main method requires only
two statements to create two objects as well as assign values to instance variable.
5. Every java class has default constructor. If programmer does not create
a default constructor java creates default constructor.
7. One Constructor can call another constructor using this. Calling must
be first statement only.
Exercise
1. Create a class of type Box which will have three attributes width,
height and depth of type double. Create two object of the Box class.
Assign the values using setValues method and print using printValues
method.
class Box {
double width;
double height;
double depth;
class BoxDemo {
public static void main(String[] args) {
Box box1 = new Box();
Box box2 = new Box();
box1.setValues(10.20,30.5);
box2.setValues(11.21,31.5);
box1.printValues();
box2.printValues();
}
}
1. Explain what is inheritance what are the benefits of inheritance and how does java
supports inheritance with an example?
4. Explain abstract class and interface? What is the difference between abstract class
and interface? Explain with an example.
7. Explain Multiple and multilevel inheritance with respect to class and interfaces?
Fundamental
1. Explain what is inheritance what are the benefits of inheritance and how does java
supports inheritance with an example ?
Different types of object have certain types of characteristics common in them. For
example, as we have seen student class in previous chapter we can have EnggStudent and
ScienceStudent class. Both these classes will have rollno and name associated with them. So
instead of declaring rollno and name as instance variable in the both class, we can create a
super class (called as parent class also) in which we can define rollno and name.
Student
rollno
extends extends
name
EnggStudent CommerceStudent
rollno rollno
name name
Note:
________________________________________________________
extends is a keyword in java. Using extends keyword properties of super class are inherited in sub
class. Private properties of the super class can not be inherited.
class Student {
int id;
String name;
}
class StudentDemo {
public static void main(String args[]) {
EnggStudent s1 = new EnggStudent();
CommerceStudent s2 = new CommerceStudent();
s1.rollno = 10;
s2.rollno = 20;
s1.name = “Ramesh”;
s2.name = “Suresh”;
}
}
Above example we are creating two objects, one of EnggStudent and second of
CommerceStudent. If you notice extends keyword in java allows us Student class inherited
by EnggStudent and CommerceStudent class. Due to inheritance we are able to assign
properties (rollno and name) to EnggStudent and CommerceStudent Object using dot (.)
operator.
It is clear from the above example that inheritance eliminates repetition / duplication of
declaring variables in subclasses. Inheritance also supports re-usability of class attributes
and behavior.
Encapsulation is the technique of making the fields private in the class. Using private keyword, java
support encapsulation. Once we declare any attribute as private it is not inherited in sub-class.
Private fields are not accessible outside the class. Encapsulated fields (private fields) are accessible
using public methods (setter & getter methods). For example in the below example we are declaring
rollno and name as private field. We are writing setter and getter methods so that our fields are
accessible outside class. But direct access using dot(.) operator is now stopped.
class Student {
private int rollno; // id and name can not be accessed outside
private String name; // the class now.
class StudentDemo {
public static void main(String args[]) {
Student s1 = new Student();
s1.rollno = 10; // private property not accessible outside class.
s1.setRollno(10); // setting property using setter method. (public method)
}
}
Benefits of encapsulation :
1. The fields of the class can be made read - only (if there is no setter method in the class).
2. The fields of the class can be made write-only (if there is no read method)
3. Fields are protected, as direct access (using dot operator) with the field is not available.
Now let’s understand encapsulation from inheritance point of view. As we have already discussed
private fields are not inherited in the sub-class, but since our getter and setter methods are public
the fields are accessible to the sub-class or it instance using setter method. In below example we are
having EnggStudent class instance accessing the field of the parent class Student.
class StudentDemo {
public static void main(String args[]) {
EnggStudent s1 = new EnggStudent();
s1.rollno = 10; // private property not accessible outside class.
s1.setRollno(10); // setting property using setter method. (public method)
As many times benefits of the encapsulation is not clear below example will make it clear. For
example if we write setter method so that setter does not set value of the rollno negative.
From above example it is clear that now user can set only positive value of the rollno. In
case if do not declare private field, as rollno will be accessible directly by object it can set
any value for e.g. s1.rollno = -10; (if no encapsulation – rollno is NOT private)
Poly means many. When we have one behavior which is implemented in many ways we
can achieve polymorphism. For example below, we have two constructor of the Student
class. Default constructor and parameterized constructor. This is called constructor
overloading. We can also have method overloading, in below example we have
setValues method with two arguments and another method with one argument only.
class Student {
private int id; // id and name cannot be accessed outside
private String name; // the class now.
public Student() {
}
It is clear from above example that names of the method remains the same which is
setValues. There is change in no. of parameters. Now when Student class object needs to
call setValues method it can call setValues method with one Parameter or with two
parameters. This is clear with below mentioned image taken from netbeans IDE 7.0.
In case with constructor overloading, we can create Student Class object by either default
constructor or using parameterized constructor. Below mentioned image explains the same.
Term Static polymorphism is also called static binding because compiler decides which
method to be called. (whether to call setValues method with one parameter or setValues
method with two parameters).
4. Explain abstract class and interface? What is the difference between abstract class and
interface? Explain with an example.
Abstract class can not be instantiated (object can not be created). It is because abstract classes are
not complete. To declare an abstract class in java atleast one of the method of the abstract class
should be abstract. To create an abstract class we need to use abstract keyword before class name.
To create abstract method we need to use abstract keyword before return type of the method.
Abstract method does not have body (curly brackets). Let’s take an example and understand.
abstract int getTotalMarks(); // note : method does not have body. It ends with semi-
colon.
In above example we have created an abstract named as Student. Student class must have atleast
one abstract method. As we have mentioned that main purpose of the abstract class is to be
extended, we have two classes EnggStudent and CommerceStudent which extends Student class.
EnggStudent and CommerceStudent class are called concrete classes because these classes does not
have any abstract method.
EnggStudent class and CommerceStudent class MUST implement the abstract method which is
inherited (due to extends Students). In case if EnggStudent or CommerceStudent does not
implement the abstract method, it MUST be declared abstract also. Let’s understand from below
example.
int getTotalMarks() {
return 100; // getTotalMarks implemented and return value is 100.
}
}
int getTotalMarks() {
return 70; // getTotalMarks implemented and return value is 70.
}
}
Above example has two implementation (one method return 70, while other application returns
100) of the getTotalMarks method. As Student is an abstract class and we have inherited
getTotalMarks which is an abstract method, EnggStudent and CommerceStudent class MUST
implement the abstract method else compilation will be failed. If CommerceStudent does not
implement getTotalMarks method, we must declare CommerceStudent as abstract class. For
example as below mentioned we have CommerceStudent class which does not implement the
abstract method, so CommerStudent is declared as an abstract class.
int getTotalMarks() {
return 70; // getTotalMarks implemented and return value is 70.
}
}
As we are clear with abstract class and abstract method, now let us understand interface. Interface
is called pure abstract class. Interface has ALL abstract methods. Abstract class can have non-
abstract method (concrete method). Below mentioned example explains Interface.
interface Student {
By default all methods in the Student interface are abstract and public. So there is no need to
declare those methods as public and abstract. Now if we have CommerceStudent and EnggStudent
classes which implement this interface below mentioned example
Here we are using implements keyword. Implements keyword allows classes to implement Student
interface.
We have seen that static polymorphism is achieved using method overloading. To understand
dynamic polymorphism let’s first understand method overriding concept. Method overriding is
achieved by keeping method signature same. Method signature includes return type, name of the
method and arguments. For example, if we have printStudent method to be overridden we will write
the printStudent method with the same signature in the sub-class. Below mentioned example
explain the same concept.
class Student {
int id;
String name;
class StudentDemo {
}
}
Ideally we should have created reference of the Student Class which is pointing to the object of
Student class, EnggStudent and ScienceStudent.
class StudentDemo {
}
}
CommerceStudent
EnggStudent
rollno
rollno
name
name
6. Explain Garbage Collection? Explain finalize() method from the Garbage Collection
point of view.
Garbage collection is mechanism in java by which objects which are no longer reference by any
reference variable is garbage collected. Meaning that memory occupied by those object will be re-
usable. The real benefit is java programmer does not need to worry for how and when object will be
garbage collection. Let’s understand using an example.
Here we are creating an object referenced by s1. When s1 = null executes, object we created is no
longer referenced using any of the reference. So object will get garbage collected. Let’s take another
example.
Above statements creates two objects of Student class. Second object is also pointed by the same
reference we have created. As one reference can point only to one object at point of time, after line
no. 2 object created on line no. 1 can be garbage collected.
Garbage collection process scans through all the objects and if any of the object does not have ANY
reference pointing to that object that object is garbage collected. Let’s take another example and
understand garbage collection.
Here, we are creating only one object which is pointed by two references. Even though s1 is pointing
to null, object created on the first statement will NOT be garbage collected because reference s2 is
still pointing to the object.
Garbage collection is an automatic process and there is no guarantee when garbage collection will
be called. Every java programmer must understand the garbage collection so that right code can be
written. Many of the memory leak issues are because garbage collector is not able to garbage collect
object.
In the languages like C++, it is job of the programmer to call destructor function programmatically.
In case if the programmer forgets to call destructor function, object will reside in the memory. This
creates slowness in the program when run for longer period of time.
Java’s Garbage collection objective is to free programmer by not worrying about garbage collection.
Garbage collector is background thread continuously checking if any object is not referenced and if
so, it calls finalize() method of the object. If object needs to release some resources which are
occupied (e.g. file open, database connection open), programmer should write down releasing of the
resource code in the finalize() method. These are the actions to be performed when the object is
destroyed by garbage collector.
The finalize () method has below mentioned form. Java defined Object class has finalize method and
when programmer writes it for the class, we override the finalize method from Object class.
Here, protected keyword will ensure that method will not be called outside the class.
It is important to note that finalize() is called only just prior to garbage collection. It is not called after
object is destroyed. These means that programmer should write down code of releasing resources
used by the object.
7. Explain Multiple and multilevel inheritance with respect to class and interfaces?
As we have seen that extends keyword of java provides inheritance support as an object oriented
language. There are two kind of inheritance. Multiple and Multilevel.
Car
RacingCar
RacingCar
From above image it is clear that we need to write down below mentioned code to create MultLevel
Inheritance.
As we can see from above example that multilevel level inheritance is possible in java. But in case
with multilevel inheritance, RacingCar class is inheriting Car and Vehicle Class. As per java
specification it is not possible to extend two classes. This means that java does NOT support Multiple
Inheritance.
Two interfaces can be implemented by class. So java supports multiple inheritance partially. For
example,
One interface can extend another interface, but again one interface can not extend two interfaces.
One class can extend another class and at the time it can implement one or more interfaces too.
Fundamentals
1. Explain java keyword static with an example. What are the benefits of static
keyword and what precautions to be kept while declaring static variable in java ?
2. Explain final keyword. Explain use of final keyword for before method / class or
variable ? Also explain super keyword,
3. Explain java API. Give overview of java inbuilt classes Math class, String class and
StringBuffer class and File class.
1. Explain java keyword static with an example ? What are the benefits of static keyword and
what precautions to be kept while declaring static variable in java ?
class is description of Object. All variables (instance variable) defined in the class belongs to object.
Each object has its own copy of instance variable. In the example below we have two student
objects and each has its own copy of rollno and name.
class Student {
private int rollno;
private String name;
}
Student
rollno = 0
S1
name = null
Student
rollno = 0
S2
name = null
Now let’s declare another variable but we will mark that variable as static.
class Student {
private int rollno;
private String rollno;
private static schoolName;
}
In above example we are declaring schoolName as static. Static variable refers to class, while
instance variable refers to the object. So every object of the Student class will NOT have its copy of
schoolname instead all objects will refer to schoolName which is with Student class. In simple terms
static always belongs to class and it does not have anything to do with the object.
rollno = 0
S1
name = null
SchoolName
Student
rollno = 0
S2
name = null
In above image both the objects s1 and s2 refers to the same schoolName as schooName is declared
static. As rollno and name are instance variable (non-static) each object is having its copy, while
schoolName is having only copy which is referred by s1 and s2.
Static can be accessed directly by class. For e.g. to set the value of the schoolName we can write
directly Student.schoolName = “Java Training School”. Now if any object is referring / changing the
schoolName will change copy of all object. Let’s take below mentioned example and understand it.
Please note that static can be accessed by
The way we have define static variable, we can also declare method static also. Static methods can
access only static variables or methods. Let’s take an example and understand it.
class Student {
int id;
String name;
static String schoolName;
class StudentDemo {
public static void main(String args[]){
Student.schoolName = "J2eetrainer.com"; // accessing static variable using class name
Student s1 = new Student();
System.out.println("School name is " + s1.schoolName); // reference calling static variable
Student s2 = new Student();
s2.schoolName = "java.oracle.com"; // reference changing value of static variable
System.out.println ("School name is " + s1.schoolName);
// now new schoolName will be printed as there is only one copy of the schoolName
}
}
We can also declare static method inside class. One of the reason for declaring static method inside
class is there is no need to create object that class to call the method. For e.g. we have Math class in
java where almost all methods are declared as static. To call methods from Math class there is no
need to create object of Math class. E.g. Math.random(). random() is a static function defined in the
Math class.
class StudentDemo {
}
}
2. Explain final keyword ? Explain use of final keyword for before method / class or
variable ?
Final is keyword in java which has multiple usage. Below mentioned is brief about final keyword
1. final before class will not allow class to be extended. (final class can not be inherited)
Say EnggStudent is a class which should not be extended. Question is why do we need to stop
inheritance ? We would not like to allow our class to inherited so that its functionality can not be
modified. For e.g. java has declared Math class as final class. So that we can not inherit Math class in
our class and can not override any function.
final class EnggStudent extends Student { // now we can not extend EnggStudent
class Student {
}
}
Note:
________________________________________________________
final variables are normally static variable. This is because final variables creates constant and it
should be associated with class instead of with object.
Super Keyword :
As we have seen this keyword refers to current object / instance. Same way super refers to parent
object / instance. We have call attributes or method of super class by using dot(.) operator with
super-class. Super is also used to call constructor of the super class from the sub-class.
class Student {
private int rollno;
private String name;
Student(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
void print () {
System.out.println(“You are student”);
}
}
class EnggStudent extends Student {
EnggStudent(int rollno, String name) {
super(rollno, name); // calling super class constructor
}
void print() { // over-ridden method
System.out.println(“You are Engineering student”);
super.print(); // calling super class print method
}
}
class StudentDemo {
public static void main(String args[]) {
EnggStudent eng = new EnggStudent(10,”Paresh”);
eng.print();
}
}
3. Explain java API. Give overview of java inbuilt classes Math class, String class and
StringBuffer class and File class.
We have understood java installation and its directory structure. Below mentioned is directory
where java in-build classes are stored.
Inside lib directory file called rt.jar file contains all java classes. Some of the java packages are
mentioned below.
Please note that there are more than 3000 java defined classes and it requires time for java
programmer to understand the use classes. We have tried to cover up all basics classes required to
be used in java programming.
Let’s understand Math class now. Math class is defined in java.lang package. As explained earlier
java.lang package is imported automatically without writing down import statement. Most of the
methods of the Math class is static. So there is no need to create object of the Math class.
Note:
________________________________________________________
All java classes first character is always capital. As a programmer we should also follow that
discipline. If programmer wants to create his own class, it is advisable to ensure that first
character is capital. To create our own class with name MyMath, first character of the class and
when the word changes we should keep first character capital.
class MyMath {
public static void main(String args[]) {
System.out.println(Math.ceil(10.2));
System.out.println(Math.floor(10.2));
System.out.println(Math.max(10.2,10.3));
System.out.println(Math.min(10.2,10.3));
System.out.println(Math.round(10.55));
System.out.println(Math.pow(2, 3));
System.out.println((int)(Math.random()*100));
}
}
Now let’s understand String class. Even though string is class we can declare String variable as if we
are creating a variable. There is no need to create object. For e.g. String name = “John”; Here we
have created object of the String class and store the value John into the same.
String objects are immutable. Meaning that even though there is no reference to the string object,
string objects are not garbage collected. So in case if we are looping through String using for loop,
we should NOT use concatenation operator. Instead we should use StringBuffer class. Below
mentioned example we are concatenating String in for loop. As we have said that string objects are
immutable, there will be 100 objects of the String will be created. String object if no longer accessed
by any reference are writing to String Pool.
class StringDemo {
public static void main(String args[]) {
String name = "xyz";
for (int i=0;i<100;i++){
name += i;
} // end of for loop
System.out.println(name);
} // END of main method
} // end of StringDemo class
Above example should be written using StringBuffer. StringBuffer class is not immutable and at the
same time it has append method. There is only one object of StringBuffer class is being created in
the memory.
class StringDemo {
public static void main(String args[]) {
StringBuffer name = new StringBuffer("xyz");
for(int i=0;i<100;i++){
name.append(i);
}
System.out.println(name);
} // END of main method
} // end of StringDemo class
So the rule is never use String class if we are using + operator in loop. Better to use StringBuffer. You
might need to know what is the reason being java is having String class as immutable object.
Immutable means that original copy can not changed. In case with String class there are high
chances that same content string is being created again, in that case instead of creating new object
java checks first String pool. If the object is NOT available in string pool, only then there is need to
create object.
We would like to take a very simple example and understand what went wrong when exception
occurs. Below mentioned java program takes two command line argument, convert String
parameter into number.
class TestException {
public static void main(String args[]) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
System.out.println(first/second);
System.out.println ("Hello Java");
}
}
As we can see from the below mentioned image that first time running program with command line
argument does not generate exception. When running program with command line argument and
passing second argument as 0 generates an exception. Whenever exception is generated program
stops excecution. In below mentioned image the same is shown.
Whenever we convert the string into the number there are chances that another exception which
can be generated called as NumberFormatException. While running the program if we will provide
the command line argument is ‘a’, while trying to covert it in number using Integer.parseInt,
exception is thrown.
As we have seen some of the occurance of the exception let’s understand now the exception
handling. Java provides try block by which exception can be handled. Try block is also called as
guarded block in which programmer will normally place those statements which can generate
exception. For Example, as shown below string to number conversion can throw
NumberFormatException we will place both those statements in try block.
try {
int x = Integer.parseInt (args[0]);
int y = Integer.parseInt (args[1]);
} catch (NumberFormatException e){
System.out.println(“ ERROR : Please Enter number only from command line argments”);
e.printStackTrace();
return;
}
With try block we have catch block which is called whenever exception occurs. Note that catch will
NOT be called if exception does not occur. Once we handle exception program continues. One try
block can have more than one catch block. For example, below we can handle ArithmeticException.
try {
int x = Integer.parseInt (args[0]);
int y = Integer.parseInt (args[1]);
} catch (NumberFormatException e) {
System.out.println(“ ERROR : Please Enter number only from command line arguments”);
e.printStackTrace();
return;
} catch (ArithmeticException e) {
System.out.println(“ ERROR : Please Do NOT provide second number as ZERO. ”);
e.printStackTrace();
return;
}
Note that at any point when the exception is generated in the try block, remaining statements from
the try block will not be executed.
Below mentioned are some of the key points for exception handling.
1. Try block is called guarded block in which we place those statements which can
generate exception.
2. Try without catch and catch without try is not possible.
3. Catch block is executed only if exception occurs.
4. One try can have multiple catch blocks.
5. After catch block is executed program continues because exception is handled.
Throw
We have seen exception handling mechanism. As we can see all the above exception were
generated by java. There are some situation when programmer wants to generate its own exception.
For example, while assigning negative value of roll no to student object or when the balance in the
bank account is less than the person withdrawing the amount from the bank account.
In scenarios where programmer wants to throw its own exception throw is used. Throw is a
statement which is followed by new keyword and Exception class. For eg.
Below mentioned is complete student class which does not allow object with negative value of the
rollno to be created.
class Student {
Student(int rollno) {
if(rollno <= 0) {
throw new IllegalArgumentException (“Roll No cannot be Zero or Negative”);
}
this.rollno = rollno;
} // end of constructor
} // end of class
class StudentDemo {
}
}
Exception hierarchy
Exception is a java class defined in java.lang package. All java programs has access of the lang
package its classes. We have seen classes ArithmeticException and NumberFormatException are
sub-classes of RuntimeException class. RuntimeException class is sub-class of Exception class. All
classes in java are sub-classes of Exception class or RuntimeException class. Below mentioned image
explains the exception hierarchy.
Throwable
Error Exception
RunTimeException
ArithmeticException IOException
NumberFormatException FileNotFoundException
ArrayIndexOutofBoundException SqlException
… …
Throws
As we have seen Exception hierarchy, now let’s understand Throws Statement. Throws is part of
method signature. Below mentioned example, method throws Exception. This method has to be
called from the try and catch block only.
class Demo {
class Test {
}
}
As we have seen that Exception and its sub-classes are ‘Checked Exception Type’ we MUST call the
method from try and catch block. Let’s understand from another example. Java File class is having
method createNewFile method which throws IOException.
Below mentioned program calls createNewFile from the File class. It must be called from try – catch
block.
import java.io.*;
class Test {
public static void main(String[] args) {
File f = new File(“d:/123.txt”);
try {
if( ! f.exists()) { // to check whether file exists or not.
boolean result = f.createNewFile(); // MUST be called from try-catch
System.out.println ( “File Creation Result “ : + result);
}
} catch ( Exception e ) {
e.printStackTrace();
}
} } // close of method and class
Below mentioned table shows difference between throw and throws clause.
Throw Throws
throw is a statement throws is part of method signature
throw is used when we can to throw our Throws is used when we do not want to handle
own exception based on some condition exception in a method but method calling should
handle exception.
throw statement is normally used to check We can declare more than one exception in
the parameter values and based on the throws. For e.g. throws IOException,
condition new exception type object FileNotFoundException
created is thrown.
Finally block
Finally is a block which is executed in all conditions. Whether exception is handled nor handled,
exception is thrown not thrown, finally is executed. That is why finally is block where we place
operations like file closing, connection closing etc. By placing these statements in the finally block we
ensure that our resources will always be closed.
try {
…
}
catch( … ) {
…
}
finally {
…
}
Java classes are created in packages. While creating real-life application it is necessary to place the
classes in the right package. If we will take example of java below mentioned is packages that are
available in java.
java
By default every java source file has all classes of lang package available. But if we want to us any
class other than lang package we have to place import statement. E.g. import java.io.*; We can also
import specific class for e.g. import import java.io.File;
Step 1 : create com directory at any location. Create test1 and test2 in com directory. Below
mentioned is our directory structure.
com
test1 test2
package com.test1;
Step 3 : create StudentDemo class in test2 package and create object of the Student class from test1
package.
package com.test2;
import com.test1.Student;
class StudentDemo {
public static void main(String[] args) {
Student s = new Student();
In any java class first statement is package and zero or more import statement. It is good practice to
have public class defined in each file.
Private is accessible in the same class, public is accessible anywhere. Protected is accessible in the
same package and also in the subclasses of another package. Default is accessible in the same
package.
Chapter 7 : IO Package
IO package many classes which are useful for File reading and writing purpose. We will start with the
File class. File class is defined in java.io package and File class is has many methods mentioned in
below mentioned program.
package com.test;
import java.io.*;
Streams Understanding
Java IO provides two types of streams. Byte streams and character streams. As shown in the image
below InputStream classes are used for reading byte contents, while output stream classes are used
to write byte contents. Reader and writer classes are means for characters reading and writing.
FileInputStream and FileOutputStream classes provides byte oriented reading and writing. Below
mentioned example shows file reading using FileInputStream.
import java.io.*;
class FileReadUsingInputStream {
Above way of getting the entire content at a single go is good if the file size is small. Possibly less
than 65k characters. If the file size is large we can write below mentioned way. We will reading the
file one byte at a time. If the eof (end of the file) comes then our character will be -1.
import java.io.*;
class FileReadUsingInputStream {
}
}
Same way we can use FileOutputStream to write content to the file. We will have our contents
stored in the string which we will convert into the byte array and write it to the file. Below
mentioned program explains the same.
import java.io.*;
class FileWriteUsingOutputStream {
}
} // end of class.
We can check the contents of the file using type command on the command line.
Reader
We can use FileReader to read the contents of the file. The way FileInputStream is having read
method which returns us int, FileReader is also having read method which returns the int value.
There will not be much difference in piece of code when use reader object to read the file.
import java.io.*;
class FileReadUsingReader {
} catch(Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
Writer
Java IO package provides us FileWriter class which is having write method which can take String
object directly. We have seen in case with FileOutputStream we have to convert the String into the
byte array because write method accepts only byte array. We should use reader / writer object
because they are more efficient when we are dealing with characters.
import java.io.*;
class FileWriteUsingWriter {
}
}
System class is defined java.lang package which provides us ‘in’ object which represent InputStream.
Below mentioned is a small program which prints the contents which we read from the console.
import java.io.*;
class ReadConsole{
public static void main(String[] args) throws IOException{
System.out.println( System.in.read( ) );
}
}
As we know that InputStream represents byte stream it displays the byte. To read more than one
character or to read the complete line we can use BufferedReader Class. BufferedReader is Reader
Type and it represents character stream. We will require InputStreamReader which provides bridge
between byte stream and character stream. In our case we require conversion from InputStream to
Reader Object. For example,
import java.io.*;
class ReadLine{
public static void main(String[] args) throws IOException{
String CurLine = ""; // Line read from standard in
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
}
}
RandomAccessFile
RandomAccessFile support reading as well as writing of the file. It behaves like a large array of byte
stored in file system. There is concept called as ‘File Pointer’ which allows programmer to place a
cursor at any point in the file. Thus reading and writing is relative to the file pointer which is placed.
RandomAccessFile provides methods like seek which sets the file pointer to the specific
location(byte) . It also provide methods like getFilePointer method which returns the current
position of the file pointer.
Below mentioned is a simple code where we are creating object of the RandomAccessFile. We are
providing file name test123.txt and opening the RandomAccessFile object in “rw” – called as read-
write mode. Current pointer of the random access file is pointing to 0 position.
import java.io.*;
}
}
RandomAccessFile is not subclass of the InputStream. Now, let’s write our content between two
lines. As we know the content of the first line is “hello file.”. We will get the length of the line and
use seek method to set the position of the file.
import java.io.*;
As we can see from the screen that the line is inserted at the end of the file. This can not be achieved
using BufferedWriter or OutputStream objects. BufferedWriter or OutputStream objects removes
the previous content if the file exists. BufferedWriter does have append method but it always
append at the end of the file. While with RandomAccessFile we can set the file pointer at any
location.
Object Streams
Object streams are representation of java object into stream of bytes . Java provides classes like
ObjectInputStream and ObjectOutputStream to deal with reading and writing objects to the file
system. This process is also termed as “Serialization” in java.
We can use ObjectOutputStream to write a object in the file and ObjectInputStream to read the
object from file. Since we are using file we will use FileInputStream and FileOutputStream objects.
import java.io.*;
Student(int rollno) {
this.rollno = rollno;
}
int getRollNo() {
return rollno;
}
It is important to note that we need to mark the class as Serializable to make it capable of reading
/writing by ObjectOutputStream. If any class is not marked as serializable it will throw exception
Exercises:
1. Write a java program which will count no. of “Hello” from the file. The
count value will be printed on the console.
2. Writer a java program which will convert file to all upper case characters.
3. Writer a java program which will use InputStream objects to read the file
having extensions .gif and Reader object to read the file having .txt
extension.
Nearly every operating system supports processes. Processes are parallel, independent programs
which are isolated by each other to some degree. Processes are managed and executed by
Operating System.
Threads are referred to as ‘Lightweigh Processes’. Java was one of the first programming languages
which included thread in the programming language itself. Java provide simple mechanism by which
threads can be created and managed.
Every java program has atleast one thread which called ‘Main Thread’. JVM creates main thread and
calls main() method. We will take some simple example first to understand the main thread which
executed thread method. Below mentioned java program displays information about main thread.
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("Current Thread Name is : " + name);
int priority = t.getPriority();
System.out.println("Priority of Thread is : " + priority);
boolean isAlive = t.isAlive();
System.out.println("Is Alive : " + isAlive);
}
We are creating object of the current thread by calling static method currentThread on the
Thread class.
Now, Let’s write down a program which will print the numbers 1 to 10 using sleep method of thread
class. Note that sleep is a static method defined in the Thread class which stops current thread
execution depending the no. of millisecond passed as parameter to sleep method.
for(int x=0;x<10;x++){
System.out.println(x);
try {
Thread.sleep(1000); // stops thread for 1 second.
} catch(Exception e) {
e.printStackTrace();
}
} // end of for loop
}
}
After every print on console, current thread (main thread) sleeps for 1 second. Every number printed
above on the screen will be printed after 1 second.
Thread Creation
We will understand program by which extends Thread way thread can be created. We will create
two thread from the main method and print 1 to 10 using for loop.
Below mentioned are steps to be followed whenever we want to create thread using extends Thread
mechanism.
super(threadName);
}
public void run() {
….
}
}
We are creating constructor of the MyThread which set the name of the thread by calling super
constructor with threadName.
Step 3: Creating object of the MyThread class and call start method on it.
It is important to understand that we always call start method. Run method is called by JVM after
start is called. We can not call start again if the thread is already running.
for(int x=0;x<10;x++){
System.out.println(Thread.currentThread().getName() + " : " + x);
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
We can see from above image that two threads are executed in parallel, each printing its own value
of the x from the stack. This also means that threads maintain their own stack.
Below mentioned are steps to be followed whenever we want to create thread using implements
Runnable mechanism.
Step 3: Creating object of the MyThread class. Creating object of the Thread class and passing
reference of MyThread class to the constructor. Call start method on the Thread class object.
Here it differs from the previous approach. We pass the reference of the Runnable type to the
thread class constructor. And we call start method on the object of the thread class. JVM in turn calls
run method from the MyThread object.
for(int x=0;x<10;x++){
System.out.println(Thread.currentThread().getName() + " : " + x);
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Note that implements Runnable is preferred approach because our class MyMath can still extend
another class.
Synchronization
In above example we have created two threads using implements Runnable approach. We created
only one object of MyThread class. Our both thread objects t1 an t2 were created on the MyThread
class object. If we have some instance variable defined in the MyThread class that variable copy will
be shared by both the thread. This type of variable are called non-thread-safe variable. Let’s take an
example and understand the real-life problem.
Ideally, for this program counter value would have been incremented by 20000. But since Java
thread is incrementing the counter variable, it might be possible that two threads reads the same
value and increment it. So instead of counter being incremented two times it will be incremented
only once. Below mentioned image tells the same story.
Java provides synchronized keyword which helps us in resolving the issue. We can put the counter++
statement in the synchronized block. Synchronized block ensure that no two thread enters in the
synchronized block. After one thread enters in the block a lock is captured and released only when
the thread exist. Then only another thread can enter in the loop.
Wait and notify provides intercommunication between threads. To understand the need for the
intercommunication we will take some specific example and try to understand. For example we are
creating one thread which will wait till notification comes. Notification interval will be depending on
the value we pass using command line argument.
}
}
Producer(String name){
super(name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Let’s understand below mentioned program. We are creating a Producer class which extends Thread
class. We also provide parameterized constructor so that we can provide the thread name –
“Producer”
We are overriding the run method from Thread class. Inside run method we immediately call wait
method. Wait method interrupts the Producer thread till we call notify. We declare the run method
as synchronized because wait and notify method must be called from the synchronized block /
method.
We create the object of the producer class from the main method and calls start method. This
creates a child thread and calls run method. Main thread continues its execution and wait for 10
seconds. After 10 seconds, it calls notify method on the Producer thread. We have placed the
synchronized block on the Producer thread object.
Note: Wait and Notify must be called from the synchronized block or method.
Now, let’s understand notifyall () method. We will be using implements Runnable approach and try
to create more than one thread on the Producer object. We will call notifyall method which will
release all threads from interrupted condition.
} catch (Exception e) {
e.printStackTrace();
}
}
}
When we run the program below mentioned is displayed whereby two threads (t1 & t2) are waiting
for the notification to be received.
As we call notifyAll () method after 5 minutes, both the threads receive notification and below
mention is displayed.
Now let’s write one program in which we Create one producer and one
Consumer. Both starts simultenously. First Producer produce 10 units at every
1 second. Till the time all units are not consumed consumer waits. Producer
notify the consumer after producing 10 units, Consumer notifies producer
after it consumes all units and till the time Consumer consumes producer
waits.
class Producer implements Runnable {
private Consumer c;
private Producer p;
@Override
public void run() {
try {
while (true) {
System.out.println(Thread.currentThread().getName() + " : Waiting for Producer
Notify ...");
synchronized(this){
this.wait();
}
System.out.println(Thread.currentThread().getName() + " : Notificaiton Received by
Producer");
for (int x = 10; x >= 1; x--) {
System.out.println("Consuming Unit No. " + x);
Thread.sleep(1000);
}
synchronized(p){
p.notify();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ProducerConsumerDemo {
}
}
Each Thread passes through different stages of its life-cycle. Below mentioned are some of the states
mentioned
Ready-to-run: This stage is also called as runnable state. After we create a thread and call start
method, thread will have state runnable state.
Running: Once thread is in ready-to-run state (runnable state), thread-scheduler will allocates CPU
cycles to the threads. When threads is given CPU cycles, we can see the output of the thread on the
screen. This means that thread is running. Much time thread is switched between ready-to-run to
running state, this is so that CPU cycles can be allocated to other same priority thread.
Blocked: we can block the thread by calling sleep or wait method. When we block the thread using
sleep method, it is blocked for specific timeframe. When we block the thread using wait method it is
blocked till notify is received.
Dead: when run method exists or we call stop method on the thread, its life-cycle ends. This is the
last stage of the thread life-cycle.
Yield is static method from Thread class. It notifies the OS that current is willing to give up the CPU
for a while. The general idea is that thread scheduler will select another thread to run instead of
current one. Note that yield behavior differs from OS to OS.
Sleep is waiting for specific time interval. Yield is putting current thread in run state from running
state.
Array are primarily used to store objects and primitives. But below mentioned are limitations of the
Array.
To come out of these limitations java provided complete util package which provides various data
structures. Java util package is based on the defined interfaces and classes.
Collection is main interface available in the util package which is extended by three interfaces List,
set And Queue.
List
List maintains the order of the elements. The order in which elements are added in the same orders
elements are fetched. We will look at the List interface first. ArrayList is the default implementation
of the List interface. We can create list as shown below.
This list is capable to store any type of object. We are creating object of the ArrayList and reference
of the List. There are methods are add(Object obj) and list.add(int index, Object obj) will add the
object in the list. The initial capacity of the list will be 10 elements. Once ArrayList reaches to the size
ArrayList will increase its size automatically.
list.add(s1);
We can fetch elements from the list using for loop as mentioned below.
for ( int x=0 ; x<list.size() ; x++ ) {
Object obj = list.get ( x );
if ( obj instanceOf Student ) {
Student s = (Student) obj ;
}
}
As we have seen from the above example that list provides us get method which
returns the object from the index no. that is specified. Java provides us for-each look
which can be written as below.
We can also use iterator object to fetch the objects from the List as shown below.
Iterator iterator = list.iterator( );
while(iterator.hasNext()) {
Object obj = iterator.next( );
if(obj instanceOf Student(){
}
Iterator also provides remove( ) method to remove the object from the current
position from the list.
LinkedList
We can also use LinkedList instead of ArrayList. LinkedList has addFirst( Object
obj) and addLast(Object obj) methods which can place the elements at the top or
bottom of the list.
LinkedList is more efficient if the more no. of insertion and deletion are more
compare to no. of access. LinkedList is not efficient if the fetching element like
list.get ( 323) ;
LinkedList is also called as doubly list. Each element in the list has the reference to previous node as
well to next node. Because of this adding or removing element from any position is instantaneous.
Below mentioned image shows the difference between how elements in ArrayList vs LinkedList is
stored.
Set
Set does not allow duplication of the object. Before we understand duplication of the object we
need to understand the shallow comparison vs deep comparison.
Shallow comparison is does for two objects using == operator. If two or more references are pointing
to the same object == operator return true. For example below.
System.out.println(s1==s2) ; // will return false because both reference are pointing to different
objects.
Below mentioned code will return us true because both references are pointing to the same objects.
Student s2 = s1;
System.out.println(s1==s2) ; // will return true because both reference are pointing to different
objects.
Object class is the super class of all java classes. Object class has default equals method which checks
for the comparison based on the == operator. Below mentioned is equals method from Object class.
Now, Let’s say that for our example, if the student’s rollno is same then both students are same
object. To achieve this we need to override equals method in Student class. Below mentioned code
overrides the equals method for the Student class.
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (this.id != other.id) {
return false;
}
if (this.rollno != other.rollno) {
return false;
}
return true;
}
We also need to override the hashCode method. hashCode() method returns the prime number
using the rollno.
@Override
int hash = 5;
return hash;
Note that overriding equals and hashcode is the primary thing to be available in the class for which
we are using Set.
Below mentioned example, we are adding three student’s object. Last Student object is having the
same rollno. When we display the size of the object it returns two.
import java.util.*;
class Student {
Student(int rollno) {
this.rollno = rollno;
}
public int getRollno() {
return rollno;
}
public Student() {
}
}
final Student other = (Student) obj;
if (this.rollno != other.rollno) {
return false;
}
return true;
}
class SetDemo {
}
}
Map
Map is an interface. It maintains key-value pair. Each object stored in the map is given some key.
Map is very useful when we want to search the object based on the some key. For e.g. we want to
search an student based on the rollno of the student.
Map has put function which adds the object against key into the map.
map.put(10,s1);
Here we are adding object s1 in the map against the key 10.
We can retrieve the object using the key as shown below using get function.
Here, we do not need to iterate through the all the objects available in the map. So search operation
based on the key will be very fast in the map. Map is primarily used for fast search operation based
on the key-value pair.
Below mentioned is an example in which we are storing the student object the key which is rollno.
import java.util.*;
class Student {
this.rollno = rollno;
this.name = name;
}
public int getRollno() {
return rollno;
}
public Student() {
}
}
class MapDemo {
// now we want to search the name of the student whose rollno is 199.
Student s = (Student) map.get(199);
System.out.println("The name of the student is : " + s.getName());
}
}
As we can see that we are getting deprecated warning when we compiler our program.
This is because java 2 onwards it was recommended that we should use generics whenever we are
using the util (List, Set and Map) Below mentioned is simple change we will placing when we want to
use generics.
This will ensure that you are going to add only students objects to the list, set and map. This will also
reduce our casting problem. Below mentioned is the simple code to iterate thru the List.
for(Student s : list) {
If you remember, previously we used to write down for(Object obj : list). And then we were casting
the object based on the instanceOf operator. Here we do not require that.
With generics we will have automatically add method allowing us to add student only.
As we have seen that when two or more threads access the object at the same time, we can have
synchronization issue. For example, we have one thread which is iterating over the list and second
thread removing the object from the thread or adding the object to the thread. This will generate
exception called as ConcurrentModificationException. Below mentioned example show us that.
We will have a class that adds one element to thelist after every one second. We are doing this using
while loop which keeps on running.
We are going to have another class which iterates over the list. Once iteration is over it waits for 10
seconds before second iteration starts.
import java.util.List;
class ConcurrentIterateThread implements Runnable {
} // class ends
import java.util.ArrayList;
import java.util.List;
} // main ends
} // class ends
This exception is occurring because when one thread is iterating over the list another thread can not
add or remove objects. This is because List is not a thread-safe object.
We can use vector in this case. Vector all methods are synchronized. So when one thread is iterating
over the vector another thread will be blocked and it will enter the method once after the first
thread exist.
It is also possible to place synchronized block in the run method while adding and iterating over the
list. This will also ensure that at a time either we are iterating or we are adding the element into the
list.
The way List is not a thread-safe object, HashMap is also not thread-safe. We should use HashTable
if we have concurrency requirement. HashTable all methods are synchronized.
HashMap HashTable
HashMap is not Thread-Safe. There will be HashTable is Thread-Safe. All methods of the
Concurrent modification exception if two HashTable are synchronized.
or more threads are iterating as well as
adding or removing elements from the
map.
HashMap allows null key or value HashTable does not allow null key or value
Practical Exercise:
import java.util.Set;
import java.util.TreeSet;
set.add(new Student(1,"aaa","[email protected]"));
set.add(new Student(2,"bbb","[email protected]"));
for(Student s : set){
int rollno;
String name;
String email;
this.rollno = rollno;
this.name = name;
this.email = email;
@Override
return this.name.compareTo(o.name);
@Override
if (obj == null) {
return false;
if (getClass() != obj.getClass()) {
return false;
return false;
return true;
@Override
int hash = 7;
return hash;
As we have seen that we can add any type of objects in the Collection (List / Set / Map). Due to
which there are chances of ClassCastException. We can use generics which will ensure that other
type of objects are not added to the Collection. For example,
Generics resolve above mentioned problem by delcaring that List will be container for only student
type objects.
List<Student> list = new ArrayList<Student>(); Now we can ONLY add student type object to the list.
Another advantage of having generics is when we are iterating over we can get Student object
directly and there is no need to cast.
while(iterator.hasNext()) {
Student s = iterator.next();
Key Points
1. List, Map and Set are interfaces defined in the java.util package
4. Set is used for duplication check. We need to override equals and hashcode method
5. Map is key-value pair. Each object is stored in Map against the key
8. LinkedList is useful only if inserting elements in the middle. For all other situation ArrayList is
better.
Appendix: Differences
3. overloading vs overriding
5. exception vs error
8. implements vs extends
9. Array vs ArrayList
Arrays are of fixed length. For example, int[] iarray = new int[10];
Arrays can be of Objects also. Person[] parray = new Person[10];
Arrays major limitation is it’s length is always fixed, which can not
be changed dynamically
ArrayList is an implementation class of List interface defined in
java.util package
ArrayList can grow dynamically as we add the object to it. There is
no size limitation of the array
Arrays can throw ArrayIndexOutofBoundsException if the we add/
fetch / delete element from the array, crossing the size of the
array
ArrayList object can be created using List list = new ArrayList();
List and Map are interface defined in the java.util package. These
interfaces are part of collection framework
List maintains order and object are retrieved in the FIFO(first in first
out) manner.
List has add and remove methods to add and remove the object from
the List
Map maintains key-value pair, each object is added using key
Map has put and remove method to add and remove methods
Map has get(Object key) method which retrieves the object stored
against the key.
ArrayList is implementation class of List while HashMap is
implementation class of Map interface.
List and Set are interfaces defined in the java.util package as a part of
Collection framework
List is ordered collection while set maintains Uniqueness
Object’s must override equals and hashcode method based on which
set will consider the duplicate objects
ArrayList is implementation of List interface and HashSet is
implementation of Set interface
Practical Exercise
1. Create a java pgoram to generate random number between 0 to 150.
System.out.println(randomInt);
// printing the random number on the screen.
2. Create a java program which will check whether random number is <50,
>50 or equal to 50.
int x = 23;
if(x<=50){
System.out.println("Value is less than or equal to 50");
} else if(x<=100){
System.out.println("Value is between 50 to 100.");
} else {
System.out.println("Value is greater than 100");
}
} // end of main method
3. Create a java program which will declare an array of integer type of size
50. Assign some random number (of between 1 to 50) to each of the
element. Generate a maximum, minimum number from the array
elements and print the values.
int max = 0;
// defining max value to be minimum of the range (range is 0 to 50)
int min = 50;
// defining min value to be maximum of the range (range is 0 to 50)
for(int x=0;x<50;x++){
myarray[x] = (int)(Math.random()*50);
if(myarray[x]>max){
max = myarray[x];
if(myarray[x]<min) {
min = myarray[x];
// printing array
System.out.println(m);
4. write a java program which will create a Vehicle class having two
instance variables color(String type) and mfgYear(integer type). Create
two objects of the Vehicle class named as v1 and v2. assing values of
color as red and yellow to v1 and v2. assign mfg year as 2010 and 2011
to v1 and v2.
class Vehicle {
variables.
class Test {
v1.mfgyear = 2010;
v2.mfgyear = 2011;
v2.color = "red";
v2.color = "white";
v1.printValues();
v2.printValues();
5. write a java pogram which will create above program and assign values
using method setValues which will accept two arguments. m as integer
type and c as color. Assign values from local varibles of the method to
instance variable. Print the values of the variable using printVehicle()
method.
class Vehicle {
void printValues() {
// method which is printing values of instance variables.
this.mfgyear = mfgyear;
// this is java keyword which will refer to instance variable of current obj
this.color = color;
}
}
class Test {
public static void main(String args[]){
Vehicle v1 = new Vehicle();
// java object creation process. Each vehicle will be referred using v1
Vehicle v2 = new Vehicle();
v1.setValues(2010,"red");
v2.setValues(2011,"yellow");
v1.printValues();
v2.printValues();
}
}
class Vehicle {
mfgyear = 1999;
color = "white";
}
this.color = color;
class Test {
v1.printValues();
v2.printValues();
6. Create a Java program which will display notepad having New, Save,
Open & Exit menu.
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
*
* @author Paresb
*/
public class JavaNotepad {
public static void main(String[] args) {
final Frame frame = new Frame("Java Notepad");
// frame will have border layout.
// textarea size will be size of the frame (center component)
// text area is final so that actionperformed can access the same.
final TextArea ta = new TextArea();
frame.add(ta);
// creating menubar,menu and menu items
MenuBar mb = new MenuBar();
Menu menuFile = new Menu("File");
MenuItem miNew = new MenuItem("New");
MenuItem miOpen = new MenuItem("Open");
MenuItem miSave = new MenuItem("Save");
MenuItem miExit = new MenuItem("Exit");
// adding menu items to menu
menuFile.add(miNew);
menuFile.add(miOpen);
menuFile.add(miSave);
menuFile.add(miExit);
// adding menu to menu bar
mb.add(menuFile);
// setting menu bar in the frame
frame.setMenuBar(mb);
//adding actionlistener event and handling of event
miNew.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ta.setText("");
}
});
// opening file dialog and io operatons for reading file
miOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
FileDialog dialog = new FileDialog(frame,"Select the file to Open");
dialog.setVisible(true);
String fileName = dialog.getFile();
String dirName = dialog.getDirectory();
File file = new File(dirName,fileName);
FileInputStream fis = null;
try {
// removing the previous contents
ta.setText("");
// file reading using binary stream
// we can use FileReader also
fis = new FileInputStream(file);
byte[] contents = new byte[(int)file.length()];
fis.read(contents);
// converting the byte array into the string
// adding text to textarea
ta.setText(new String(contents));
} catch(Exception e){
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
@Override
public void actionPerformed(ActionEvent event) {
// creating file dialog with save - cancel button
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// frame location, size and visibility
frame.setLocation(100,100);
frame.setSize(400,400);
frame.setVisible(true);
}
}
7. Create a Java Program which will change the color of the rectangle after
every 5 seconds in an Applet.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/**
*
* @author Paresb
*/
// infinite loop
while (true) {
try {
// wait for 5 seconds before we change the color
Thread.sleep(5000);
// repaint will call paint method
repaint();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
test.html file
Note: applet class file and html file must be in the package.
8. Create a java program which will generate a frame having three text
field, one drop down and an answer button. Dropdown menu will have
+, - , / and * signs. Based on the selection of the sign from the dropdown
and numbers entered in the two textfield, when answer button is
pressed third text field should display the answer.
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
*
Core Java By Paresh Bhavsar Page 113
Core Java Solution Paresh Bhavsar
* @author Paresb
*/
public class CalculatorFrame {
public static void main(String[] args) {
Frame frame = new Frame("Calculator Frame");
// panel is a container like frame
// panel has default layout as flow layout
Panel p = new Panel();
final TextField tfFirst = new TextField(4);
final TextField tfSecond = new TextField(4);
final TextField tfAnswer = new TextField(4);
// creating a dropdown
final Choice list = new Choice();
list.add("+");
list.add("-");
list.add("*");
list.add("/");
list.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
String strItem = (String) e.getItem();
System.out.println("Selected : " + strItem);
// converting string into number
int firstNumber;
int secondNumber;
try {
firstNumber = Integer.parseInt(tfFirst.getText());
secondNumber = Integer.parseInt(tfSecond.getText());
} catch (Exception ex) {
ex.printStackTrace();
return;
}
if (strItem.equalsIgnoreCase("+")) {
int answer = firstNumber + secondNumber;
// converting integer into string
tfAnswer.setText(String.valueOf(answer));
} else if (strItem.equalsIgnoreCase("-")) {
int answer = firstNumber - secondNumber;
// converting integer into string
tfAnswer.setText(String.valueOf(answer));
} else if (strItem.equalsIgnoreCase("*")) {
int answer = firstNumber * secondNumber;
// converting integer into string
tfAnswer.setText(String.valueOf(answer));
} else {
int answer = firstNumber / secondNumber;
// converting integer into string
tfAnswer.setText(String.valueOf(answer));
}
}
});
frame.add(p);
frame.setSize(500, 200);
frame.setLocation(100, 100);
frame.setVisible(true);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
10.Write a java frame based application in which user will enter the
directory name in the text field. List all files of the directory in a text area
on clicking the list button.
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Button;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
*
* @author Paresb
*/
public class DirectoryListFrameDemo {
public static void main(String[] args) {
Frame frame = new Frame("Directory List Demo");
final TextField tf = new TextField(15);
Button b = new Button("List");
final TextArea ta = new TextArea(10,20);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
File file = new File(text);
if(!file.exists() && !file.isDirectory()){
ta.setText("Directory does not exit. or not a valid directory");
return;
}else {
ta.setText("");
String[] files = file.list();
for(String str : files){
ta.append(str + "\n");
}
}
}
});
Panel p = new Panel();
p.add(tf);
p.add(b);
p.add(ta);
frame.add(p);
frame.setLocation(100,100);
frame.setSize(200,300);
frame.setVisible(true);
}
}
11.Write an applet which display the x and y will position of the mouse in
the String. (Using MouseMotionListener)
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
*
* @author Paresb
*/
public class AppletDemo extends Applet implements
MouseMotionListener {
private int x;
private int y;
boolean released = false;
@Override
public void start() {
this.addMouseMotionListener(this);
}
@Override
public void paint(Graphics g){
if(!released)
g.drawString("Mouse Position : X : " + x + " Y : " + y, 100,100);
}
@Override
public void mouseDragged(MouseEvent e) {
x = e.getPoint().x;
y = e.getPoint().y;
released = false;
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
} }
12.Create a Java frame which will take all required inputs for Student
creation. (Name, address, date of birth, sex (radio button (male &
female), education (dropdown using under-graduate, graduate, post-
graduate,doctorate). On submit click display all values entered by user or
selected by user in a text area.
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StudentFormFrame {
public static void main(String[] args) {
if (cbMale.getState()) {
taForm.append("Sex : Male" + "\n");
} else {
taForm.append("Sex : FeMale" + "\n");
}
taForm.append("Education : " +education.getSelectedItem() +
"\n");
}
});
frame.add(lname);
frame.add(tfName);
frame.add(laddress);
frame.add(ta);
frame.add(lsex);
frame.add(cbMale);
frame.add(cbFemale);
frame.add(ledu);
frame.add(education);
frame.add(button);
frame.add(taForm);
frame.setLayout(new FlowLayout());
frame.setSize(210, 400);
frame.setLocation(100, 100);
frame.setVisible(true);
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
/**
*
* @author Paresb
*/
class Employee {
int employee_id;
String employee_name;
Employee (int employee_id, String employee_name) {
this.employee_id = employee_id;
this.employee_name = employee_name;
}
}
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Paresb
*/
public class FrameDemo {
@Override
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
@Override
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("Mouse Exited");
}
});
frame.addMouseMotionListener(new MouseMotionListener()
{
@Override
public void mouseDragged(MouseEvent e) {
l.setText("Mouse Dragged X Position " + e.getPoint().x + "
Y Point " + e.getPoint().y );
}
@Override
public void mouseMoved(MouseEvent e) {
l.setText("Mouse Dragged X Position " + e.getPoint().x + "
Y Point " + e.getPoint().y );
}
});
// Adding exit capabilities
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setSize(500,100);
frame.setLocation(300, 300);
frame.setVisible(true);
}
}
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.lang.Integer;
import java.util.Stack;
import java.awt.Button;
import java.awt.Panel;
import java.awt.event.ActionListener;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Paresb
*/
public class StackDemo {
@Override
public void actionPerformed(ActionEvent e) {
stack.push(Integer.parseInt(tf.getText()));
tf.setText("");
msgLabel.setText("Element Pushed");
}
});
popButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(stack.isEmpty()){
msgLabel.setText("Stack is Empty");
tf.setText("");
return;
}
tf.setText(String.valueOf(stack.pop()));
}
});
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Paresb
*/
public class ThreadMatrixReadDemo {
int[][] matrix ;
int row;
@Override
public void run() {
int[] rowdata = matrix[row];
int sum=0;
for(int x=0;x<rowdata.length;x++){
// System.out.println(Thread.currentThread().getName() + " Data
:" + rowdata[x]);
sum += rowdata[x];
}
System.out.println("Sum of Row " + row + " is " + sum);
}
- A method named display() will display description for the fan. If the fan
is on,
the display() method displays speed, color and radius. If the fan is not
on, the method returns fan color and radius along with the message “fan
is off”.
Write a test program that creates two Fan objects. One with default
values and the other with medium speed, radius 6, color brown, and
turned on status true. Display the descriptions for two created Fan
objects.
class Fan {
final int SLOW = 1;
static final int MEDIUM = 2;
static final int FAST = 3;
private int speed;
private boolean f_;
private double radius;
private String color;
public Fan() {
speed = SLOW;
f_ = false;
radius = 4;
color = "blue";
}
public Fan(int speed, boolean f_, double radius, String color) {
this.speed = speed;
this.f_ = f_;
this.radius = radius;
this.color = color;
}
public void display() {
System.out.println("_____Displaying Fan Info_____");
System.out.println("Radius : " + radius);
System.out.println("Color : " + color);
if (f_) {
System.out.println("Speed : " + speed);
} else {
System.out.println("Fan is Off.");
}
}
}
public class FanDemo {
public static void main(String[] args) {
Fan fan1 = new Fan();
Fan fan2 = new Fan(Fan.MEDIUM, true, 6, "brown");
fan1.display();
fan2.display();
}
}
class Rectangle {
private double x,y,width,height;
public Rectangle() {
width = height =1;
x=y=0;
}
public Rectangle(double x, double y,double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return (2*width) + (2*height);
}
public boolean contains(double x, double y){
if((x>=(this.x-(width/2))) && (x<=(this.x+(width/2)))) {
if((y>=this.y-(height/2)) && (y<=this.y+(height/2))){
return true;
} else {
return false;
}
} else {
return false;
}
}
}
public class RectangleDemo {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
double area = r1.getArea();
double perimeter = r1.getPerimeter();
boolean pointInsideResult = r1.contains(10, 10);
System.out.println("_______ Rectangle Details _______");
System.out.println("Area : "+ area);
System.out.println("Perimeter : "+ perimeter);
System.out.println("Point Inside Result : " + pointInsideResult);
Rectangle r2 = new Rectangle(5, 5, 20, 20);
area = r2.getArea();
perimeter = r2.getPerimeter();
16. The Transport interface declares a deliver() method. The abstract class
Animal is the superclass of the Tiger, Camel, Deer and Donkey classes. The
Transport interface is implemented by the Camel and Donkey classes. Write
a test program that initialize an array of four Animal objects. If the object
implements the Transport interface, the deliver() method is invoked.
interface Transport {
void deliver() ;
}
abstract class Animal {
// error in question… it must talk about which abstract method
}
class Tiger extends Animal{
}
class Camel extends Animal implements Transport {
public void transport() {
System.out.println(“Transporting Camel”);
}
public void deliver() {
System.out.println(“Camel !!! deliver);
}
}
class Test {
public static void main(String args[]) {
Animal[ ] a = new Animal[4];
a[0] = new Donkey();
a[1] = new Tiger();
a[2] = new Dear();
a[3] = new Camel();
a[0].deliver();
a[3].deliver();
}
}
17. Write a program that counts the no. of words in a text file. The file name
is passed as a command line argument. The program should check
whether the file exists or not. The words in the file are separated by
white space characters.
} else {
System.out.println("File Does not Exists.");
}
} catch(Exception e){
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}