Sunteți pe pagina 1din 138

Core Java Solution Paresh Bhavsar

Core JAVA
Paresh Bhavsar
(BE - DDIT, SCJP-Sun Inc., MBA)
www.j2eetrainer.com / bhavsar.er@gmail.com

Core Java By Paresh Bhavsar Page 1


Core Java Solution Paresh Bhavsar

Table of Contents

Chapter 1 : Basics of Java Programming Language ................................................................................. 3

Chapter 2 : Understanding Class and Object ........................................................................................ 12

Chapter 3 : OOP - Object Oriented Programming (Inheritance, Encapsulation and polymorphism) ... 21

Chapter 4 : Understanding Java Keywords & Inbuilt Java Classes ........................................................ 36

Chapter 5 : Exception Handling............................................................................................................. 45

Appendix : Differences

Core Java By Paresh Bhavsar Page 2


Core Java Solution Paresh Bhavsar

Chapter 1 : Basics of Java Programming Language


Chapter ObjectiveFundamentals

1. Understanding and comparing java compilation process and run time


process with other programming languages. Also explain java’s
Platform Independence feature.

2. Benefits of Java languages

Exercise

1. Understanding jdk kit directory structure

2. Running first java program from command line

3. Create a java program which will generate random number between


0 to 50

4. Create a java program which will print number between 100 to 200
using for loop, do while loop and while loop

5. Use if-else statement to check whether number is <50, >50 or equal


to 50

Core Java By Paresh Bhavsar Page 3


Core Java Solution Paresh Bhavsar

Chapter 1 : Basics of Java Programming Language


1. Understanding and comparing java compilation process and run time
process with other programming languages

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.

.c File C Compiler .exe file

Source Code Executable code

1.1 Compilation Process of C Language

.java File JAVA Compiler .class file

Source Code Byte code

1.2 Compilation Process of JAVA Language

Core Java By Paresh Bhavsar Page 4


Core Java Solution Paresh Bhavsar

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).

Core Java By Paresh Bhavsar Page 5


Core Java Solution Paresh Bhavsar

Chapter 1 : Basics of Java Programming Language


2. Benefits of Java Language
a. Java is Platform Independent

b. Java is Portable – Java code can be transferred from one machine to another machine

c. Java is distributed – Java code is capable to run on Multiple JVM env.

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.

Core Java By Paresh Bhavsar Page 6


Core Java Solution Paresh Bhavsar

Chapter 1 : Basics of Java Programming Language


Exercise

1. Installation process and setting path variable on computer to execute


javac command
Java is installed on c:/program files/ java directory

In java directory you can find two directories jdk or jre.

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

Core Java By Paresh Bhavsar Page 7


Core Java Solution Paresh Bhavsar

Command prompt should display below mentioned when we type javac now.

2. Running first java program from command line


Open Notepad and type below mentioned.

public class Test {

public static void main (String args[]) {

System.out.println (“Hello World”);

‘S’ is upper case (capital) for String and System word.

Save the file with Test.java

Open command prompt and type javac Test.java

If there is no compilation error, Test.class file will be created.

This Test.class is called as byte code and to run Test.class we require JVM as discussed
earlier.

Below mentioned image runs Java program - java Test

Core Java By Paresh Bhavsar Page 8


Core Java Solution Paresh Bhavsar

3. Write a Java program which will display the use of if … else


(conditional statements) and for (looping) using an example.

class Test {

public static void main(String[] args) {


System.out.println("Hello java");
int x = 10;
if(x==0)
System.out.println("x is zero");
else
System.out.println("x is not zero");

for(int y=0;y<10;y++){
System.out.println(y);
}
} // method ends

} // class ends

4. Create a java program which will generate random number between


0 to 50
public class Test {

public static void main(String args[]){

double random = Math.random(); // Math class is java defined class having random
// function which return double.

random = random * 50; // as random method is created between 0.0 to 1.0 by


// multiplying with 50 we genererated random number
//between 0.0 to 50.0

int randomInt = (int) random; // we are explicitly converting double number into int so
// our random number will be between 0 to 50 now.

System.out.println(randomInt); // printing the random number on the screen.

Core Java By Paresh Bhavsar Page 9


Core Java Solution Paresh Bhavsar

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 {

public static void main(String args[]){

for(int x=100;x<=200;x++){

System.out.println("Value of x is " + x);

} // end of for loop

} // end of main method

} // end of Test class

// program using while loop.

public class Test {

public static void main(String args[]){

int x = 100;
while(x<=200){

System.out.println("Value of x is " + x);

x++;

} // end of while loop

} // end of main method

} // end of Test class

// program using do while loop.

public class Test {

public static void main(String args[]){

int x = 100;
do {

System.out.println("Value of x is " + x);

x++;

} while(x<=200); // end of do-while loop

} // end of main method

} // end of Test class

Core Java By Paresh Bhavsar Page 10


Core Java Solution Paresh Bhavsar

6. Use if-else statement to check whether number is <50, >50 or equal


to 50
public class Test {

public static void main(String args[]){

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

} // end of Test class

Core Java By Paresh Bhavsar Page 11


Core Java Solution Paresh Bhavsar

Chapter 2 : Understanding Class and Object


Fundamentals

1. Concepts of Class and Object, Object Creation Process in Java. Explain


this keyword and methods creation in java.

2. What is constructor? Explain Constructor overloading along with


method overloading?

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.

2. Create a class Animal having instance variable nolegs (integer type)


and age (integer type). Create two objects of Animal class a1 and a2.
Assign values of instance variable using dot(.) Operator. Print the
values of the objects.

Core Java By Paresh Bhavsar Page 12


Core Java Solution Paresh Bhavsar

Chapter 2 : Understanding Class and Object

Fundamentals

1. Concepts of Class and Object, Object Creation Process in Java. Explain


this keyword and methods creation in java.

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.

Core Java By Paresh Bhavsar Page 13


Core Java Solution Paresh Bhavsar

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 {

public static void main(String[] args) {

Student s1 = new Student(); // s1 is called reference which is pointing to object


Student s2 = s1; // same object pointed by another reference s2

} // end of main method

} // end of class

Core Java By Paresh Bhavsar Page 14


Core Java Solution Paresh Bhavsar

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

Core Java By Paresh Bhavsar Page 15


Core Java Solution Paresh Bhavsar

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

2. What is constructor? Explain Constructor overloading along with


method overloading?

Core Java By Paresh Bhavsar Page 16


Core Java Solution Paresh Bhavsar

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,

Student (int rollno, String name) {


this.rollno = rollno;
this.name = name;

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’

Core Java By Paresh Bhavsar Page 17


Core Java Solution Paresh Bhavsar

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.

1. Using dot(.) operator


2. By setValues method
3. By constructor (default or parameterized)

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

Core Java By Paresh Bhavsar Page 18


Core Java Solution Paresh Bhavsar

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.

To summarize about constructor

1. Constructor are used to initialize object parameters

2. Constructor name is same as class name

3. Constructor cannot have return type.

4. Constructors are called only during the object creation time

5. Every java class has default constructor. If programmer does not create
a default constructor java creates default constructor.

6. If programmer creates parameterized constructor java does not create


default constructor

7. One Constructor can call another constructor using this. Calling must
be first statement only.

Core Java By Paresh Bhavsar Page 19


Core Java Solution Paresh Bhavsar

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;

void setValues(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
}
void printValues() {
System.out.println(“Width is “ + width);
System.out.println(“Height is “ + height);
System.out.println(“Depth is “ + 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();
}
}

Core Java By Paresh Bhavsar Page 20


Core Java Solution Paresh Bhavsar

Chapter 3 : OOP - Object Oriented Programming


(Inheritance, Encapsulation and polymorphism)
Fundamental

1. Explain what is inheritance what are the benefits of inheritance and how does java
supports inheritance with an example?

2. Explain encapsulation? Explain private keyword of java with an example.

3. Explain static polymorphism? Explain constructor overloading / method


overloading with example? Also explain what is static binding?

4. Explain abstract class and interface? What is the difference between abstract class
and interface? Explain with an example.

5. Explain dynamic polymorphism. Explain the method overriding? Give an example


to explain concept?

6. Explain Garbage Collection. Explain garbage collection process using various


example. Explain finalize() method from the Garbage Collection point of view.

7. Explain Multiple and multilevel inheritance with respect to class and interfaces?

Core Java By Paresh Bhavsar Page 21


Core Java Solution Paresh Bhavsar

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.

Core Java By Paresh Bhavsar Page 22


Core Java Solution Paresh Bhavsar

Let’s understand using an example.

class Student {
int id;
String name;
}

class EnggStudent extends Student {

class CommerceStudent extends Student {

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.

Core Java By Paresh Bhavsar Page 23


Core Java Solution Paresh Bhavsar

2. Explain encapsulation? Explain private keyword of java with an example.

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.

public String getName() { // return value of name attribute


return name;
}

public void setName(String name) { // set the value name attribute


this.name = name; // assigning value to instance variable
(this)
}

public int getRollno() { // return value of rollno attribute


return rollno;
}

public void setRollno(int rollno) { // set the value name attribute


this.rollno = rollno; // assigning value to instance variable
(this)
}
}

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 :

Core Java By Paresh Bhavsar Page 24


Core Java Solution Paresh Bhavsar

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)

// due to inheritance setRollno method is accessible


}
}

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.

public void setRollno(int rollno) { // set the value name attribute


if(rollno < 0){
System.out.println(“Can not Set rollno to Negative Value”);
Return;
}
this.rollno = rollno; // assigning value to instance variable (this)
}

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)

Core Java By Paresh Bhavsar Page 25


Core Java Solution Paresh Bhavsar

3. Explain static polymorphism? Explain constructor overloading / method overloading


with example? Also explain what is static binding?

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 void setValues(int rollno, String name) {


this.rollno = rollno;
this.name = name;
}

public void setValues(int rollno) { // method overloading (change in arguments)


this.rollno = rollno;

public Student() {
}

public Student(int rollno, String name) { // constructor overloading


this.rollno = rollno;
this.name = name;
}
}

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.

Core Java By Paresh Bhavsar Page 26


Core Java Solution Paresh Bhavsar

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).

Core Java By Paresh Bhavsar Page 27


Core Java Solution Paresh Bhavsar

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 class Student {

private int rollno;


private String name;

public Student(int rollno, String name) {


this.rollno = rollno;
this.name = name;
}

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.

class EnggStudent extends Student {

int getTotalMarks() {
return 100; // getTotalMarks implemented and return value is 100.
}
}

class CommerceStudent extends Student { //

int getTotalMarks() {
return 70; // getTotalMarks implemented and return value is 70.
}
}

Core Java By Paresh Bhavsar Page 28


Core Java Solution Paresh Bhavsar

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.

abstract class CommerceStudent extends Student { //

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 {

void getTotalMarks(); // no need to declare method as abstract.

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

class CommerceStudent implements Student {

… // implementation of the getTotalMarks method as explained earlier.

Here we are using implements keyword. Implements keyword allows classes to implement Student
interface.

Core Java By Paresh Bhavsar Page 29


Core Java Solution Paresh Bhavsar

5. Explain dynamic polymorphism? Explain the method overriding? Give an example to


explain concept? Also explain Garbage Collection ?

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;

public void printStudent() {


System.out.println(“I am student”);
}
}

class EnggStudent extends Student {

public void printStudent() { // overridden method


System.out.println(“I am Engineering student”);
}
}

class ScienceStudent extends Student {

public void printStudent() { // overridden method


System.out.println(“I am Science student”);
}
}

class StudentDemo {

public static void main(String args[]){

Student s1 = new Student();


s1.printStudent();
EnggStudent s2 = new EnggStudent();
s2.printStudent();
ScienceStudent s3 = new ScienceStudent();
S3.printStudent();

}
}

Core Java By Paresh Bhavsar Page 30


Core Java Solution Paresh Bhavsar

As we can see in mentioned example, printStudent method is overridden in sub-class. The


implementation of the method is different. Now, if we create the student class object and call the
printStudent method, we will have o/p printed on the console screen will be “I am Student”. We can
create object of the EnggStudent and call printStudent method, o/p will be “I am Engineering
Student”.

Ideally we should have created reference of the Student Class which is pointing to the object of
Student class, EnggStudent and ScienceStudent.

class StudentDemo {

public static void main(String args[]){

1 Student s1 = new Student();


2 s1.printStudent();
3 s1 = new EnggStudent(); // same reference (s1) pointing to EnggStudent now
4 s1.printStudent();
5 s1 = new ScienceStudent(); // same reference(s1) pointing to CommerceStudent now
6 s1.printStudent();

}
}

Student Object garbage Student


collected After line no 3
rollno
S1
name

CommerceStudent
EnggStudent
rollno
rollno

name
name

EnggStudent Object garbage


collected After line no 5

Core Java By Paresh Bhavsar Page 31


Core Java Solution Paresh Bhavsar

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.

Student s1 = new Student();


s1 = null;

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.

Student s1 = new Student();


s1 = new Student();

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.

Student s1 = new Student();


Student s2 = s1;
s1 = null;

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.

Core Java By Paresh Bhavsar Page 32


Core Java Solution Paresh Bhavsar

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.

protected void finalize () {

// finalization code here. E.g. flie closing, socket closing etc.

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.

Core Java By Paresh Bhavsar Page 33


Core Java Solution Paresh Bhavsar

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.

Multilevel and multiple inheritances is described using below image.

Vehicle Vehicle Car

Car

RacingCar

RacingCar

Muti Level Inheritance Multiple Inheritance

From above image it is clear that we need to write down below mentioned code to create MultLevel
Inheritance.

Mutilevel Inheritance Multiple Inheritance

class Vehicle { class Vehicle {


…. ….
} }
class Car extends Vehicle { class Car {
…. ….
} }
class RacingCar extends Car { class RacingCar extends Vehicle , Car {
… …
} }

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.

Core Java By Paresh Bhavsar Page 34


Core Java Solution Paresh Bhavsar

Now let’s understand from interface point of view.

Two interfaces can be implemented by class. So java supports multiple inheritance partially. For
example,

class ClassOne implements InterfaceOne, InterfaceTwo {

One interface can extend another interface, but again one interface can not extend two interfaces.

class InterfaceThree extends InterfaceOne {

class InterfaceThree extends InterfaceOne, InterfaceTwo { // not allowed.

One class can extend another class and at the time it can implement one or more interfaces too.

class ClassOne extends ClassTwo implements InterfaceOne, InterfaceTwo {

Core Java By Paresh Bhavsar Page 35


Core Java Solution Paresh Bhavsar

Chapter 4 : Understanding Java Keywords & Inbuilt Java Classes

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.

Core Java By Paresh Bhavsar Page 36


Core Java Solution Paresh Bhavsar

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.

Core Java By Paresh Bhavsar Page 37


Core Java Solution Paresh Bhavsar
Student

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
}
}

Core Java By Paresh Bhavsar Page 38


Core Java Solution Paresh Bhavsar

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 {

public static void main(String args[]){

double r = Math.random(); // no need to create instance of Math class


System.out.println("Random Number is " + r);

}
}

Core Java By Paresh Bhavsar Page 39


Core Java Solution Paresh Bhavsar

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)

2. We can not override final method.

3. For any variable if we declare final it becomes constant.

Let’s understand above using example.

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 MEStudent extends EnggStudent { // NOT - allowed

Now let’s understand final method and variable declared as final.

class Student {

private int rollno;


private String name;
final String schoolName = “www.j2eetrainer.com”; // schoolName can not be changed now
final static TOTAL_MARKS = 100; // final and static so TOTAL_MARKS memory will be
//associated with the class only instead of with object.
final static void displayTotalMarks() { // can not override method
System.out.println(“Total Marks for the Engg Student is “ + TOTAL_MARKS);
// can not access rollno and name in static method
}
}
class StudentDemo {

public static void main(String args[]){

Student s = new Student();


s.schoolName = "www.oracle.com"; // can not change value of schoolname

}
}

Core Java By Paresh Bhavsar Page 40


Core Java Solution Paresh Bhavsar

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.

Let’s understand with an example.

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();
}
}

Core Java By Paresh Bhavsar Page 41


Core Java Solution Paresh Bhavsar

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.

Sr. Java Package Name Remarks


No.

1. java.lang This package is default package which is inherited in all java


files. Classes of java.lang package and available without writing
import statement. Meaning that we do not need to write down
import java.lang.* in java file. This package contains classes like
String, Math, StringBuffer etc.

2. java.io This package include all Input/Output related classes required


for File reading and writing operations.

3. java.awt This package contains classes necessary for windows Frame


programming, normally used for creating desktop application
for e.g. button, textfield, textarea etc.

4. java.applet This package provides classes by which applet programming is


possible. Applet is java class that executes in the browser (e.g.
IE, Firefox etc.)

5. java.util This package provides data-structure implementation for e.g.


LinkedList, ArrayList, HashMap, HashTable etc.

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.

Core Java By Paresh Bhavsar Page 42


Core Java Solution Paresh Bhavsar

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.

Below mentioned are some of the methods from Math class.

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.

Core Java By Paresh Bhavsar Page 43


Core Java Solution Paresh Bhavsar

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.

Core Java By Paresh Bhavsar Page 44


Core Java Solution Paresh Bhavsar

Chapter 5: Exception Handling

Introduction to Exception Handling

Java provides comprehensive exception handling mechanism. Exception is unwanted occurrence of


an event. For example, division by zero, File not found while reading / writing file, SQL exception etc.
As a java programmer you should be aware of how to handle exception. Java programmer should
also be aware of different kinds of exception which can be thrown while writing down java code.

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.

Core Java By Paresh Bhavsar Page 45


Core Java Solution Paresh Bhavsar

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.

Core Java By Paresh Bhavsar Page 46


Core Java Solution Paresh Bhavsar

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.

throw new IllegalArgumentException (“Roll No cannot be Zero or Negative”);

Below mentioned is complete student class which does not allow object with negative value of the
rollno to be created.

class Student {

private int rollno;

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 {

public static void main(String[] args) {

Student s = new Student (-10);

}
}

Core Java By Paresh Bhavsar Page 47


Core Java Solution Paresh Bhavsar

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
… …

Some key points of the exception hierarchy explained above.

Throwable is super class of Exception class.


RuntimeException and its sub-class are called ‘Un-Checked’ exceptions. Those exception
are not required to be called from try-catch block.
Exception and its sub-classes are called ‘Checked’ Exception it must be called from try –
catch block
Error and its subclasses should NOT be handled. They are errors and not recoverable.

Core Java By Paresh Bhavsar Page 48


Core Java Solution Paresh Bhavsar

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 {

public void mymethod() throws Exception {

class Test {

public static void main ( String[] args) {

Demo d = new Demo();


d.mymethod(); // Compilation Error : Should be called from try and catch block.

}
}

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.

public void createNewFile () 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 ) {

Core Java By Paresh Bhavsar Page 49


Core Java Solution Paresh Bhavsar

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 {

}

Core Java By Paresh Bhavsar Page 50


Core Java Solution Paresh Bhavsar

Chapter 6 : Packages, import and Access Modifiers

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

lang io util awt sql net

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;

Let’s take one example and try to understand the same.

Step 1 : create com directory at any location. Create test1 and test2 in com directory. Below
mentioned is our directory structure.

com

test1 test2

Step 2: Now create Student class in test1 package.

package com.test1;

public class Student {

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();

Core Java By Paresh Bhavsar Page 51


Core Java Solution Paresh Bhavsar

System.out.println(“Student Object created”);


}}

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.

# Same Class Same Package Another Package Anywhere


Private Accessible Not Accessible Not accessible Not Accessible
outside class
Default Accessible Accessible Not accessible Not accessible
Protected Accessible Accessible Only in Sub-classes Not Accessible
Public Accessible Accessible Accessible Accessible

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.

Core Java By Paresh Bhavsar Page 52


Core Java Solution Paresh Bhavsar

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.*;

public class FileDemo {

public static void main(String[] args) {

File file = new File("d:/123.txt");


System.out.println(file.exists());

} // end of main method


}

Below mentioned are some of the methods of file class useful.

# Name of Method from File Description


Class
boolean createNewFile( ) Returns true if the file is created and false if file can not be
created
boolean mkDir( ) Returns true if the directory can be created.
boolean canRead( ) Returns true if file is having read permission
boolean canWrite( ) Returns true if the file is having write permission
boolean canExecute( ) Returns true if the can is executable
boolean length( ) Returns the length of the file in bytes
boolean isDirectory( ) File object can point to directory also. method will return true
boolean isFile( ) If File object is for file, return true
String[ ] list( ) If file object is pointing to directory, list method will return
String array of all directories / file from the directory where it is
pointing to.
boolean renameTo( ) This method will return Boolean value if renaming is successful.

Core Java By Paresh Bhavsar Page 53


Core Java Solution Paresh Bhavsar

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 {

public static void main(String[] args) {


FileInputStream fis = null;
try {
File f = new File ("d:/Student.java");
fis = new FileInputStream ( f );
byte[ ] content = new byte[ (int)f.length() ];
fis.read ( content );
String contentStr = new String ( content );
System.out.println("File Contents \n " + contentStr);
} catch( Exception e ) {
e.printStackTrace( );
} finally {
if( fis!=null ){
try {
fis.close( );
} catch(Exception e) {
e.printStackTrace( );
}
}
} // end of finally
} // end of main
} // end of class

Core Java By Paresh Bhavsar Page 54


Core Java Solution Paresh Bhavsar

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 {

public static void main(String[] args) {


FileInputStream fis = null;
try {
File f = new File("d:/Student.java");
fis = new FileInputStream(f);
int data = fis.read();
while(data != -1) {
System.out.print((char)data);
data = fis.read();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

}
}

Core Java By Paresh Bhavsar Page 55


Core Java Solution Paresh Bhavsar

File Writing Using FileOutputStream

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 {

public static void main(String[] args) {


FileOutputStream fos = null;
try {
File f = new File("d:/test123.txt");
fos = new FileOutputStream(f);
String fileContent = "hello file. \n We are using outputstream to write contents.";
fos.write( fileContent.getBytes( ) );
System.out.println("File Writing Completed Successfully.");
} catch(Exception e) {
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

}
} // end of class.

We can check the contents of the file using type command on the command line.

Core Java By Paresh Bhavsar Page 56


Core Java Solution Paresh Bhavsar

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 {

public static void main(String[] args) {


FileReader reader = null;
try {
File f = new File("d:/Student.java");
reader = new FileReader(f);
int data = reader.read();
while(data != -1) {
System.out.print(data);
data = reader.read();
}

} catch(Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

}
}

Core Java By Paresh Bhavsar Page 57


Core Java Solution Paresh Bhavsar

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 {

public static void main(String[] args) {


FileWriter writer = null;
try {
File f = new File("d:/test123.txt");
writer = new FileWriter(f);
String fileContent = "hello file. \n We are using WRITER to write contents.";
writer.write(fileContent);
System.out.println("File Writing Completed Successfully.");
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer!=null){
try {
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

}
}

Reading contents of the file.

Core Java By Paresh Bhavsar Page 58


Core Java Solution Paresh Bhavsar

Reading from Console

System class is defined java.lang package which provides us ‘in’ object which represent InputStream.

In System class it is written as public static final InputStream in = …

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

System.out.println("Enter a line of text (type 'quit' to exit): ");


InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);

while (!(CurLine.equals("quit"))){
CurLine = in.readLine();

if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
}
}

Core Java By Paresh Bhavsar Page 59


Core Java Solution Paresh Bhavsar

Core Java By Paresh Bhavsar Page 60


Core Java Solution Paresh Bhavsar

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.*;

public class RandomAccessFileDemo {

public static void main(String[] args) throws Exception {

RandomAccessFile randomFile = new RandomAccessFile ("c:/test123.txt", "rw");


System.out.println ("Current Pointer of the file is " + randomFile.getFilePointer( ) );

}
}

Core Java By Paresh Bhavsar Page 61


Core Java Solution Paresh Bhavsar

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.*;

public class RandomAccessFileDemo {

public static void main(String[] args) throws Exception {

RandomAccessFile randomFile = new RandomAccessFile("d:/test123.txt", "rw");


System.out.println("Current Pointer of the file is " + randomFile.getFilePointer());
long lengthOfFile = randomFile.length( );
randomFile.seek( lengthOfFile );
randomFile.writeBytes("Inserting content at the end of the file");
randomFile.close();

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.

Core Java By Paresh Bhavsar Page 62


Core Java Solution Paresh Bhavsar

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.*;

class Student implements Serializable {

private int rollno;

Student(int rollno) {
this.rollno = rollno;
}

int getRollNo() {
return rollno;
}

public class ObjectWriteAndRead {

public static void main(String[] args) throws Exception {

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream ("d:/student.ser"));


os.writeObject(new Student(100));
os.close();
System.out.println("Object written successfully in file.");
System.out.println("_______Reading Object from File");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/student.ser"));
Student s = (Student)ois.readObject();
System.out.println("Object Successfully read. Id of the Student is " + s.getRollNo());
}
}

We can see run the program as shown below.

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

Core Java By Paresh Bhavsar Page 63


Core Java Solution Paresh Bhavsar

NotSerializableException. Below mention is exception throw when we do not implements


Serializable for the Student class. For example

class Student implements Serializable {

Key Points about Java IO Package

There are two kinds of streams byte-stream and character-stream


InputStream and OutputStream and its subclasses represent java byte
streams
System.in and System.out are byte streams for console
FileInputStream and FileOuputStream are byte streams for file reading and
writing operation
Reader and Writer type represents Character oriented streams
FileReader and FileWriter allows direct character reading/writing from file
InputStreamReader provides bridge between byte stream and character
stream
RandomAccessFile allows read as well as write on the file
RandomAccessFile object allows file pointer to be set at specific position
using seek method
ObjectOutputStream and ObjectInputStream classes write / read the object
to stream.

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.

Core Java By Paresh Bhavsar Page 64


Core Java Solution Paresh Bhavsar

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.

public class MainThreadDemo {

public static void main(String[] args) throws Exception {

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.

public class ThreadSleepDemo {

public static void main(String[] args) {

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
}
}

Core Java By Paresh Bhavsar Page 65


Core Java Solution Paresh Bhavsar

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

Thread provides two mechanism by which thread can be created.


1. extends Thread
2. implements Runnable

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.

Step 1: class must extends Thread class

class MyClass extends Thread {


…..
}

Step 2: Override run method from the Thread class

class MyClass extends Thread {

public MyClass (String threadName) {

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.

Core Java By Paresh Bhavsar Page 66


Core Java Solution Paresh Bhavsar

Step 3: Creating object of the MyThread class and call start method on it.

MyThread t1 = new MyThread( );


t1.start( );

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.

Here is complete program to create thread and run it.

class MyThread extends Thread {

public MyThread(String threadName){


super(threadName);
}

public void run() {

for(int x=0;x<10;x++){
System.out.println(Thread.currentThread().getName() + " : " + x);
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}

public class ThreadCreationDemo{

public static void main(String[] args) {


MyThread t1 = new MyThread("Thread One ");
t1.start();
MyThread t2 = new MyThread("Thread Two ");
t2.start();
}
}

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.

Core Java By Paresh Bhavsar Page 67


Core Java Solution Paresh Bhavsar

Below mentioned are steps to be followed whenever we want to create thread using implements
Runnable mechanism.

Step 1: class must implements Runnable Interface

class MyClass implements Runnable {


…..
}

Step 2: Override run method from the Thread class

class MyClass implements Runnable {

public void run() {


….
}
}

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.

MyThread obj = new MyThread( );


Thread t1 = new Thread(obj, “Thread One”);
Thread t2 = new Thread(obj, “Thread One”);
t1.start( );
t2.start();

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.

Here is complete program to create thread and run it.

class MyThread implements Runnable {

public void run() {

for(int x=0;x<10;x++){
System.out.println(Thread.currentThread().getName() + " : " + x);
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}

public class ThreadCreationDemo{

public static void main(String[] args) {

Core Java By Paresh Bhavsar Page 68


Core Java Solution Paresh Bhavsar

MyThread obj = new MyThread();


Thread t1 = new Thread(obj, "Thread One");
t1.start();
Thread t2 = new Thread(obj, "Thread Two ");
t2.start();
}
}

Note that implements Runnable is preferred approach because our class MyMath can still extend
another class.

Core Java By Paresh Bhavsar Page 69


Core Java Solution Paresh Bhavsar

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.

class MyThread implements Runnable {

int counter = 0; // instance variable which is shared by two threads t1 and t2

public void run() {


for(int x=0;x<10000;x++){
counter++;
}
}
}

public class ThreadSynchronizationDemo{

public static void main(String[] args) {

MyThread obj = new MyThread();


Thread t1 = new Thread(obj, "Thread One");
t1.start();
Thread t2 = new Thread(obj, "Thread Two ");
t2.start();
System.out.println(" Counter value is " + obj.counter);
}
}

Below mentioned is output of the program.

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.

Core Java By Paresh Bhavsar Page 70


Core Java Solution Paresh Bhavsar

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.

public class WaitNotifyDemo {

public static void main(String[] args) throws Exception {

Producer p = new Producer(“Producer”);


p.start();
Thread.sleep(10000);
synchronized(p){
p.notify();
}

}
}

class Producer extends Thread {

Producer(String name){
super(name);
}

public void run() {


try {
System.out.println(Thread.currentThread().getName() + " Waiting ...");
synchronized(this) {
wait();
}
System.out.println(Thread.currentThread().getName() + " Notification Received ...");

} catch (Exception e) {
e.printStackTrace();
}
}
}

Core Java By Paresh Bhavsar Page 71


Core Java Solution Paresh Bhavsar

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.

public class WaitNotifyDemo {

public static void main(String[] args) throws Exception {

Producer p = new Producer();


Thread t1 = new Thread(p);
t1.setName("Producer - 1 ");
Thread t2 = new Thread(p);
t2.setName("Producer - 2 ");
t1.start();
t2.start();
Thread.sleep(5000);
synchronized(p){
p.notifyAll();
}
}
}

class Producer implements Runnable {

public void run() {


try {
System.out.println(Thread.currentThread().getName() + " Waiting ...");
synchronized(this){
this.wait();
}
System.out.println(Thread.currentThread().getName() + " Notification Received ...");

} catch (Exception e) {
e.printStackTrace();
}

Core Java By Paresh Bhavsar Page 72


Core Java Solution Paresh Bhavsar

}
}

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.

Core Java By Paresh Bhavsar Page 73


Core Java Solution Paresh Bhavsar

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;

void setConsumer(Consumer c){


this.c = c;
}
@Override
public void run() {
try {
while (true) {
for (int x = 1; x <= 10; x++) {
System.out.println("Producing Unit No. " + x);
Thread.sleep(1000);
}
synchronized(c){
c.notify();
}
System.out.println(Thread.currentThread().getName() + " : Waiting for Consumer
Notify ...");
synchronized(this){
this.wait();
}
System.out.println(Thread.currentThread().getName() + " : Notificaiton Received by
Consumer.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

class Consumer implements Runnable {

private Producer p;

void setProducer(Producer p){


this.p = p;

Core Java By Paresh Bhavsar Page 74


Core Java Solution Paresh Bhavsar

@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 {

public static void main(String[] args) {

Producer p = new Producer();


Consumer c = new Consumer();
p.setConsumer(c);
c.setProducer(p);
Thread t1 = new Thread(p);
t1.setName("Producer Thread : ");
Thread t2 = new Thread(c);
t2.setName("Consumer Thread : ");
t1.start();
t2.start();

}
}

Core Java By Paresh Bhavsar Page 75


Core Java Solution Paresh Bhavsar

Explain Thread life-cycle?

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.

Core Java By Paresh Bhavsar Page 76


Core Java Solution Paresh Bhavsar

Explain yield method. Explain difference between yield and sleep


method?

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.

Core Java By Paresh Bhavsar Page 77


Core Java Solution Paresh Bhavsar

Java util package

Array are primarily used to store objects and primitives. But below mentioned are limitations of the
Array.

Arrays cannot grow dynamically. Arrays are of fixed size

Arrays can store only one type of the objects or data

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.

List list = new ArrayList();

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.

Student s = new Student();


Student s1 = new Student();
list.add(s);

Core Java By Paresh Bhavsar Page 78


Core Java Solution Paresh Bhavsar

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.

for (Object obj : list ) {


if ( obj instanceOf Student ) {
Student s = (Student) obj ;
}
}

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.

Core Java By Paresh Bhavsar Page 79


Core Java Solution Paresh Bhavsar

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.

Student s1 = new Student () ;

Student s2 = new Student () ;

System.out.println(s1==s2) ; // will return false because both reference are pointing to different
objects.

Core Java By Paresh Bhavsar Page 80


Core Java Solution Paresh Bhavsar

Below mentioned code will return us true because both references are pointing to the same objects.

Student s1 = new Student () ;

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.

public boolean equals(Object obj) {

return (this == obj);

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;
}

Core Java By Paresh Bhavsar Page 81


Core Java Solution Paresh Bhavsar

We also need to override the hashCode method. hashCode() method returns the prime number
using the rollno.

@Override

public int hashCode() {

int hash = 5;

hash = 79 * hash + this.rollno;

return hash;

Note that overriding equals and hashcode is the primary thing to be available in the class for which
we are using Set.

Set is an interface. We can use default implementation class HashSet.

Set set = new HashSet();

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 {

private int rollno;

Student(int rollno) {

this.rollno = rollno;

}
public int getRollno() {
return rollno;
}

public void setRollno(int rollno) {


this.rollno = rollno;
}

public Student() {
}

public boolean equals(Object obj) {


if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;

Core Java By Paresh Bhavsar Page 82


Core Java Solution Paresh Bhavsar

}
final Student other = (Student) obj;
if (this.rollno != other.rollno) {
return false;
}
return true;
}

public int hashCode() {


int hash = 5;
hash = 79 * hash + this.rollno;
return hash;
}

class SetDemo {

public static void main(String args[]) {

Student s1 = new Student(10);

Student s2 = new Student(10);

Student s3 = new Student(10);

Set set = new HashSet();


set.add(s1); set.add(s2); set.add(s3);
System.out.println("Size of the Set is " + set.size());

}
}

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.

Core Java By Paresh Bhavsar Page 83


Core Java Solution Paresh Bhavsar

Student s = (Student) map.get(10);

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 {

private int rollno;


private String name;

Student(int rollno, String name) {

this.rollno = rollno;
this.name = name;

}
public int getRollno() {
return rollno;
}

public void setRollno(int rollno) {


this.rollno = rollno;
}

public String getName(){


return name;
}

public Student() {
}

}
class MapDemo {

public static void main(String args[]) {

Map map = new HashMap();

for(int x=0; x<1000;x++) {

map.put(x,new Student(x,"Test " + x));

Core Java By Paresh Bhavsar Page 84


Core Java Solution Paresh Bhavsar

// 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.

List<Student> list = new ArrayList<Student>();

Set<Student> set = new HashSet<Student>();

Map<Integer, Student> map = new HashMap<Integer, Student>();

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.

Core Java By Paresh Bhavsar Page 85


Core Java Solution Paresh Bhavsar

List adding object without using generics

With generics we will have automatically add method allowing us to add student only.

Synchronization issues with the util package.

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.

class ConCurrentAddThread implements Runnable {

private List list;

public ConCurrentAddThread(List list){


this.list = list;
}

public void run() {


while(true){
try {
list.add(new Object());
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

Core Java By Paresh Bhavsar Page 86


Core Java Solution Paresh Bhavsar

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 {

private List list;

public ConcurrentIterateThread(List list) {


this.list = list;
}

public void run() {


while(true){
for(Object obj : list){
try {
System.out.println(obj);
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
} // end of catch
} // for ends
} // while ends
} // method ends

} // class ends

Below mentioned program starts both the threads.

import java.util.ArrayList;
import java.util.List;

public class ConcurrentModificationExample {

public static void main(String[] args) {

List list = new ArrayList();


ConCurrentAddThread addThread = new ConCurrentAddThread(list);
ConcurrentIterateThread iterateThread = new ConcurrentIterateThread(list);
Thread t = new Thread(addThread);
Thread t1 = new Thread(iterateThread);
t.start();
t1.start();

} // main ends

} // class ends

Core Java By Paresh Bhavsar Page 87


Core Java Solution Paresh Bhavsar

When we turn the program, we get the below mentioned exception.

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

If synchronization is not an issue we should If application is thread-based we should use


use HashMap. As the performance is better. HashTable. Performance will be degraded
compare to HashMap.

Core Java By Paresh Bhavsar Page 88


Core Java Solution Paresh Bhavsar

Practical Exercise:

Write Java class Student having rollno(int), name(String) and email(String).


Create two java object each having rollno 1 & 2, name “aaa” and “bbb” and
email as “a@a.com” and “b@b.com” . Write a java program which will sort
Student object based on the name of the Student.

import java.util.Set;

import java.util.TreeSet;

public class TreeSetDemo {

public static void main(String[] args) {

Set<Student> set = new TreeSet<Student>();

set.add(new Student(1,"aaa","a@a.com"));

set.add(new Student(2,"bbb","b@b.com"));

for(Student s : set){

System.out.println(s.name); // will print

class Student implements Comparable<Student> {

int rollno;

String name;

String email;

public Student(int rollno, String name, String email){

this.rollno = rollno;

this.name = name;

Core Java By Paresh Bhavsar Page 89


Core Java Solution Paresh Bhavsar

this.email = email;

@Override

public int compareTo(Student o) {

return this.name.compareTo(o.name);

@Override

public boolean equals(Object obj) {

if (obj == null) {

return false;

if (getClass() != obj.getClass()) {

return false;

final Student other = (Student) obj;

if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {

return false;

return true;

@Override

public int hashCode() {

int hash = 7;

hash = 97 * hash + (this.name != null ? this.name.hashCode() : 0);

return hash;

Core Java By Paresh Bhavsar Page 90


Core Java Solution Paresh Bhavsar

What is generics ? Explain with an example.

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.

Iterator<Student> iterator = list.iterator();

while(iterator.hasNext()) {

Student s = iterator.next();

We can also use HashMap using generics.

Map<Integer,Student> map = new HashMap<Integer,Student>();

Core Java By Paresh Bhavsar Page 91


Core Java Solution Paresh Bhavsar

Key Points

1. List, Map and Set are interfaces defined in the java.util package

2. List maintains ordered collection

3. ArrayList and LinkedList are implementation of List

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

6. HashMap is implementation of Map interface

7. TreeSet and TreeMap is used for sorted collection

8. LinkedList is useful only if inserting elements in the middle. For all other situation ArrayList is
better.

Core Java By Paresh Bhavsar Page 92


Core Java Solution Paresh Bhavsar

Appendix: Differences

Core Java By Paresh Bhavsar Page 93


Core Java Solution Paresh Bhavsar

Explain differences between below.

1. abstract class & interface

 Abstract class is a class in which at least one method is abstract.


Interface is 100 % abstract in nature. All methods in the an interface
are abstract
 Abstract classes can be inherited by other classes using extends
keyword. Interfaces can be implemented by other classes using
implements keyword
 Abstract class and interface cannot be instantiated (object cannot be
created)
 All variables declared in an interface are static and final by default
 Abstract class can extend other classes (abstract as well as non-
abstract classes) and implements interfaces. Interface can only
extend other interfaces.

2. throw & throws

 throws is a part of method signature for example,


public void test() throws Exception
 Throws is a part of method signature
 Throws means that any statement of the method can throw
exception. Exception is not handled in the method, method calling
statement will be from try-catch block
 Throw is a statement to throw exception for the user-defined
condition for example,
if(salary<0) {
throw new Exception(“Salary can not be negative”);
}

Core Java By Paresh Bhavsar Page 94


Core Java Solution Paresh Bhavsar

3. overloading vs overriding

 Overloading is “Same Method Name but change in Parameters of the


method”
 For example below mentioned are all overloaded methods
o public void test (int x, int y) { … }
o public void test ( ) { … }
o public void test ( ) (int x, char y) { … }
 Overloaded methods are in same class
 Overriding is “Same Method signature”. Methods will reside in the
different classes
 Overriding refers to dynamic polymorphism while overloading refers
to static polymorphism
 Overloaded methods are compile time binding as the compiler
decides which method to call at the run time because between
methods there is difference in parameters (type of parameter or no.
of parameters)
 Overridden method are run-time binding, as the JVM at the run-time
which method to call depending on which object it is referring to.

4. checked vs un-checked exception

 All exception which are sub-classes of RuntimeException is called un-


checked exception
 All Exception which are Exception and its sub-classes are called
checked exceptions
 Unchecked exceptions are not checked by compiler, method
throwing checked exception must be called from try-catch block
 Unchecked exception are not supposed to be part of throws (method
signature)

Core Java By Paresh Bhavsar Page 95


Core Java Solution Paresh Bhavsar

5. exception vs error

 Exception are conditions (run-time) which can be handled using try-


catch block
 Errors are those situation which can not be handled
programmatically (using try-catch block) for example,
OutOfMemoryError, StackOverFlowError etc
 All exception’s parent class is Exception class
 All error’s parent class is Error class
 Exception and Error class extends Throwable

6. Multiple Inheritance vs Multilevel Inheritance

 Multple inheritance is not supported in java


 In Multiple inheritance one class extends two or more classes
 One class can implements two interfaces but can not extends two
classes
 Multilevel inheritance is when the Parent class extends another
Parent class.
For example class Child extends Parent One { … } and class PareshOne
extends ParentTwo

7. String & StringBuffer

 String is an immutable class, meaning that string instances are not


destroyed once new instance is created. String instances are moved
to String-Pool instead of being garbage collected
 It is NOT preferable to use concatenation of String in loop as many
string objects are created and previous objects are not garbage
collected
 StringBuffer provides append method which can used in the loop
structure and only one object will be created of the same.

Core Java By Paresh Bhavsar Page 96


Core Java Solution Paresh Bhavsar

8. implements vs extends

 both are java keyword used in the inheritance concept of OO.


 One class can implements one or more interfaces using implements
keyword and inherit only one class using extends keyword for
example
public class ClassOne extends ClassTwo implements InfOne, InfTwo
 One interface can inherit only one interface using extends keyword
for example,
public interface InterfaceOne extends InterfaceTwo

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();

10. List vs ArrayList

 List is an interface while ArrayList is an implementation class


 As per the definition ArrayList implements List
 We can create reference of List which can point to ArrayList object
for example List list = new ArrayList

Core Java By Paresh Bhavsar Page 97


Core Java Solution Paresh Bhavsar

11. List vs Map

 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.

12. List vs Set

 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

13. HashMap vs HashTable

 HasMap and HashTable are part of java.util package


 Both classes maintains key-value pair of object and implementation
of Map interface
 HashTable all methods are synchronized, so HashTable is thread-safe
class
 HashMap is not thread-safe so two threads accessing the elements
and adding / removing elements will generate
ConcurrentModificationException

Core Java By Paresh Bhavsar Page 98


Core Java Solution Paresh Bhavsar

14. Application vs Applet

 Application are console based or windows based (GUI) which are


run by JRE installed on OS
 Applets are java class run in the browser JRE
 Application project has one class having main method
 Applets life-cycle is managed by init(), start(), paint(), stop() and
destroy() methods.
 Applets adds dynamism to web-pages used to games,
advertisement creation etc.
 Each applets MUST extends java.applet.Applet class
 Applications are run using java appname.class. Here
appname.class file has main method
 Applets require .html file having applet tag for example <applet
code=”myapplet.class” width=”100” height=”200”></applet>

15. Binary streams vs character streams

 Java.io package has two types of streams binary and character


 Binary streams reads / write binary data (e.g. image / video
contents)
 Characters streams reads / write character data (ASCII value files)
 InputStreams / OutputStreams and its subclasses represents
binary streams
 Reader / Writer and its subclasses represents character streams
 For example, FileInputStream is to read the binary content from
the file, it can read ASCII value of character file also.
 FileReader is to read character content from a file, it can NOT read
image / video file

Core Java By Paresh Bhavsar Page 99


Core Java Solution Paresh Bhavsar

16. FileWriter vs FileOutputStream

 FileWriter represents character stream while FileOutptStream


represents binary streams
 Both are part of java.io package used to write data to file system
 FileOutputStream has write method which require byte array to
be written
 FileWriter has write method which require String (character array)
to be written to file system
 If we are writing character contents FileWriter is preferable

Core Java By Paresh Bhavsar Page 100


Core Java Solution Paresh Bhavsar

Appendix: Practical Exercise: Solution

Core Java By Paresh Bhavsar Page 101


Core Java Solution Paresh Bhavsar

Practical Exercise
1. Create a java pgoram to generate random number between 0 to 150.

public class Test {

public static void main(String args[]){

double random = Math.random(); // Math class is java defined


// class having random method which return random number

random = random * 50;


// as random method is created between 0.0 to 1.0 by multiplying with
// 50 we genererated random number between 0.0 to 50.0

int randomInt = (int) random;


// we are explicitly converting double number into int so our random
//number will be between 0 to 50 now.

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.

public class Test {

public static void main(String args[]){

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.");

Core Java By Paresh Bhavsar Page 102


Core Java Solution Paresh Bhavsar

} else {
System.out.println("Value is greater than 100");
}
} // end of main method

} // end of Test class

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.

public class Test {

public static void main(String args[]){

int[] myarray = new int[50];


// declaring the size of the array which is 50. first element will be
// myarray[0] and last element will be myarray[49].

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];

Core Java By Paresh Bhavsar Page 103


Core Java Solution Paresh Bhavsar

// printing array

for(int m : myarray) { // called for-each statement (meaning for


each value of myarray which will be stored in m

System.out.println(m);

// printing min and maximum values

System.out.println("Maximum value is " + max);


System.out.println("Minimum value is " + min);

} // end of main method

} // end of Test class

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 {

int mfgyear; // instance variable


String color; // instance variable

void printValues(){ // method which is printing values of instance

Core Java By Paresh Bhavsar Page 104


Core Java Solution Paresh Bhavsar

variables.

System.out.println("Manufacturing year of vehicle is " +


mfgyear);
System.out.println("Color of vehicle is " + 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.mfgyear = 2010;
v2.mfgyear = 2011;

v2.color = "red";
v2.color = "white";

v1.printValues();
v2.printValues();

Core Java By Paresh Bhavsar Page 105


Core Java Solution Paresh Bhavsar

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 {

int mfgyear; // instance variable


String color; // instance variable

void printValues() {
// method which is printing values of instance variables.

System.out.println("Manufacturing year of vehicle is " + mfgyear);


System.out.println("Color of vehicle is " + color);

void setValues(int mfgyear, String color) {

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();

Core Java By Paresh Bhavsar Page 106


Core Java Solution Paresh Bhavsar

}
}

writing the same exercise using constructor.

class Vehicle {

int mfgyear; // instance variable


String color; // instance variable

void printValues(){ // method which is printing values of instance


variables.

System.out.println("Manufacturing year of vehicle is " +


mfgyear);
System.out.println("Color of vehicle is " + color);

void setValues(int mfgyear, String color) {

this.mfgyear = mfgyear; // this is java keyword which will


refer to instance variable of current class
this.color = color;

Vehicle(){ // called default constructor

mfgyear = 1999;
color = "white";
}

Vehicle(int mfgyear, String color) { // parameterized constructor...


also called constructor overloading

this.mfgyear = mfgyear; // this is java keyword which will


refer to instance variable of current class

Core Java By Paresh Bhavsar Page 107


Core Java Solution Paresh Bhavsar

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(2010,"red");

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;

Core Java By Paresh Bhavsar Page 108


Core Java Solution Paresh Bhavsar

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() {

Core Java By Paresh Bhavsar Page 109


Core Java Solution Paresh Bhavsar

@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();
}
}
}
}
});

// opening file dialog and io operatons for writing file


miSave.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent event) {
// creating file dialog with save - cancel button

Core Java By Paresh Bhavsar Page 110


Core Java Solution Paresh Bhavsar

FileDialog dialog = new FileDialog(frame, "File Save" , FileDialog.SAVE);


dialog.setVisible(true);
String fileName = dialog.getFile();
String dirName = dialog.getDirectory();
File file = new File(dirName,fileName);
FileOutputStream fos = null;
try {
// file writing using binary stream
// we can use FileWriter also
fos = new FileOutputStream(file);
// get the contents from the text area
String str = ta.getText();
byte[] contents = str.getBytes();
fos.write(contents);
fos.flush();
System.out.println("File Writing Completed Successfully");
} catch(Exception e){
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
});
// exit menu
miExit.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// frame location, size and visibility
frame.setLocation(100,100);
frame.setSize(400,400);

Core Java By Paresh Bhavsar Page 111


Core Java Solution Paresh Bhavsar

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
*/

public class ChangeColorApplet extends Applet implements Runnable {


@Override
public void init() {
// creating new thread on the current object : this
Thread t = new Thread(this);
t.start();
}
@Override
public void paint(Graphics g) {
// generating three random number between 0-255 range
int iRead = (int)(Math.random()*255);
int iGreen = (int)(Math.random()*255);
int iBlue = (int)(Math.random()*255);
// creating new color
Color c = new Color(iRead,iGreen,iBlue);
g.setColor(c);
// filling rectangle set color
g.fillRect(20,20,200,200);
}
@Override
public void run() {

Core Java By Paresh Bhavsar Page 112


Core Java Solution Paresh Bhavsar

// 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

<applet code="ChangeColorApplet.class" width="500" height="500">


</applet>

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));

Core Java By Paresh Bhavsar Page 114


Core Java Solution Paresh Bhavsar

} 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));
}
}
});

// adding items to the panel


p.add(tfFirst);
p.add(tfSecond);
p.add(list);
p.add(tfAnswer);
// close button on the frame
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

frame.add(p);
frame.setSize(500, 200);
frame.setLocation(100, 100);
frame.setVisible(true);
}
}

9. Producer thread produces 10 items and consumer thread consumes the


10 items after producer thread finishes production. Producer thread
resumes production after consumer thread finishes. Write below
mentioned using java thread and synchronization concepts.

public class ProducerConsumerDemo {

Core Java By Paresh Bhavsar Page 115


Core Java Solution Paresh Bhavsar

public static void main(String[] args) {


Producer p = new Producer();
Consumer c = new Consumer();
p.setConsumer(c);
c.setProducer(p);
Thread t1 = new Thread(p);
t1.setName("Producer Thread : ");
Thread t2 = new Thread(c);
t2.setName("Consumer Thread : ");
t1.start();
t2.start();

}
}

class Producer implements Runnable {


private Consumer c;
void setConsumer(Consumer c){
this.c = c;
}
@Override
public void run() {
try {
while (true) {
// producing 10 units
for (int x = 1; x <= 10; x++) {
System.out.println("Producing Unit No. " + x);
Thread.sleep(1000);
}
// notify consumer that production is over
synchronized(c){
c.notify();
}
// waiting for the consumer to notify
synchronized(this){
this.wait();
}
System.out.println(Thread.currentThread().getName() + " :
Notificaiton Received by Consumer.");
}

Core Java By Paresh Bhavsar Page 116


Core Java Solution Paresh Bhavsar

} catch (Exception e) {
e.printStackTrace();
}
}
}

class Consumer implements Runnable {


private Producer p;
void setProducer(Producer p){
this.p = p;
}
@Override
public void run() {
try {
while (true) {
// waiting for the producer to notify
synchronized(this){
this.wait();
}
for (int x = 10; x >= 1; x--) {
System.out.println("Consuming Unit No. " + x);
Thread.sleep(1000);
}
// notify producer that consumption is over
synchronized(p){
p.notify();
}
}
} 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;

Core Java By Paresh Bhavsar Page 117


Core Java Solution Paresh Bhavsar

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);

Core Java By Paresh Bhavsar Page 118


Core Java Solution Paresh Bhavsar

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;

Core Java By Paresh Bhavsar Page 119


Core Java Solution Paresh Bhavsar

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;

Core Java By Paresh Bhavsar Page 120


Core Java Solution Paresh Bhavsar

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) {

Frame frame = new Frame("Student Registration Frame");


// creating all labels
Label lname = new Label("Name");
Label laddress = new Label("Address");
Label lsex = new Label("Sex");
Label ledu = new Label("Education");
// creating textfields, radio button, drop-down etc.
final TextField tfName = new TextField(10);
// Text Area with 4 rows and 12 columns
final TextArea ta = new TextArea(4, 12);
CheckboxGroup cgb = new CheckboxGroup();
// we will add both the check box with group to create radio button
final Checkbox cbMale = new Checkbox("Male", cgb, true);
final Checkbox cbFemale = new Checkbox("FeMale", cgb, true);
// creating dropdown
final Choice education = new Choice();
education.add("Under-Graduate");
education.add("Graduate");
education.add("Post-Graduate");
// creating submit button
Button button = new Button("submit");
// form display text area
final TextArea taForm = new TextArea(7, 20);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
taForm.setText("");
taForm.append("Name : " + tfName.getText() + "\n");
taForm.append("Address : " + ta.getText() + "\n");

Core Java By Paresh Bhavsar Page 121


Core Java Solution Paresh Bhavsar

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);
}
}

13.Write a program to replace all “word1” by “word2” from a file1, and


output is written to file2 file and display the no. of replacement.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

/**
*
* @author Paresb
*/

Core Java By Paresh Bhavsar Page 122


Core Java Solution Paresh Bhavsar

public class FileCopy {

public static void main(String[] args) throws Exception {

File file = new File("d:/test.txt");


FileReader reader = new FileReader(file);
BufferedReader bReader = new BufferedReader(reader);
String str = bReader.readLine();
StringBuffer buffer = new StringBuffer();
while(str!=null){
buffer.append(str);
// reading second line
str = bReader.readLine();
}
reader.close();
bReader.close();
System.out.println("Contents of the Line are ::: " + buffer);
String contents = buffer.toString();
// replacing word1 with word2
contents = contents.replaceAll("word1", "word2");
System.out.println("Replaced contents are ::: " + contents);
FileWriter writer = new FileWriter(new File("d:/test_copy.txt"));
writer.write(contents);
writer.close();
System.out.println("File Copying Completed Successfully");
}
}

14.Declare a class called employee having employee_id and


employee_name as members. Extend class employee to have a subclass
called salary having designation and monthly_salary as members. Define
following:
- Required constructors
- A method to find and display all details of
employees drawing salary more than Rs. 20000/-.
- Method main for creating an array for storing these
details given as command line arguments and
showing usage of above methods.

Core Java By Paresh Bhavsar Page 123


Core Java Solution Paresh Bhavsar

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;
}
}

class Salary extends Employee {


String designation;
double monthly_salary;
Salary(int employee_id, String employee_name, String
designation, double monthly_salary) {
super (employee_id, employee_name);
this.designation = designation;
this.monthly_salary = monthly_salary;
}
void checkAndDisplayDetails() {
if(monthly_salary>20000) {
System.out.println("Details of Employee Having
Salary > 20000 Rs.");
System.out.println("Name " + employee_name);
System.out.println("Id " + employee_id);
System.out.println("Designation " + designation);
System.out.println("Monthly Salary " +
monthly_salary);
}
} // end of method }
// end of class

public class EmployeeDemo {


public static void main(String args[]) {
int id = Integer.parseInt(args[0]);
String name = args[1];
String designation = args[2];

Core Java By Paresh Bhavsar Page 124


Core Java Solution Paresh Bhavsar

double salary = Double.parseDouble(args[3]);


Salary emp = new Salary(id,name, designation,salary);
emp.checkAndDisplayDetails();
}
}

15.Write a method for computing xy by doing repetitive multiplication. x


and y are of type integer and are to be given as command line
arguments. Raise and handle exception(s) for invalid values of x and y.
Also define method main. Use finally in above program and explain its
usage.

public class X2YDemo {


public static void main(String[] args) {
try{
System.out.println(getAnswer(Double.parseDouble
(args[0]), Double.parseDouble(args[1])));
}
catch(Exception e) {
System.out.println("Command Arguments Not Present or
Numbers are not Correct");
e.printStackTrace();
}
}
private static double getAnswer(double x, double y){
double answer = 1;
while(y!=0) {
y = y-1;
answer *= x;
}
return answer;
}
}

16.Write a program to create a frame with exit capabilities. Handle events


for mouse pressed, mouse released, mouse clicked and mouse dragged
Core Java By Paresh Bhavsar Page 125
Core Java Solution Paresh Bhavsar

by displaying appropriate message describing the event at the


coordinates where the event has taken place.

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 {

public static void main(String[] args) {

final Frame frame = new Frame("My Frame");


frame.setLayout(new FlowLayout(FlowLayout.LEFT));
final Label l = new Label(" ") ;
frame.add(l);
frame.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");

@Override
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");

Core Java By Paresh Bhavsar Page 126


Core Java Solution Paresh Bhavsar

@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);
}
});

Core Java By Paresh Bhavsar Page 127


Core Java Solution Paresh Bhavsar

frame.setSize(500,100);
frame.setLocation(300, 300);
frame.setVisible(true);

}
}

17.Write a complete program to create a frame for providing GUI to


implement a stack for storing integer numbers. There are two buttons
called PUSH & POP and a text field. Clicking of button PUSH pushes the
number entered in the text field onto the stack. The click of button POP
pops an element from the stack and displays that in the text field.

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 {

public static void main(String[] args) {

Frame frame = new Frame("Stack Demo");


Label l = new Label("Enter a Number");
final TextField tf = new TextField(10);

Core Java By Paresh Bhavsar Page 128


Core Java Solution Paresh Bhavsar

Button pushButton = new Button("PUSH");


Button popButton = new Button("POP");
final Label msgLabel = new Label();

final Stack<Integer> stack = new Stack<Integer>();


pushButton.addActionListener(new ActionListener() {

@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()));

}
});

Panel p = new Panel();


p.add(l);
p.add(tf);
p.add(pushButton);
p.add(popButton);
p.add(msgLabel);
frame.add(p);
frame.setSize(300,300);
frame.setLocation(300,300);
frame.setVisible(true);

Core Java By Paresh Bhavsar Page 129


Core Java Solution Paresh Bhavsar

18.Write a complete multi-threaded program to meet following


requirements:
- Read matrix [A] m x n
- Create m number of threads
- Each thread computes summation of elements of one row, i.e. i th row
of the matrix is processed by i th thread. Where 0 <= i < m. - Print the
results.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Paresb
*/
public class ThreadMatrixReadDemo {

public static void main(String[] args) {

int[][] matrix = {{1,2,3},{2,3,4},{3,4,5}}; // creating 3x3 matrix


for(int x=0;x<matrix.length;x++){
ThreadMatrix thread = new ThreadMatrix("Thread : Row : x "+ x,
matrix);
thread.setRow(x);
thread.start();
}

class ThreadMatrix extends Thread {

int[][] matrix ;

Core Java By Paresh Bhavsar Page 130


Core Java Solution Paresh Bhavsar

int row;

public ThreadMatrix(String threadName, int[][] matrix) {


super(threadName);
this.matrix = matrix;
}

public void setRow(int row) {


this.row = 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);
}

19.Design a class named Fan to represent a fan. The class contains:


- Three constants named SLOW, MEDIUM and FAST with values 1,2 and
3 to denote the fan speed.
- An int data field named speed that specifies the speed of the fan
(default SLOW).
- A boolean data field named f_on that specifies whether the fan is
on(default false).
- A double data field named radius that specifies the radius of the fan
(default 4).
- A data field named color that specifies the color of the fan (default
blue).
- A no-arg constructor that creates a default fan.
- A parameterized constructor initializes the fan objects to given values.

Core Java By Paresh Bhavsar Page 131


Core Java Solution Paresh Bhavsar

- 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);

Core Java By Paresh Bhavsar Page 132


Core Java Solution Paresh Bhavsar

} 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();
}
}

15. Define the Rectangle class that contains:


Two double fields x and y that specify the center of the rectangle, the
data field width and height , A no-arg constructor that creates the
default rectangle with (0,0) for (x,y) and 1 for both width and height. A
parameterized constructor creates a rectangle with the specified
x,y,height and width.
A method getArea() that returns the area of the rectangle.
A method getPerimeter() that returns the perimeter of the rectangle.
A method contains(double x, double y) that returns true if the specified
point (x,y) is inside this rectangle.
Write a test program that creates two rectangle objects. One with
default values and other with user specified values. Test all the methods
of the class for both the objects.

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) {

Core Java By Paresh Bhavsar Page 133


Core Java Solution Paresh Bhavsar

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();

Core Java By Paresh Bhavsar Page 134


Core Java Solution Paresh Bhavsar

pointInsideResult = r2.contains(1, 1);


System.out.println("_______ Rectangle Details _______");
System.out.println("Area : "+ area);
System.out.println("Perimeter : "+ perimeter);
System.out.println("Point Inside Result : " + pointInsideResult);
}
}

Core Java By Paresh Bhavsar Page 135


Core Java Solution Paresh Bhavsar

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 Dear extends Animal {


}
class Donkey extends Animal implements Transport {
public void transport() {
System.out.println(“Transporting Donkey”);
}

public void deliver() {


System.out.println(“Camel !!! deliver);
}
}

Core Java By Paresh Bhavsar Page 136


Core Java Solution Paresh Bhavsar

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.

public class FileWordCountDemo {

public static void main(String[] args) {


FileInputStream fis = null;
try {
File file = new File(args[0]);
if(file.exists()){
System.out.println("File Exists.");
fis = new FileInputStream(file);
int x = fis.read();
StringBuffer buffer = new StringBuffer();
while(x!=-1){
buffer.append((char)x);
x = fis.read();
}
StringTokenizer tokenizer = new StringTokenizer
(buffer.toString()," ");
int count = tokenizer.countTokens();
System.out.println("Total No. of Words in file are " + count);

Core Java By Paresh Bhavsar Page 137


Core Java Solution Paresh Bhavsar

} 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();
}
}
}
}
}

Core Java By Paresh Bhavsar Page 138

S-ar putea să vă placă și