Sunteți pe pagina 1din 253

The

Complete
Reference

Java
Complete Video Lecture Series
First Edition

The only text book with video lecture.

Pankaj P Mutha

1
Before I start with java I want every one reading my book to
know that James Gosling invented Java and he is known as father
of JAVA. He is Canadian computer scientist (Born on May 19
1955).
I really don’t know why people get scared to learn programming.
Moment we start talking about classes and object concept people
are disinterested to continue with the subject further. What I have
decided is to take up the challenge to simplify the whole of Java
and at the same time make sure people enjoy learning. Best part
about this book is you get video lectures along with the book. I
am sure this will make your learning much better and easy.
At the end of the session students will not just complete the
course, but then they will learn the course with practical
examples. I am sure reader of this book will be better
programmer at the end.
Thanks,
Pankaj P Mutha

2
About Author – Pankaj P Mutha

He has got 10+ years of corporate training and work experience.


He has worked for top MNC companies. Teaching has always
been his passion. He has trained thousands of students in the field
of IT. He always believe that teaching is one of the most
challenging profession and requires lots of creativity to deliver
lecture.

3
Index
1. Installing JDK. And Configuring it
2.

4
Downloading and Configuring JDK

5
The very first think you need to understand, what JDK & JRE is.
If you are a developer and you are planning to develop and run
the software then JDK (Java Development Kit) is required. When
you download JDK from internet you also get JRE (JAVA
RUNTIME ENVIRONMENT) along with it. But if the software
is already developed and you need to only run the JAVA
application then JRE is enough.
In simple words, if you are developer then Download JDK, but
if you are planning to install java application in your computer
then only JRE is required.
My First java program.
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println("Hello World");

}
}
Step 1 – type the above program in notepad or any other editor
and save it with the extension .java
Example – MyFirstProgram.java

6
Step 2 – Copy the path till bin folder of JDK(Because inside bin
folder we have Java Compiler which compiles Java Code in
.class file)

Note – For the above program MyFirstProgram.class file will be


created in D: drive.
Step 3 – To run MyFirstProgram.class file, from the command
prompt navigate to D: drive.

Step 4 – now type the command: java MyFirstProgram


You will get the following output.

7
Let’s see the best practices to develop and compile the software.
Usually all the experienced developers create folder structure to
save java files and class files separately.
First create App Folder.

Inside App folder create two folders, one with the name src and
the other one with the name classes

8
In src folder we will store java files and in the classes folder class
files will be generated.

Before we compile the program, this time we will set the path
variable for JDK. The advantage is that you need not set the

9
directory structure to bin folder of JDK in command prompt
every time when you launch it.
To set the path variable do the following – Navigate to My
Computer >> right click >> Properties >> Advanced System
Setting >> Environment Variables >> Under System variable
>>select Path environment variable and click on edit.

10
Copy the path till bin folder of JDK.

At the end of path environment variable place a semicolon. Paste


the path in System variables window –

11
Now run javac command in command prompt window to check
is path variable set properly.

If you observe the above image, regardless of the current


directory javac command will work.
To compile the Java file stored in D:/App/src, do the following
Go to command window and set the current directory to
D:/App/src

In the above command what is –d ../classes

12
-d command is used to set the path where class file should be
generated
.. indicates from the current directory structure D:/App/src move
one folder up. That is in our example move to D:/App folder.
/classes indicated from D:/App/ move to the folder
D:/App/classes
Now navigate to D:/App/classes folder you will find class file
generated for the program MyFirstProgram.java

To run the class file, in the command prompt set the current
directory to D:/App/Classes and then type the command java
MyFirstProgram and there you go, you will get the output Hello
World as shown below

13
Note – cd ../classes will move one folder up to D:/App and then
to classes folder D:/App/Classes

Building complex software using basic editors like notepad or


notepad++ or EditPlus etc. is difficult. There is where now we
are going to use rich IDE (Integrated Development Environment)
like eclipse to build complex software
Many people use the term eclipse should be installed. Let me
correct you, eclipse is never installed, you just download it and
directly run to access eclipse. Please watch my video lecture to
see how to download and use eclipse. Once you download
eclipse you will get following icon in the eclipse folder

14
Just double click on the eclipse icon & eclipse will be launched.
Going forward we will write all the programs in eclipse IDE.
Note – Detailed description is given in my video lecture. Please
watch the video lecture & then read the book.
To understand the subject more clearly let’s discuss about the
following –
1. Composition
2. Compilation
3. Execution or Running

15
Composition –
In composition, develop a java file with the following program –
Class A {
Public static void main () {
System.out.println (“Hello World”);
}
}
Compilation –
In compilation java compiler present inside your bin folder of
JDK will take character code and will generate a byte code which
will be saved inside .class file.
Execution / Running –
Once the class file is generated, next in command prompt, we use
JAVA command. What java command does?
Firstly it will request operating system for memory on RAM for
execution. Once the memory is allocated for execution, JAVA
command will divide the memory into two parts –
1. Stack memory
2. Heap memory

16
What will be present in stack memory is the order in which
statements should be executed.
Heap memory is used for storage purpose. Please read classes
and objects chapter then continue with the following example -
Example -1
Class A {
Public static void main () {
System.out.println (“Inside Main”);
A a = new A();
a.test1();
}Public void test() {
System.out.println (“Inside test”);
}
}
Output –
Inside Main
Inside Test

17
Example 2 –
Class B {
Static int i=20;
Public static void main () {
B b = new B();
System.out.println(B.i);
b.test1();
}
Public void test() {
System.out.println(“Inside Test”);

18
}
}
Output – 20
Inside Test

19
What are Classes and Objects?

20
To understand this, let’s take simple analogy. Let’s assume I
want to start a pen manufacturing factory in India. To
manufacture pen the very first think what I require is a
machinery. To every time generate a pen, we have to hit on
generate button of machinery. And there you go, pen is
generated. As many time we hit on generate button of the
machinery a pen is generated.
In the analogy mentioned you can consider machinery as a class.
What is class? Class is a factory which generates objects.
Objects can be related to pen generated by the machinery.
Class Syntax –
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println ("Hello World");
}
To generate an object for class we make use of the syntax -
ClassName refVariable = new ClassName ();
Every time we use the statement new ClassName(); an object is
created on the RAM memory of your computer. Once the object
is created its memory address will be stored in refVariable
To understand this more clearly let’s take an example.
21
public class A {

static int var1=20;

public static void main(String[] args) {


A a = new A();
a.test1();
A.test2();

}
public void test1() {

System.out.println("Inside Test1");

}
public static void test2() {

System.out.println("Inside Test2");
System.out.println(A.var1);

}
}
In the above example the statement A a = new A(); will create
an object on RAM. Once the object is created on RAM what will
be present in the object is non-static members of the class. And

22
that objects memory address will be present in the refVariable
‘a’. Please see the image below:
a is a reference variable

Object for the Class A

Only non-static members or instance members are loaded into


the object. Static members will be stored in a common memory
location. In the above example there are two static members

23
1. public static void test2();
2. static int var1=20;
Both the above static statement will stored in Common memory
location and not inside the object. Both objects and static
members will be present inside the heap memory of your
computer. Please refer example 1 and 2 on page number 18, 19
and 20.
How to access instance/non-static member is –
refVariable.MemberName

Example -
a.test1();

How to access static members –

ClassName.MemberName
A.test2();

A.var1; even if you access the static variable using the syntax
a.Var1, the Java compiler will not throw error instead it will
automatically replace the statement a.Var1 with A.var1
internally.
Output for Class A will be

24
Inside Test1
Inside Test2
10

25
Variables and Data Types in Java

26
Variables in Java are classified into

1. Static variables
2. Instance variables
3. Local Variables
4. Reference Variables

Static variables – Static variables are declared outside all the


methods but inside the class using static keyword. Static
variables can be used anywhere in the program.

Example –

public class A {

static int i=10;


public static void main(String[] args) {
System.out.println(i);
}
}

Output – 10

Instance Variable – Instance variable are declared outside all


the methods, but then inside the class. They are accessed only

27
within the object. Hence reference variable is required to access
that.

Example –

public class A {

int i=10; //Instance Variable

public static void main(String[] args) {

A a = new A(); //creating object


System.out.println(a.i);
/* instance variable are accessed using reference variables.*/

}
}

Output -10

Local variables – They are created inside method and can be


accessed only within method and not outside that.

Example –
public class A {

28
public static void main(String[] args) {
int i=10;
System.out.println(i);

}
}

Output – 10

Reference Variable – These variables are used to store the


memory address of the object created in java. We have already
discussed about this in classes and objects chapter.

Data Types – It helps us to specify what kind of value can be


stored in a variable

Data Type Size


1. Byte 1 byte
2. Short 2 byte
3. Int 4 byte
3. Long 8 byte
4. Float 4 byte
5. Double 8 byte
6. char 2 byte
7. Boolean True or False

29
Note – String is a class.

Note - when Static and instance variables are not initialized by


the developer, then Java will initialize the variables to default
values as shown below:

Data Type Default Value


8. Byte 0
9. Short 0
3. Int 0
10. Long 0
11. Float 0.0
12. Double 0.0
13. char blank
14. Boolean False

Note - String by default is initialized to null.

Note – Local variables if not initialized, then it will throw error.

30
Methods and type casting (part 1)

31
To write the program in more organized manner and create better
reusability of the code we make use of methods in java. Please
see the following examples to understand how to access and
develop methods

Rule 1 – Method will get executed only when we call it. We can
call the same method multiple times.

public class A {

public static void main(String[] args) {


System.out.println("Inside Main");
}
public static void test1() {
System.out.println("Inside Test1");
}
public static void test2() {
System.out.println("Inside Test2");
}
}

For the above program we will get the output as “Inside Main”.
It will not print the content of test1 () and test2 () methods.
Because the rule is, “methods will get executed only when we
call that”. Look at the next program.

32
public class A {
public static void main(String[] args) {
System.out.println("Inside Main");
A.test1();
A.test2();
//I am calling test1() & test2() using class name because they are
//static members
}
public static void test1() {
System.out.println("Inside Test1");
}
public static void test2() {
System.out.println("Inside Test2");
}
}

The output for the above program will be –


Inside Main
Inside Test1
Inside Test2

Now let’s see how we call instance members.

public class A {
public static void main(String[] args) {
System.out.println("Inside Main");
A a = new A();
33
a.test1();
a.test2();
/* I am calling test1() & test2() using reference variable because
they are non-static members/instance members */
}
public void test1() {
System.out.println("Inside Test1");
}
public void test2() {
System.out.println("Inside Test2");
}
}

Rule 2 – Methods will return the value back to the place from
where it is called

public class A {

public static void main(String[] args) {


System.out.println("Inside Main");
A a = new A();
int total = a.test1(10, 20); //Calling Statement
System.out.println(total);
}

public int test1(int a, int b) { //Called Statement


System.out.println("Adding");
34
int c;
c=a+b;
return c;

Output – Inside Main


Adding
30

Rule 3 – Return type of the function should match with type of


return value.

Example –

public class A {

public static void main(String[] args) {

A a = new A();
System.out.println(a.test());
}

public double test()

35
{
return 20.3;
}
}

Example –

public class A {

public static void main(String[] args) {

A a1 = new A();
System.out.println(a1.test());
System.out.println(a1);

public A test()
{
A a2 = new A();
return a2;
}
}

Before we move with further rules on methods, we need to


understand typecasting
36
Type Casting on Variables – Process of converting particular
data type into required data type is called as Type Casting of
variables.

1. Auto up casting
2. Explicit Down casting

To understand this lets take simple analogy – Let’s assume we


have two glasses of different sizes.

Glass 1 Glass 2

If we pour water from smaller glass to bigger glass, water will


not spill out of glass, I mean there is no wastage of water. But
then if you look at the other way, which is if you pour water from
bigger glass to smaller glass water will spill and we will lose

37
some amount of water. Auto upcasting is similar to pouring water
from smaller glass to bigger glass. Explicit down casting is
similar to pouring water from bigger glass to smaller glass. In
case of explicit down casting there are chances of losing some
amount of data, but then in case of auto upcasting we will not
lose any data.

Example – Auto up Casting

public class A {

public static void main(String[] args) {

short i=10;
int j=i;
System.out.println(j);
}
}

In above example int is of 4 byte and short is of 1 byte. This will


automatically type cast short to int and stores the data 10 in
variable j as integer.

Example – Explicit Down Casting

public class A {
38
public static void main(String[] args) {
long i=10;
int j=(int)i;
System.out.println(j);

}
}

In the above example we are type casting bigger data type to


smaller data type. To do this we have to do it explicitly or else
we will get error in the program, but then converting smaller data
type to bigger data type will happen automatically in the
program.

Rule 4 - If the method is returning smaller data type value and


the return type of the function is bigger data type then auto up
casting will happen.

public class A {

public static void main(String[] args) {

A a = new A();
System.out.println(a.test());

39
}

public int test() {


short i=10;
return i;
}
}

Rule 5 – If the method is returning bigger data type and the return
type of the function is smaller data type, then make sure Explicit
down casting is done.

public class A {

public static void main(String[] args) {

A a = new A();
System.out.println(a.test());
}

public short test() {

int i=10;
return (short)i;
}
}
40
Inheritance and type casting(part 2)

41
In inheritance properties of one class is inherited into another to
create better reusability of the code and easy enhancements.

Image there are two classes –

1. Class A
2. Class B

Class A has the following code and it is parent class or super


class–

public class A {

public void test1() {


System.out.println("Inside Test1");
}

public void test2() {


System.out.println("Inside Test2");
}

Class B has the following code and it is child class–

class B extends A {

42
public static void main(String[] args) {

System.out.println("Inside Main - B");


B b = new B();
b.test1();
b.test2();
}
}

When we write class B extends Class A, what’s technically


happening is all the instance members of A can be accessed in
class B. But the question arises why should we inherit the
members of one class into another? Inheritance creates better
reusability of the code and enhancements of the code is much
simpler in the project. Let’s assume we have already developed
a class for free ads, people posting ads as free subscriber will get
following facilities.

1. Add description
2. Add contact number
3. Add email id

On the other hand I want to develop one more class for PaidAds
where user along with the above three features they also get
additional features like

1. Assign dedicated manager and

43
2. Select the page location where ad should be displayed

Example –

public class FreeAds {

public void addDescription(String Description) {

System.out.println("Your description is:"+ Description);

public void addcontactNumber(String phoneNumber) {

System.out.println("Your phoneNumber is:"+ phoneNumber);

}
public void addEmailId(String emailId) {

System.out.println("Your emailId is:"+ emailId);


}
}

class PaidAds extends FreeAds {

public static void main(String[] args) {

44
PaidAds postAd = new PaidAds();
postAd.addDescription("Want to sell four wheeler");
postAd.addcontactNumber("9632629455");
postAd.addEmailId("pankaj@gmail.com");
postAd.addManager("Smith");
postAd.addPageName("HomePage");
}

public void addManager (String ManagerName) {


System.out.println("Your ManagerName is:"+ ManagerName);
}

public void addPageName (String PageName) {

System.out.println("Your ad is uploaded to:"+ PageName);


}

Super most parent class in java is Object class. All the class
which we write by default is inherited from Object class. Even in
the following example Class A is actual inherited from Object
class. Please see my video lecture to understand this more
clearly.

Once we are clear about inheritance, now let’s discuss about


Type Casting for class –
45
Type Casting for class –

1. Auto up casting
2. Explicit down casting

Auto up casting – Here parent class reference will point to child


class object.

Eample –

public class A {

public void test() {


System.out.println("Inside Test");
}
}

class B extends A {

public static void main(String[] args) {

A a = new B(); //Auto Up Casting


a.test();
}
}
Explicit Down casting – Here super class is assigned to child
class.

46
public class A {
public void test2() {
System.out.println("Inside Test 2");
}
}
class B extends A{

public static void main(String[] args) {

A a = new A();
B b = new B();
a=b;
b=(B)a;
b.test2();

}
}

47
Method overriding and method overloading

48
Why method overriding is required?

Imagine there are two classes. In class one there are three
methods with the name test1(), test2(), test3() and class two there
are two methods with the name test1(), test2(). If you want to
reuse the members of class A into class B then as we discussed
earlier we know that inheritance will help us to do that. But what
if I want to inherit methods from class A into class B and change
the implementation of certain methods as per the requirement of
my project. Then to do this we require inheritance & method
overriding concept –

Example –

public class FirstClass {

public void test1() {


System.out.println("Inside Test 1 of First Class");
}

public void test2() {


System.out.println("Inside Test 2 of First Class ");
}
public void test3() {
System.out.println("Inside Test 3 of First Class ");
}
}

49
class SecondClass extends FirstClass {

public static void main(String[] args) {

SecondClass sc = new SecondClass();


sc.test1();
sc.test2();
sc.test3();
sc.test4();
}

public void test1() {


System.out.println("Inside Test 1 of Second Class");
}

public void test4() {


System.out.println("Inside Test 4 of Second Class");
}

Output –
Inside Test 1 of Second Class
Inside Test 2 of First Class
Inside Test 3 of First Class
Inside Test 4 of Second Class

50
When we are overriding the method, make sure that both
methods have same signatures.

To get this concept more clearly let’s take one example –

public class SavingsAccountPlanOne {

public void rateOfInterest() {

System.out.println("You will get 4% on deposit


maintained/year");
}

public void averageBalance() {

System.out.println("Average balance should be 1,00,000");


}

public void checkBooks() {

System.out.println("checkBooks- unlimited/year");
}

public void phoneBanking() {

System.out.println("phoneBanking- Yes Support will be


provided");

51
}
public void netBanking() {

System.out.println("netBanking- Yes Support will be


provided");
}
}

class SavingsAccountPlanTwo extends


SavingsAccountPlanOne{

public static void main(String[] args) {


SavingsAccountPlanTwo plantwo = new
SavingsAccountPlanTwo();
plantwo.averageBalance();
plantwo.rateOfInterest();
plantwo.checkBooks();
plantwo.phoneBanking();
plantwo.netBanking();
}

public void rateOfInterest() {

System.out.println("You will get 6% on deposit


maintained/year");
}

52
public void averageBalance() {

System.out.println("Average balance should be 3,00,000");


}

OutPut –

Average balance should be 3,00,000


You will get 6% on deposit maintained/year
checkBooks- unlimited/year
phoneBanking- Yes Support will be provided
netBanking- Yes Support will be provided

In the above example the difference between Savings Account


plan one and plan two is, In plan two you additional rate interest
of 2% on balance maintained, but then you have to maintain the
average balance of Rs. 3,00,000. Rest all options in plan one and
plan two are same. So if you look at the above program. Firstly I
inherited all the members of SavingsAccountPlanOne to
SavingsAccountPlanTwo and then the requirement was to
change the methods rateOfInterest and averageBalance in the

53
class SavingsAccountPlanTwo. To achieve this I am overriding
the methods rateOfInterest and averageBalance.

So hope overriding is clear, but then what is method overloading


and where it can be used?

Many a times if you have noticed when we use using certain web
applications we get the option - login to continue or continue
without logging options. But whether you login or not you will
the same options. In method overloading the signatures of the
methods will be different but then their names will be the same.

Example –

public class User {

public static void main(String[] args) {

User user = new User();


user.Login("pankaj@gmail.com");
System.out.println("---------------------------------");
System.out.println("Other User");
System.out.println("---------------------------------");
user.Login();

54
}

public void Login(String username) {

System.out.println("you have logged in: "+username);


System.out.println("click to see old cars");
System.out.println("click to see house for sale:");
System.out.println("click to see mobile phones on
sale:");
}

public void Login() {

System.out.println("click to see old cars");


System.out.println("click to see house for sale:");
System.out.println("click to see mobile phones on
sale:");
}

Output –

you have logged in: pankaj@gmail.com


click to see old cars
click to see house for sale:

55
click to see mobile phones on sale:
---------------------------------
Other User
---------------------------------
click to see old cars
click to see house for sale:
click to see mobile phones on sale:

56
Loops and Conditional Statements

57
What if as a programmer you want to execute certain statements
based on conditions? In java we have following conditional
statements –

1. If
2. If – else
3. Elseif
4. Switch

Before we learn about conditional statements in detail, we should


know some of the scenarios where are Boolean values practical
used. I am sure everyone is already aware of relational operators.
In java we have following relational operators –

>, <, >=, <=, !=, ==

Whenever we use any relational operators, the comparison


happens inside ALU of your computer. Please see the diagram
below –

58
The output of ALU is always Boolean value true/false.

public class RelationalOperators {

public static void main(String[] args) {


int a=10,b=20;

System.out.println(a==b);
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a>=b);
System.out.println(a<=b);
System.out.println(a!=b);

59
Output –

false
false
true
false
true
true

Now it makes sense to discuss about conditional statements –

1. If – works only when the condition is true


Syntax –

If (condition) {

Example 1 –

public class ConditionalStatements {

public static void main(String[] args) {

int i=10, j=20;


60
if (i>j) {
System.out.println("i is greater");
}
}
}

For the above program we will not get any output, because the
condition i>j will return false upon comparison.

Example 2 –

public class ConditionalStatements {

public static void main(String[] args) {

int i=100, j=20;

if (i>j) {
System.out.println("i is greater");
}
}
}
Output - i is greater

61
2. If –else – when the condition returns Boolean value true,
if part will be executed, but if the condition returns
Boolean value false then else part will be executed.

public class ConditionalStatements {

public static void main(String[] args) {

int i=10, j=20;

if (i>j) {
System.out.println("i is greater");
} else {
System.out.println("j is greater");
}
}
}

Output – j is greater

3. Elseif – If statement works only for true condition, if-else


statement works for true and false condition. When we
want to write program to check multiple conditions then
we use Elseif statements.

62
Example –

public class ConditionalStatements {

public static void main(String[] args) {

int i=10, j=20;

if (i==j) {
System.out.println("i is equal to j");
} else if (i>j) {
System.out.println("i is greater than j");
} else if (i<j) {
System.out.println("j is greater than i");
}
}
}

Output –
j is greater than i

4. Switch –
Example –
public class ConditionalStatements {

public static void main(String[] args) {

63
int caseval=1;
switch (caseval) {

case 1: System.out.println("Inside Case One");


System.out.println("Execution Completed");
break;

case 2: System.out.println("Inside Case Two");


System.out.println("Execution
Completed");
break;

case 3: System.out.println("Inside Case Three");


System.out.println("Execution
Completed");
break;
}
}
}

Output –
Inside Case One
Execution Completed

64
Loops – When you want to repeat certain statements repeatedly
then we use loops.

1. For
2. While

For – We use for loop when we know number of iterations well


in advance

Example – Write a program to enter the pin number. If you enter


valid pin number, then we should get the message welcome, but
incase if you enter invalid pin number more than thrice
incorrectly then we should get the message card is blocked.
Note – Keep the pin number 1234 fixed.

import java.util.Scanner;

public class ConditionalStatements {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

for (int i=0;i<3;i++){


System.out.println("Enter the Pin Number:");
int pinNumber = in.nextInt();

65
if (pinNumber == 1234) {
System.out.println("Welcome");
break;
} else {
System.out.println("Invalid Pin Number");
}

if (i==2) {
System.out.println("Your Card is blocked");
}

}
}

If you see the above program I am using for loop because the
numbers times I should repeat the statements is defined well in
advance.

While – When we don’t know the number of iterations well in


advance then we use while loop.

Example – Write a program to withdraw money, where end user


will enter the amount to be withdrawn. Number of times the
66
amount to be withdrawn is decided by the end user, and hence
we don’t know the number of iterations to be repeated well in
advance.

import java.util.Scanner;

public class ConditionalStatements {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String cnd = "yes";


while (cnd.equals("yes")) {

System.out.println("Enter the amount:");


int amount = in.nextInt();

System.out.println("Please Collect Rs."+amount);

System.out.println("Do you want to continue:");


cnd = in.next();

}
}

67
Output-
Enter the amount:
1000
Please Collect Rs.1000
Do you want to continue:
yes
Enter the amount:
2000
Please Collect Rs.2000
Do you want to continue:
no

68
Unary Operators in Java

69
There are four types of unary operators in java –

1. Post increment – Changes will reflect in the next usage


and not in the current usage of the variable

Example 1 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = i++; //In current usage it will be 10
System.out.println(j);
System.out.println(i); //In next usage value of i will
increment by 1 so it will be 11

Output-
10
11

70
Example 2 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = i++ + i++;
System.out.println(j); //22
System.out.println(i); //12

Output –
21
12

Example 3 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = i++ + i++ + i++;
71
System.out.println(j); //33
System.out.println(i); //13

Output –
33
13

2. Pre Increment – Changes will reflect in the current usage


of the variable

Example 1 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = ++i;
System.out.println(j);
System.out.println(i);
}
}

72
Output –
11
11

Example 2 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = ++i + ++i;
System.out.println(j);
System.out.println(i);

Output –
23
12

73
Example - Both Post Increment and Pre Increment.

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = ++i + i++ + i++ + ++i;
System.out.println(j);
System.out.println(i);

Output –

48
14

74
1. Post decrement – Changes will reflect in the next usage
of the variable

Example 1 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = i--;
System.out.println(j);
System.out.println(i);

}
}

Output –
10
9

Example 2 -

public class UnaryOperators {

public static void main(String[] args) {

75
int i = 10;
int j = i-- + i-- - i--;
System.out.println(j);
System.out.println(i);

Output –
11
7

3. Pre Decrement – Changes will reflect in the current usage


of the variable

public class UnaryOperators {

public static void main(String[] args) {


int i = 10;
int j = --i;
System.out.println(j);
System.out.println(i);

76
}

Output –
9
9

Example 2 –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = --i - --i + --i;
System.out.println(j);
System.out.println(i);

Output –
8
7
77
Example – Both Post and Pre Decrement

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = --i - --i + --i + i-- + i--;
System.out.println(j);
System.out.println(i);

Output-
21
5

One more Example –

public class UnaryOperators {

public static void main(String[] args) {

int i = 10;

78
int j = --i - ++i + --i + i++ + i--;
System.out.println(j);
System.out.println(i);

Output
27
9

79
Interface and Abstract class

80
To understand the main purpose of interface we will take a
simple analogy. Let’s assume it’s my first day to office and
before I start with my work I am supposed to sign contract with
the company to make sure that as an employee I will follow the
terms and conditions mentioned in the contract. What all rules I
am supposed to follow is clearly specified in the contract
document. If I do not follow any rules then it will be breach of
contract. In this analogy you can consider contract as interface
and employee as class. That is a class which implements the
interface should use the methods present in the interface.

Interface will help developers understand what classes they are


supposed to develop. It gives them more clarity in terms of what
all functionality they are supposed to develop in the project. All
the methods in interface by default will be public and abstract.

But then abstract class is also more over like a contract signed,
but it is not a strict contract. In other words abstract class can
have abstract and non-abstract methods.

Example – Interface

interface ExampleInterface {

void a();
void b();
void c();

81
void d();

class Test implements ExampleInterface {

public void a() {


System.out.println("Inside a");
}

public void b() {


System.out.println("Inside b");
}

public void c() {


System.out.println("Inside c");
}

public void d() {


System.out.println("Inside d");
}

82
class manager {

public static void main(String[] args) {


Test t = new Test();
t.a();
t.b();
t.c();
t.d();
}
}

Example – abstract

package com.testingcampus.example;

abstract class ExampleAbstract {

abstract public void test1();


abstract public void test2();

public void test3() {


System.out.println("Inside Test3");
}

83
package com.testingcampus.example;

class F extends ExampleAbstract {

@Override
public void test1() {
System.out.println("Inside Test1");

@Override
public void test2() {
System.out.println("Inside Test2");

public void test4() {


System.out.println("Inside Test4");
}

public static void main(String[] args) {


F t = new F();
t.test1();
t.test2();
t.test3();
t.test4();

84
}

Important point about Interface –

1. Can contain only abstract methods


2. Interface supports multiple inheritance
3. Interface can contain only static and final variables
4. 100% incomplete

Important point about abstract class –

1. Can contain abstract and non-abstract methods


2. Can contain main method
3. Does not support multiple inheritance
4. 0% - 100% incomplete
5. We can never create object for abstract class

85
Arrays

86
Imagine I want to store the age of four employees, Now that’s
simple to do, I will just create four variables age1, age2, age3,
age4 and then store the respective age into it. Please see the
example shown below.

public class EmpolyeeAge {

public static void main(String[] args) {


int age1, age2, age3, age4;
age1 = 27;
age2 = 24;
age3 = 26;
age4 = 28;

System.out.println(age1);
System.out.println(age2);
System.out.println(age3);
System.out.println(age4);

Thank god!! There were only four employees working in


company!!!! Think of the situation what if there were 100
employees working in company, then definitely I cannot do that
87
tedious work to create 100 variables and then store the age of the
employee in it.

Note- Variables can only store one value at a time and will store
the most recent value in it.

Example –

public class EmpolyeeAge {

public static void main(String[] args) {


int age1, age2, age3, age4;
age1 = 27;
age1 = 28;
/*In the above step value 28 will overwrite 27. Because variables
will store only one value at time and that too most recent value
will be stored in it */
System.out.println(age1);

Output – 28

88
The best solution for the above problem would be to use arrays.
Arrays is used to store data of similar type in easier manner.

Example 1 – Arrays

public class ExampleArray {

public static void main(String[] args) {

int[] age = new int[3];

age[0]=27;
age[1]=25;
age[2]=29;

System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);

89
In the above example we declared the array with the size 3, that
is we can store 3 items in the array, and all the items stored in the
above array should be of the type integer. But it is not the best
practice to read the array as done in the above program. Rather
to read the array we make use of for loops as shown in the
program below.

Example -2

public class ExampleArray {

public static void main(String[] args) {

int[] age = new int[3];

age[0]=27;
age[1]=25;
age[2]=29;

for (int i=0;i<3;i++) {


System.out.println(age[i]);
}

90
}
Ouput –
27
25
29

Again example above show cases how for loop can be used to
read/print the values of array. But till the code written above is
not the best practice. Because when we change the size of array
we have to alter the condition value in for loop. To enhance the
code further we will make use of length function in arrays. Please
see the example shown below.

Example 3 –

public class ExampleArray {

public static void main(String[] args) {

int[] age = new int[3];

age[0]=27;
age[1]=25;
age[2]=29;

for (int i=0;i<age.length;i++) {

91
System.out.println(age[i]);
}

If you want to know how many items we can store in array, just
make use of the length function as shown above.

For arrays to read/print the values from arrays we have exclusive


loop called as for each. Please the example below to see how for
each works.

public class ExampleArray {

public static void main(String[] args) {


int[] age = new int[3];

age[0]=27;
age[1]=25;
age[2]=29;

for (int k:age) {


System.out.println(k);
}
}
92
}

In the above example K is variable and age is an array. Now how


for each works is, values from the array age will be copied one
by one into variable k and then we are printing the value of k. we
keeping reading the values from array as long as we have not
reached the final index.

Very importantly we should know how to return array from a


method in java.

public class ExampleArray {

public static void main(String[] args) {

int[] res = new int[3];


ExampleArray eArray = new ExampleArray();
res = eArray.returnArray();

for (int j: res) {


System.out.println(j);
}
}

public int[] returnArray() {

93
int[] age = new int[3];

age[0]=27;
age[1]=25;
age[2]=29;

return age;
}

94
Constructors

95
Constructors in java is a special kind of method which is called
when the object is created. When we are creating constructors we
should follow the rules mentioned below –

1. Constructor and class name should be same.


2. Constructors cannot return values.
3. Constructors are not inherited.

Example 1 –

public class ConstructorExamples {

public ConstructorExamples() {
System.out.println("Inside the constructor");
}

public static void main(String[] args) {


ConstructorExamples cm = new ConstructorExamples();

Output –
Inside the constructor

96
Example 2-
public class ConstructorExamples {

public ConstructorExamples(String name) {


System.out.println("My Name is: "+name);
}

public static void main(String[] args) {

ConstructorExamples c = new ConstructorExamples("Pankaj");

Output –
My Name is: Pankaj
Example 3 – Constructor overloading

public class ConstructorExamples {

public ConstructorExamples() {
System.out.println("Inside no argument constructor");
}

97
public ConstructorExamples(String name) {
System.out.println("(Inside constructor with arguments)My
Name is: "+name);
}

public static void main(String[] args) {

ConstructorExamples cm1 = new ConstructorExamples();


ConstructorExamples cm2 = new ConstructorExamples("Pankaj");

Output –
Inside no argument constructor
(Inside constructor with arguments)My Name is: Pankaj

98
This keyword

99
1. This keyword refers to the current object.

Example 1-

public class ConstructorExamples {

public void test() {


System.out.println(this);
}

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();

System.out.println(cm);
cm.test();

Example 2 –

public class ConstructorExamples {

public void test2() {

100
System.out.println("Inside Test2");
}
public void test1() {
this.test2();
System.out.println("Inside Test1");
}

public static void main(String[] args) {


ConstructorExamples cm = new ConstructorExamples();
cm.test1();
}

}
2. This cannot be used in static blocks.

public class ConstructorExamples {

public void test2() {


System.out.println("Inside Test2");
}
public static void test1() {

this.test2();
System.out.println("Inside Test1");
}

101
public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();

this.test1();

Output –

Exception in thread "main" java.lang.Error: Unresolved


compilation problem: Cannot use this in a static context at
ConstructorExamples.main(ConstructorExamples.java:19)

3. If you don’t use this, then compiler will place this operator
automatically.

Example –

public class ConstructorExamples {

public void test2() {


102
System.out.println("Inside Test2");
}
public void test1() {

test2();
System.out.println("Inside Test1");
}

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();


cm.test1();

Output –
Inside Test2
Inside Test1

4. This keyword can be used to invoke current class


constructor. And it should be the very first statement
inside the constructor

103
Example -1

public class ConstructorExamples {

public ConstructorExamples(String name) {


this();
System.out.println("My name is: "+name);
}

public ConstructorExamples() {

System.out.println("Inside no argument Constructor");

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples("Pankaj");

104
Example 2 –

public class ConstructorExamples {

public ConstructorExamples(String name) {

System.out.println("My name is: "+name);


}

public ConstructorExamples() {
this("Pankaj");
System.out.println("Inside no argument Constructor");

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();

}
Output –
My name is: Pankaj
Inside no argument Constructor

105
Super keyword

106
1. Super keyword refers to the parent class instance variables
and methods in java

Example 1-

class parentClassTOConstructorExamples {

public void test() {


System.out.println("Inside test method -
ParentClassTOConstructorExamples");
}
}

Public class ConstructorExamples extends


parentClassTOConstructorExamples {

public void test() {


super.test();
System.out.println("Inside test - ConstructorExamples");
}

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();


cm.test();

107
}

Output –
Inside test method - parentClassTOConstructorExamples
Inside test – ConstructorExamples

2. Super keyword is used to call parent class constructor in


java.

Example –

class parentClassTOConstructorExamples {

public parentClassTOConstructorExamples() {
System.out.println("Inside Constructor -
parentClassTOConstructorExamples");
}
}

public class ConstructorExamples extends


parentClassTOConstructorExamples {

108
public ConstructorExamples() {
super();
System.out.println("Inside Constructor -
ConstructorExamples");
}

public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();

Exercise – On this keyword

public class ConstructorExamples {

int i;

public void test(int i) {


this.i=i;

109
public static void main(String[] args) {

ConstructorExamples cm = new ConstructorExamples();


cm.test(20);
System.out.println(cm.i);
}

Output –
20

110
Packages

111
The main purpose of packages in java is to organize your code.
To create package we make use of the following statement –

package com.testingcampus.example;

public class A {

public void test() {

System.out.println("Inside Test - A");


}
}

To import the class present inside the package we write the code
as shown below –

import com.testingcampus.example.A;
public class B {

public static void main(String[] args) {

A a = new A();
a.test();

}
112
In simple words you can say packages are similar to folders. Why
we create folders? So that we can keep the content organized,
similarly why we create packages? So that we can create
programs in organized manner.

113
Access Specifier

114
There are four types of access modifiers in java-

1. Public
2. Protected
3. Private
4. Default

Access Specifier provides better level of security to programs.


Access Specifier in java may look complex, but then I have
simplified it with the help of table show below -

Accessing Members

Private Default Protected Public


Same Class Yes Yes Yes Yes
Same No Yes Yes Yes
Package
subclass
Same No Yes Yes Yes
Package
non-
subclass
Different No No Yes Yes
package
subclass

115
Different No No No Yes
Package
non-
subclass

116
Exception handling in java

117
What are Exception?

When a bad user input is given by the programmer then the


program halts abruptly because of which none of the further lines
of code will execute. And hence this will not let the user to
interact with the application further. For example – when the card
is inserted properly in the ATM machine, the ATM machine
program will work properly, but then think of a scenario what if
a user inserts the card incorrectly, this bad input will abruptly halt
the ATM machine and none of the other users will be able to use
it. As of now the solution is restart the ATM to solve the problem.
118
As a good programmer we have to make sure that bad user inputs
are handled properly, that is when a program throws exception
we should handle the exception and educate the user about what
went wrong in the program.

As shown in the exception diagram above, Exceptions are of two


types –
1. Runtime Exception
2. Straight Away Exceptions

Both runtime and straight away exceptions are inherited from the
class Exception, And Exception class is inherited from the class
Throwable.

RUNTIME Exceptions

During compilation of the program we never get exceptions, but


then during runtime of the program we get exception.

1. Arithmetic Exception - Imagine a user is trying to divide


the number by ZERO, we know that number can never be
divided by ZERO. Hence the program throws Arithmetic

119
exception as it is mathematical expression and because of
exception none of the further lines of code will execute.

public class ExceptionExamples {

public static void main(String[] args) {

int j = 10;
int i = 0;
int k = j/i;
System.out.println("k");
System.out.println("Execution Compeleted");

Output - Exception in thread "main"


java.lang.ArithmeticException: / by zero
at ExceptionExamples.main(ExceptionExamples.java:8)

To solve the problem we have to handle the exception and how


we do that is we make use of try, catch blocks. There is also
something called as finally block which we will discuss latter.

Solution to above problem

120
public class ExceptionExamples {

public static void main(String[] args) {

int j = 10;
int i = 0;

try {
int k = j/i;
System.out.println("k");
}
catch (ArithmeticException e) {
System.out.println("Cannot divide the
number by ZERO");
}

System.out.println("Execution Completed");

Output - Cannot divide the number by ZERO


Execution Completed

121
2. Null Pointer Exception – Imagine that due to some
reason object is not created in the program and the
reference variable contains no reference to object.
Reference variable is set to null. Using null reference
variable if you are calling the instance method we will get
Null Pinter Exception.

Example –

public class ExceptionExamples {

public static void main(String[] args) {

ExceptionExamples a=null;
a.test();
}

public void test() {


System.out.println("Inside Test");
}
}

Solution to above program –

public class ExceptionExamples {


public static void main(String[] args) {

122
ExceptionExamples a = null;

try {

a.test();
}
catch (NullPointerException e) {
System.out.println("Object is not created for
the class ExceptionExamples");
}

public void test() {


System.out.println("Inside Test");
}

3. Number Format Exception – When an invalid


conversion of the number is performed in the program, we
get Number Format Exception.

123
Example –

public class ExceptionExamples {

public static void main(String[] args) {

String str = "Pankaj";


int i = Integer.parseInt(str);

Output –
Exception in thread "main" java.lang.NumberFormatException:
For input string: "Pankaj"
at
java.lang.NumberFormatException.forInputString(Unknown
Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ExceptionExamples.main(ExceptionExamples.java:9)

Solution to above problem –

public class ExceptionExamples {


124
public static void main(String[] args) {

String str = "Pankaj";

try {
int i = Integer.parseInt(str);
}
catch (NumberFormatException e) {
System.out.println("Invalid conversion");

System.out.println("Execution Completed");

4. Array Index Out Of Bound Exception – If the items


stored in array exceeds the size of array we will get Array
Index Out Of Bound Exception.

Example –

public class ExceptionExamples {

125
public static void main(String[] args) {

int[] a = new int[2];


a[0]=20;
a[1]=21;
a[2]=22;

System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);

System.out.println("Execution Completed");

In the above example size of the array is 2, which means it can


store only two items, but then we are trying to store three items
and hence we get an exception.

Solution to above problem –


public class ExceptionExamples {

public static void main(String[] args) {

126
int[] a = new int[2];

try {
a[0]=20;
a[1]=21;
a[2]=22;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
}
catch (ArrayIndexOutOfBoundsException e ) {
System.out.println("Exceeding the limit of
array - Sorry cannot perform initialization operation");
}
System.out.println("Execution Completed");

}
}
Output –
Exceeding the limit of array - Sorry cannot perform initialization
operation Execution Completed

5. Class Cast Exception – When parent class object is


referenced to child reference variable, we get class cast
Exception.

Example –

127
class A {
public void test() {
System.out.println("Inside Test");
}
}

public class ExceptionExamples extends A{

public static void main(String[] args) {

ExceptionExamples ex = (ExceptionExamples) new A();


ex.test();
}
}

Exception in thread "main" java.lang.ClassCastException: A


cannot be cast to ExceptionExamples
at ExceptionExamples.main(ExceptionExamples.java:15)

Solution to above problem is –

class A {
public void test() {
System.out.println("Inside Test");
}
}

128
public class ExceptionExamples extends A{

public static void main(String[] args) {

try {
ExceptionExamples ex = (ExceptionExamples) new A();
ex.test();
}
catch (ClassCastException e){
System.out.println(e);
}
System.out.println("Execution Completed");

}
}

Non – Runtime/Straight Away Exceptions

During Compilation of the program we get exceptions.

1. Class Not Found Exception –

Example –
public class ExceptionExamples {

129
public static void main(String[] args) {

Class.forName("A");
System.out.println("Execution Completed");
}
}

Class.forName() statement is used to load the class in the


required program. But in the above program there is no class with
the name “A” and hence we get the following exception –

Exception in thread "main" java.lang.Error: Unresolved


compilation problem:
Unhandled exception type ClassNotFoundException

at ExceptionExamples.main(ExceptionExamples.java:11)

Solution to above problem is –


class A {

public void test() {


System.out.println("Inside Test");
}
}

130
public class ExceptionExamples {

public static void main(String[] args) {

try {
Class.forName("A");
System.out.println("class Loaded.....");
} catch (ClassNotFoundException e) {

System.out.println("Class Was Not loaded");


}

}
}

In the above example A will be successfully loaded. And we get


the following output -class Loaded.....

Example –

class A {

public static void test() {


System.out.println("Inside Test");
}
}

131
public class ExceptionExamples {

public static void main(String[] args) {

try {
Class.forName("A");
System.out.println("class Loaded.....");
A.test();
} catch (ClassNotFoundException e) {

System.out.println("Class Was Not loaded");


}

}
}

Output –

class Loaded.....
Inside Test

To understand further IO and FileNotFound Exception we have


to first understand File Handling Concept in java.

132
File Handling and Exceptions part 2

133
In java to write the data into file and read the data from file we
make use of the class FileOutputStream and FileInputStream
respectively.

Reading data from text file –

Example – 1
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileHandling {

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

try {
int i=0;
FileInputStream file = new FileInputStream("D://Pankaj.txt");
while ((i=file.read())!=-1){
134
System.out.print((char)i);

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

Output – Testing Campus

Sometimes it might so happen that when we are reading data


from text file or writing data into text file the operation may get
interrupted. If the read/write operation is interrupted java
program will throw exception and if the exception is not handled
then program will halt abruptly. To handle this exception we
make use of the class IOException.

Sometimes there are also possibilities that when we are trying to


interact with the file and if the file is missing, then again the
program will throw exception. In order to handle such exceptions
we make use of FileNotFoundException Class.

135
Please see the program written above to understand IO and
FileNotFound Exception. Please watch the video lectures to
understand this more clearly.

Writing data into text file –

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileHandling {

public static void main(String[] args) throws


FileNotFoundException {

FileOutputStream file = new


FileOutputStream("D://Pankaj.txt");
String str = "Testing Campus";
byte data[] = str.getBytes();

try {
file.write(data);
file.close();
} catch (IOException e) {
e.printStackTrace();
}

136
}
}

In the above program we have made use of throws clause. What


is throws clause?

Let’s discuss about that with the help of an example.

Example – For Throws Clause.

Whenever we use throws clause to handle the exception, then the


developer of the function will not handle the exception, instead
the caller of that function will handle the exception.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

class ABC {

public void write() throws IOException {


FileOutputStream file = new
FileOutputStream("D://Pankaj.txt");
String str = "Testing Campus";
byte b[] = str.getBytes();
file.write(b);
file.close();

137
}
}

public class ThrowAndThrows {

public static void main(String[] args) {

ABC a = new ABC();


try {
a.write();
} catch (IOException e) {
e.printStackTrace();
}

But if you want the developer of the function to handle the


exception then he should use try catch block to do that.

Example –

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

138
class ABC {

public void write() {

FileOutputStream file = null;


try {
file = new FileOutputStream("D://Pankaj.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str = "Testing Campus";
byte b[] = str.getBytes();

try {
file.write(b);
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

139
public class ThrowAndThrows {

public static void main(String[] args) {

ABC a = new ABC();


a.write();

When do we use throw clause? As a programmer when we want


to create customized exceptions or if we want to explicitly throw
exceptions then we use throws clause.

Example – What if the user is trying to withdraw the amount


from his account and he has low balance.

public class insufficientFunds extends Exception {

public insufficientFunds() {
System.out.println("Low Balance!!!!");
}

140
}

public class BankAccount {

public static void main(String[] args) {

try {
throw new insufficientFunds();
} catch (insufficientFunds e) {
e.printStackTrace();
}
}

Output –
Low Balance!!!!
insufficientFunds
at BankAccount.main(BankAccount.java:7)

Difference Between try, catch, finally

As we discussed earlier we know that when exception occurs


then try block will throw exception to catch block and catch
block will handle that. But many a times it might be required that

141
whether exception are thrown are not we have to execute certain
statements. There is where we make use of finally block.

Example –

public class ExampleFinally {

public static void main(String[] args) {

try {
int a=10/0;
System.out.println(a);
} catch(ArithmeticException e) {

e.printStackTrace();

}
finally {
System.out.println("I will always run no matter what happens");
}

Output –
java.lang.ArithmeticException: / by zero

142
at
com.testingcampus.example.ExampleFinally.main(ExampleFin
ally.java:8)
I will always run no matter what happens

Example –

public class ExampleFinally {

public static void main(String[] args) {

try {
int a=10/2;
System.out.println(a);
} catch(ArithmeticException e) {

e.printStackTrace();

}
finally {
System.out.println("I will always run no matter what happens");
}

143
Output –
5
I will always run no matter what happens

144
Threads

145
To know clearly what are threads and what’s the purpose of
threads in java, we should know –

1. Multi-Processing
2. Multi-Tasking

Best example to understand what multi-processing is we need


to understand the way SETI (Search for extraterrestrial
intelligence) operated. The main core research what this institute
was doing was find new existence of life on any other planet. But
to do this research they wanted many computers to process the
signals. As the investments to do this was high, SETI decided to
use the computers of residents of our country at their will. Every
signal to be processed now SETI had dedicated processor. In
simple terms, to perform multi-processing, we should have
multiple processors. So that each processor will handle particular
task.

But on the other hand, to understand multi-tasking think of the


scenario where in your computer you open word document, text
file and you are listening to some music. There are three task to
be performed but there is only one processor in your computer to
do that. So how your computer would operate is, processor will
switch between the task quickly and try to complete the task turn
by turn in small quantity giving us a feel that all the work are
getting executed at the same time.

146
Purpose of thread is to write programs to achieve better multi-
tasking. There are two ways to create threads in java

1. By Implementing Thread class


2. By Implementing Runnable Interface

Example – Using Thread Class

package com.testingcampus.example;

public class ExampleThread extends Thread {

public void run() {

for (int i=0;i<100;i++) {


System.out.println("Task 1 - "+i);
}
}
public static void main(String[] args) {

ExampleThread th = new ExampleThread();


th.start();

147
for (int i=0;i<100;i++) {
System.out.println("Task 2 - "+i);
}

Example – Using Runnable Interface

package com.testingcampus.example;

public class ExampleThread implements Runnable{

public void run() {

for (int i=0;i<100;i++) {


System.out.println("Task 1 - "+i);
}
}
public static void main(String[] args) {

ExampleThread Eth = new ExampleThread();


Thread th = new Thread(Eth);

148
th.start();

for (int i=0;i<100;i++) {


System.out.println("Task 2 - "+i);
}

}
When the first thread is called and we make that sleep
for 500 millisecond, then the thread scheduler will pick
the next thread for execution.

Note - you can never start the same thread twice. If you
try to do that we will get IllegalThreadStateException.

Example -
public class ExampleSleepThread extends Thread{

public void run() {


try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

149
for (int i=0;i<100;i++) {
System.out.println(i);
}
}

public static void main(String[] args) {

ExampleSleepThread th1 = new ExampleSleepThread();


ExampleSleepThread th2 = new ExampleSleepThread();

th1.start();
th2.start();
th2.start();

Part of output -
Exception in thread "main"
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at
com.testingcampus.example.ExampleSleepThread.main(
ExampleSleepThread.java:25

150
Thread life cycle –

Example –
public class ThreadLifeCycle {

public static void main(String[] args) {

G a1 = new G();
System.out.println("1:"+a1.getState());
a1.start();
System.out.println("2:"+a1.getState());

try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
151
System.out.println("3:"+a1.getState());

class G extends Thread {

public void run() {

}
}

Output –
1:NEW
2:RUNNABLE
3:TERMINATED

Synchronization -
When two threads are accessing common data, there are chances
that the data might get corrupted. Imagine that for the same user
account we are depositing amount in the bank and at the same

152
time from ATM the amount is withdrawn. If both the operations
are happening simultaneously then balance might not be
calculated properly.
Example –

public class ExampleSynchronization {

int balance;
public static void main(String[] args) {

ExampleSynchronization u = new ExampleSynchronization();


u.account();
System.out.println("Balance:Rs."+u.balance);

public void account() {

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
add();

153
});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
sub();

});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

public void add() {

154
for (int i=0;i<10000;i++)
balance = balance+1;
}

public void sub() {


for (int i=0;i<10000;i++){
balance = balance-1;
}

In the above example there are two threads created t1 and t2.
Both the threads are at the same time they are calling add () and
sub () method. When you see the output you will notice that
balance will not be calculated properly, because if you are adding
10,000 and you are withdrawing the balance 10,000 then the final
balance should be ZERO. But when you run the program you
will notice that output will be different every time.

To solve the above program, we use the concept of


synchronization. When we synchronize the methods, at a given
point of time only one thread can access the required method.
That is first add () method will be called and only then sub ().
Hence you will get the right balance which will be ZERO. Please
see the program shown below.

155
Example -

public class ExampleSynchronization {

int balance;
public static void main(String[] args) {

ExampleSynchronization u = new ExampleSynchronization();


u.account();
System.out.println("Balance:Rs."+u.balance);

public void account() {

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
add();

});
Thread t2 = new Thread(new Runnable() {

156
@Override
public void run() {
sub();

});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

public synchronized void add() {


for (int i=0;i<10000;i++)
balance = balance+1;
}

157
public synchronized void sub() {
for (int i=0;i<10000;i++){
balance = balance-1;
}

Output – Balance:Rs.0

Notify (), Wait (), Notifyall () –

Think of a scenario, where there are ten patients waiting for the
doctor. It’s obvious that the doctor cannot diagnose all the 10
patients at the same time. What the doctor will do is, he will call
first patient and then diagnose the patient, and meanwhile all
other nine patients will be waiting for the doctor to notify them.
Once done with first patient doctor will notify that the other
patient can come in and same process will continue for all other
patients. Taking the same analogy we will understand Notify(),
Wait(), NotifyAll().

158
Example –

public class WaitNotify {

public static void main(String[] args) {

AdderThread adder = new AdderThread();


adder.start();

synchronized (adder) {

try {
adder.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("Total:"+adder.total);

159
class AdderThread extends Thread{

int total;
public synchronized void run() {

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


total = total + i;

notify();
}

Output - Total:499500

Difference between notify & notifyall() –

Notify() - will notify only one thread which is in wait condition.


NotifyAll() – will notify all the threads which are in the wait
condition

160
Example - NotifyAll

public class Manager {

public static void main(String[] args) {

S s1 = new S();
S s2 = new S();
S s3 = new S();
A a1 = new A(s1);
B b1 = new B(s2);
D c1 = new D(s3);

a1.start();
b1.start();
c1.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}

161
s1.test2();
s2.test2();
s3.test2();
}

class S {

synchronized void test1() {


Thread t = Thread.currentThread();
System.out.println(t.getName()+" Priority:
"+t.getPriority()+" is going to wait");

try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(t.getName()+" Priority:
"+t.getPriority()+" is restarted to active");
}

synchronized void test2() {


notifyAll();
}

162
}

class A extends Thread {


S s1;
A (S s1) {
this.s1 = s1;
}

public void run() {


s1.test1();
}

class B extends Thread {


S s2;
B (S s2) {
this.s2 = s2;
}

public void run() {


s2.test2();
}

163
public class C extends Thread{

S s3;
public C(S s3) {
this.s3 = s3;
}

public void run() {


s3.test1();
}
}

Output –
Thread-0 Priority: 5 is going to wait
Thread-2 Priority: 5 is going to wait
Thread-2 Priority: 5 is restarted to active
Thread-0 Priority: 5 is restarted to active

Note - Performance of notifyall () is better when compared to


notify () method. Because notify method will randomly pick one
thread then will allow that for execution, but notifyall () will
notify all the waiting threads at once, and then the threads will
execute in queue and hence it’s faster

164
To get the Thread name we use the method Thread.currentThread
and getName’(). To see the priority of the thread we use the
method

Thread Dead Lock – Deadlock describes a situation where two


or more threads are blocked forever, waiting for each other.
Deadlock occurs when multiple threads need the same locks. A
Java multithreaded program may suffer from the deadlock
condition because the synchronized keyword causes the
executing thread to block while waiting for the lock. Here is an
example:

Example –

public class Util {

static void sleep(long millis) {

try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

165
public class Shared {

synchronized void test1(Shared S) {


System.out.println("test1 begin");
Util.sleep(1000);
S.test2(this);
System.out.println("test1 end");

synchronized void test2(Shared S) {


System.out.println("test2 begin");
Util.sleep(1000);
S.test1(this);
System.out.println("test2 end");
}

public class Manager {

public static void main(String[] args) {

Shared s1 = new Shared();


Shared s2 = new Shared();

A a1 = new A(s1,s2);

166
B b1 = new B(s1,s2);

a1.start();
b1.start();
}

public class A extends Thread {

Shared s1,s2;

A(Shared s1, Shared s2) {


this.s1 = s1;
this.s2 = s2;

public void run() {


s1.test1(s2);
}

public class B extends Thread{

Shared s1,s2;

167
B(Shared s1, Shared s2) {
this.s1 = s1;
this.s2 = s2;

public void run() {


s2.test2(s1);
}
}

Output –

test1 begin
test2 begin

The program will be stuck here.

Thread Pool - Thread Pools are useful when you need to limit
the number of threads running in your application at the same
time. But why should we limit the number threads running in our
application? The main purpose would be to increase the
performance

168
Instead of starting a new thread for every task to execute
concurrently, the task can be passed to a thread pool. A thread
pool contains collection of threads. As soon as the pool has any
idle threads the task is assigned to one of them and executed.
Thread pools are often used in servers. Each connection arriving
at the server via the network is wrapped as a task and passed on
to a thread pool. The threads in the thread pool will process the
requests on the connections concurrently. This is how we can use
existing thread instead of creating a new thread every time we to
accomplish the task and hence performance in terms of execution
can increased.

169
Collection

170
Think of a scenario where as a programmer I want to perform
search, sorting operation etc. Now this is quite complicated as we
have to build our own algorithm or technique to do that in case
of arrays. What if I say, you need not worry about that in Java?
In java we have frame work called collection. Which means logic
to perform search, sorting, insertion, deletion etc. is already
implemented and we are going to use that and not build the logic
to do that. Let’s now see different collection in Java.

171
Differences between Arrays and Collection –

Array Collection
It is Fixed Size Size of the collection is
dynamic
It can store only Can store both
homogeneous data homogeneous as well as
heterogeneous data
It terms of memory usage it It terms of memory usage it
is less efficient is more efficient
No underlying data structure Has got underlying data
structure to simply our
work

Difference between Collection and Collections -

Collection Collections
Collection is an interface Collections is a class
It stores several object as It is a utility class that’s
single entity helps us to perform
operations like sorting,
searching on objects
present inside collection.

1. List –
 It’s an interface
172
 Maintains insertion order
 Allows duplicate data

1.1 Array List –


 It can contain duplicate items
 It maintains insertion order
 Allows random access of data
 Internally it is implemented as dynamic arrays

Example –

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionFrameWork {

public static void main(String[] args) {


ArrayList<String> data = new ArrayList<String>();
data.add("Testing");
data.add("Campus");
data.add("Training");
data.add("Institute");

Iterator it = data.iterator();

while (it.hasNext()) {
173
System.out.println(it.next());
}

Output –

Testing
Campus
Training
Institute

You can also use for each loop to read the data from array –

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionFrameWork {

public static void main(String[] args) {


ArrayList<String> data = new ArrayList<String>();
data.add("Testing");

174
data.add("Campus");
data.add("Training");
data.add("Institute");

for (String str:data) {

System.out.println(str);

Output –
Testing
Campus
Training
Institute

If you want to remove a particular added item in Array List, then


we use remove method as shown below –

175
Example –

import java.util.ArrayList;
import java.util.Iterator;

public class CollectionFrameWork {

public static void main(String[] args) {


ArrayList<String> data = new ArrayList<String>();
data.add("Testing");
data.add("Campus");
data.add("Training");
data.add("Institute");

Iterator it = data.iterator();
data.remove(1);

for (String str:data) {

System.out.println(str);

176
}

Output –
Testing
Training
Institute

1.2 Linked List –

 Can contain duplicate data


 Maintains insertion order
 It’s internally implemented as doubly linked list

Example –

import java.util.Iterator;
import java.util.LinkedList;

public class CollectionFrameWork {

public static void main(String[] args) {


LinkedList<String> data = new LinkedList<String>();

177
data.add("Pankaj");
data.add("Smith");
data.add("Silk");
data.add("Sam");

Iterator it = data.iterator();

while (it.hasNext()) {

System.out.println(it.next());
}

Output –
Pankaj
Smith
Silk
Sam

Difference between ArrayList and LinkedList

178
ArrayList LinkedList
Internally implement as Internally implemented
dynamic arrays as doubly linked list
Memory allocation is Memory allocation need
continuous, hence it’s not that not be continuous, hence
efficient in terms of memory better utilization of memory
usage

2. Set –
 It’s an interface
 Does not maintain any insertion order
 Cannot contain duplicate values

2.1 Hash Set –


 Uses hash table internally
 Will contain only unique elements
 Does not maintain insertion order

import java.util.HashSet;
import java.util.Iterator;

public class CollectionFrameWork {


179
public static void main(String[] args) {

HashSet set = new HashSet();

set.add(21);
set.add(42);
set.add(25);
set.add(26);

Iterator it = set.iterator();

while (it.hasNext()) {
System.out.println(it.next());
}

}
}

Output –
21
25
42
26

180
There are following constructors available in hash set –

1. HashSet set = new HashSet() – Initial default size is 16,


and has load ration of 0.75
2. HashSet set = new HashSet(int initialSize) – Here you can
decide the initial size of the HashSet, but the load ratio will
remain 0.75
3. HashSet set = new HashSet(int intialSize, float loadRatio)
– Here as programmer you can decide the initial size and
load ratio

Example –

import java.util.HashSet;

public class CollectionFrameWork {

public static void main(String[] args) {

HashSet set = new HashSet();


set.add("Pankaj");
set.add("Smith");
set.add(10);
set.add(null);
set.add("Pankaj");

181
System.out.println(set);

}
}

Output –
[null, Smith, Pankaj, 10]

2.2 Linked Hash Set –


 Contains unique elements only like HashSet. It
extends HashSet class and implements Set
interface.
 Maintains insertion order.

Example –
import java.util.LinkedHashSet;

public class CollectionFrameWork {

public static void main(String[] args) {

LinkedHashSet set = new LinkedHashSet();


set.add("Pankaj");
set.add("Smith");

182
set.add(10);
set.add(null);
set.add("Pankaj");

System.out.println(set);

}
}

Output - [Pankaj, Smith, 10, null]

2.3 Tree Set –


 Contains unique elements only like HashSet.
 Maintains ascending order.

Example –

import java.util.TreeSet;

public class CollectionFrameWork {

public static void main(String[] args) {

TreeSet set = new TreeSet();


set.add("Pankaj");

183
set.add("Smith");
set.add("Adam");
set.add("Ram");
System.out.println(set);

}
}

Output –

[Adam, Pankaj, Ram, Smith]

3. Queue –
The Queue interface basically orders the element in
FIFO(First In First Out)manner.

3.1 PriorityQueue –
 The PriorityQueue class provides the facility of
using queue.
 But it does not orders the elements in FIFO
manner.

Example –

import java.util.Iterator;
184
import java.util.PriorityQueue;

public class CollectionFrameWork {

public static void main(String[] args) {

PriorityQueue queue = new PriorityQueue();

queue.add("Pankaj");
queue.add("Amith");
queue.add("Ricky");
queue.add("carl");

System.out.println(queue.peek());
queue.poll();
System.out.println("_______________");

Iterator it = queue.iterator();

while (it.hasNext()) {
System.out.println(it.next());
}
}
}

185
Ouput –

Amith
_______________
Pankaj
carl
Ricky

186
Collections Class

187
Points to remember-

 Collections class does not sort set.


 For sorting in set you can make use of TreeSet
 Collections class helps us to sort List

Example – To Sort Data

import java.util.ArrayList;
import java.util.Collections;

public class CollectionFrameWork {

public static void main(String[] args) {

ArrayList list = new ArrayList();

list.add("Pankaj");
list.add("Adam");
list.add("Carl");
list.add("Patrick");

188
Collections.sort(list);

System.out.println(list);
}
}

Output –

[Adam, Carl, Pankaj, Patrick]

Example - To search data –

import java.util.ArrayList;
import java.util.Collections;

public class CollectionFrameWork {

public static void main(String[] args) {

ArrayList list = new ArrayList();

list.add("Pankaj");
list.add("Adam");
list.add("Carl");
189
list.add("Patrick");

int index = Collections.binarySearch(list, "Carl");

System.out.println(list.get(index));

}
}

Output –

Carl

190
String

191
Many people they go wrong here and they tell that string is a
DataType in java. Let me correct you there, String is a class in
java. To work on string, java String class provides lots of
methods to do that. What all operations we can perform on string
let’s see that –

1. toUpperCase() and toLowerCase() - The java string


toUpperCase() method converts string into uppercase
letter and string toLowerCase() method converts string
into lowercase letter.

Example –

public class StringExamples {

public static void main(String[] args) {

String S = "PANkaj";

System.out.println(S.toLowerCase());
System.out.println(S.toUpperCase());

192
}

Output –
pankaj
PANKAJ

2. trim() – The string trim() method eliminates white spaces


before and after string.

Example –

public class StringExamples {

public static void main(String[] args) {

String S = " Pankaj ";

System.out.println(S);
System.out.println(S.trim());

Output –
Pankaj
Pankaj

193
3. startsWith() and endsWith() – Checks whether the string
with particular letter/letters and ends with particular
letter/letters.

Example –

public class StringExamples {

public static void main(String[] args) {

String S = "Pankaj";

System.out.println(S.startsWith("Pa"));
System.out.println(S.endsWith("k"));

Output –
true
false

4. charAt() - The string charAt() method returns a character


at specified index.

194
Example –

public class StringExamples {

public static void main(String[] args) {

String S = "Pankaj";

System.out.println(S.charAt(2));
System.out.println(S.charAt(1));

n
a

5. Length() – The string length() method returns length of the


string.

Example –
public class StringExamples {

public static void main(String[] args) {

195
String S = "Pankaj";

System.out.println(S.length());
;

Output –
6

6. valueOf() – The string valueOf() method coverts given


type such as int, long, float, double, boolean, char and char
array into string.

Example –

public class StringExamples {

public static void main(String[] args) {

int a = 10;
String s = String.valueOf(a);

System.out.println(s);

196
}

Output –
10

Before we proceed further now, we should know what are


mutable and immutable classes?

Immutable Class - Immutable class is a class where once its


objects are created then its state cannot be changed.

Steps to create Immutable Class –

1. Create a final class


2. Set the values of properties using only constructor
3. Make the properties final
4. Do not provide any setter for these properties

Example –

public final class ExampleImmutable {

private final int age ;

197
private final String name ;

public static void main(String[] args) {

ExampleImmutable im = new ExampleImmutable(20,"Pankaj");


System.out.println(im.getAge());
System.out.println(im.getName());

public ExampleImmutable(final int age, final String


name){
this.age = age;
this.name = name;
}

public int getAge() {

return age;

public String getName() {

return name;
}

198
}

Output –
20
Pankaj

In the above example you cannot change the value of the object
once created at any point of time. These kind of objects are called
as immutable objects.

But mutable class are the one whose properties can be changed.

Best implementation examples for this is –


String Class is immutable. Once object is created then its values
cannot be changed

7. String comparison – This can be done in three ways

7.1. Equals() – It compares the value of string objects


Example –
public class StringExamples {

public static void main(String[] args) {

199
String s1 = "Pankaj";
String s2 = new String("Pankaj");
String s3 = "Smith";

System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));

Output –
true
false

7.2.== - This will not compare values but then it will


compare the objects reference.
Example –

public class StringExamples {

public static void main(String[] args) {

200
String s1 = "Pankaj";
String s2 = "Pankaj";
String s3 = new String("Pankaj");
System.out.println(s1 == s2);
System.out.println(s1 == s3);

Output –
True
False

Please refer the diagram shown below to understand the concept


more clearly –

201
7.3. CompareTO() – compareTo() method compares
values and returns an int which tells if the values
compared are less than, equal, or greater than.

public class StringExamples {

public static void main(String[] args) {

String s1 = "Pankaj";
String s2 = "Pankaj";
String s3 = new String("Smith");
System.out.println(s1.compareTo(s2));

202
System.out.println(s1.compareTo(s3));

}
Output –
0
-3

8. Concat() - String concatenation method is used to add


strings.

public class StringExamples {

public static void main(String[] args) {

String s1 = "Pankaj";
String s2 = "Trainer";
System.out.println(s1.concat(s2));

Output –

203
PankajTrainer

9. substring –

Example –
public class StringExamples {

public static void main(String[] args) {

String s1 = "Pankaj Trainer";


String s2 = "Trainers";
System.out.println(s1.substring(0,6));
System.out.println(s2.substring(1));

Output –
Pankaj
Rainers

1. public String substring(int startIndex): This method


returns new String object containing the substring of the
given string from specified startIndex (inclusive).

204
2. public String substring(int startIndex,int endIndex):

This method returns new String object containing the


substring of the given string from specified startIndex to
endIndex.

As we know that string class in immutable, that’s is once the


string class object is created its value cannot be changed. But if
you want the string objects values to be changed during run time
then we use –

1. StringBuffer class – It is mutable and synchronized


2. StringBuilder class – It is mutable and non - synchronized

Example –

1. Append() – The append() method concatenates the given


argument with a string.

public class ExampleStringBuffer {

public static void main(String[] args) {

StringBuffer s1 = new StringBuffer("Hello ");


s1.append("Java");
System.out.println(s1);

205
String s2 = new String("Pankaj ");
s2.concat("Trainer");
System.out.println(s2);
}
}

Output –
Hello Java
Pankaj

2. Insert() – The insert() method inserts the given string with


a string at the given position.

public class ExampleStringBuffer {

public static void main(String[] args) {

StringBuffer s1 = new StringBuffer("Hello ");


s1.insert(1,"Java");
System.out.println(s1);

206
}

Output –
HJavaello

3. Replace – The replace() method replaces the given string


from the specified beginIndex to endIndex.

Example –

public class ExampleStringBuffer {

public static void main(String[] args) {

StringBuffer s1 = new StringBuffer("H");


s1.replace(1, 3,"Java");
System.out.println(s1);

}
}

Output –

207
HJava

4. Delete - The delete() method of StringBuffer class deletes


the string from the specified beginIndex to endIndex.

Example –

public class ExampleStringBuffer {

public static void main(String[] args) {

StringBuffer s1 = new StringBuffer("Hello");


s1.delete(1,4);
System.out.println(s1);
}
}

Output –
Ho

5. Reverse – The reverse() method of StringBuffer class


reverses the current string.

Example –

208
public class ExampleStringBuffer {

public static void main(String[] args) {

StringBuffer s1 = new StringBuffer("Hello");


s1.reverse();
System.out.println(s1);

}
}

Output –
olleH

StringBuilder –

Example -

public class ExampleStringBuilder {

public static void main(String[] args) {

StringBuilder s1 = new StringBuilder("Hello ");


s1.append("Pankaj");

209
System.out.println(s1);

}
}

210
Garbage Collector

One of the most unique feature what java has got is garbage
collector. To understand this let’s take simple analogy, that is
maid in your house is supposed to make sure that the dustbin in

211
your house does not overflow with the garbage. She has to dump
the garbage regularly. But as soon as you throw some garbage in
the dustbin she is not going to dump the garbage, she will wait
until some amount of garbage is filled and only then she will
dump it. Now java garbage collector works in the same way.
When many objects are created and they are not in use then JVM
will automatically call java garbage collector to clean up the
unused object. But when garbage collector will be called is quite
difficult to predict.

Even we can request java garbage collector to clean the objects,


but then there is no guarantee that the garbage collector will
execute and do the required work.

To remove the object from memory JVM will call finalize


method. Even we can call this method explicitly, but then there
is no guarantee that garbage collector will execute.

Example –

public class ExampleGarbageCollector {

@Override
protected void finalize() throws Throwable{
System.out.println("From Finalize");
}

212
public static void main(String[] args) {

ExampleGarbageCollector e = new
ExampleGarbageCollector();
e=null;
System.gc(); //Static method present inside the
System class
System.out.println("done");

Output –
Done
From Finalize

213
Clone

The process of copying the content of one object completely into


another object is called as cloning.

214
Example –

public class ExampleCloning implements Cloneable {

int i ;
public void test1() {
System.out.println("Inside Test1");
}

public void test2() {


System.out.println("Inside Test2");
}
public static void main(String[] args) throws
CloneNotSupportedException {

ExampleCloning e1 = new ExampleCloning();


ExampleCloning e2 = (ExampleCloning)e1.clone();

e1.test1();
e2.test2();

Output –
Inside Test1

215
Inside Test2

216
Hash Code

Hash code will return integer representation of memory address

Example –
217
public class ExampleHashCode {

public static void main(String[] args) {

ExampleHashCode e1 = new ExampleHashCode();


ExampleHashCode e2 = new ExampleHashCode();

System.out.println("e1 "+e1.hashCode());
System.out.println("e2 "+e2.hashCode());

Output –
e1 1432605192
e2 208811780

218
Annotations

Annotations was introduced in JDK 1.5 version. I am sure all us


would have seen annotations like @Override, @Deprecated.
When we talk about annotations we get several questions like

219
how it works and why it is used. Let me answer these questions
first so that you will get more clarity about annotations.

Let’s take the following example to get clarity on how it works -

Example – Let’s see how @Override work

class Z {
public void test() {
System.out.println("Inside Test - Z");
}
}

class K extends Z {

@Override
public void Test() {
System.out.println("Inside Test - K");
}
public static void main(String[] args) {

K k1 = new K();
k1.test();

220
Output - Inside Test - Z

In the above program the annotation @Override will inform the


compiler to check whether the method test is overridden or not.
If not overridden then we will get a message “The method Test()
of type K must override or implement a supertype method”, it
means that methods are not overridden because there is case
mismatch in methods name(in the parent and child class). This
will educate the developer whether the methods are overridden
or not. In the above example the methods are not overridden
hence we get the output – Inside Test Z

Example –

class Z {
public void test() {
System.out.println("Inside Test - Z");
}
}

class K extends Z {

@Override
public void test() {
System.out.println("Inside Test - K");
}

221
public static void main(String[] args) {

K k1 = new K();
k1.test();

Output –
Inside Test – K

Example - @SuppressWarnings

class K {
public static void main(String[] args) {

@SuppressWarnings("unused")
int i;
i=10;
}
}

Many a times when we declare the variable but then if it is not


used then we get some warning messages and if you want to tell
compiler to suppress warning messages then we can use
@SuppressWarnings.

222
Example 3 –

class K {

@Deprecated
public void test() {
System.out.println("Inside Test");
}
public static void main(String[] args) {

System.out.println("Inside Main");
}
}

@Deprecated annotation is used when we want to inform the


compiler that certain statements are no longer in use in our
program.

When we want to do unit testing using Junit or if in case you


want to map URL’s of servlets, we use pre-defined annotations.

223
Web Application Development

Firstly let’s understand what is the difference between Web site


and Web application?

224
Web site is static in nature. Here we do not do any data
manipulations.

Web application is dynamic in nature. Here we do data


manipulation. Example – Gmail, Facebook etc.

If you want to develop static application or website then html and


Css is enough. But then if you want to develop web application
in java then we should know servlets, jsp, JDBC etc. All these
concepts are included in J2EE which we will discuss in the next
sections where we will discuss how to develop a registration
form, Login page, sessions, tomcat etc.

225
Servlets

Servlet is a java class used to develop dynamic web page. Let’s


see how to build a servlet first and then we will discuss more on
working of servlets. To build the servlet, you have to download
226
tomcat and configure that in eclipse. What is tomcat? Tomcat is
a webserver. That’s the standard definition you get by everyone.
But if you ask me what is tomcat I would describe it as a piece
of software running on server which will accept the http request
from the client and based on the request required http response
will be sent back to the client. Without tomcat your server cannot
do anything. Tomcat is just one intelligent guy who knows what
to serve for every request and whom to server. In the latter
discussion when we talk about sessions and more about tomcat.
Now without wasting time let’s download tomcat from internet.

I have download in D: drive of my computer

Go to eclipse and servers tab click on “Click this link to create


new server”

227
If servers tab is not available then go to Window >> Show view
>> others >> servers

In new servers window select apache and the required tomcat


version. Then browse and select the Apache folder from D: drive
228
and click on finish. In package explorer you should see Servers
folder

In the package explorer right click>> New >> others >> select
Dynamic web project

229
Once you select dynamic project you will get following
window

230
In the above window give the project name as Servlet, and in
the same window select the target version of apache which you
have downloaded

Once you select servlet, you get the following window and in
the following window give the package and servlet name.

231
And click on next button,

232
In the above window URL mapping section contains the name
using which we can call a particular servlet from browser. If you
want you can change the name in URL mapping. Finally click on
finish button.

Once the servlet is created write the following program in the


servlet file –

package Com.Blogs.TestingCampus;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyFirstServlet")
public class MyFirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public MyFirstServlet() {
super();
}

233
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
PrintWriter out = response.getWriter();
out.print("<h3>Testing Campus</h3>");
}

Output –

You will get t output in the browser as Testing Campus.

Going forward you can use the following URL in the browser to
access the servlet –

http://localhost:8080/Servlets/FirstServlet

Next let’s discuss more about web.xml deployment descriptor.


And what is the purpose of that

Create a class called as Xmlservlet extends HTTPServlet

add doGet method in the class

234
Now map the above servlet to a particular URL, to do this go to
web.xml and add the following code.

<servlet>
<servlet-name>xmlservlet</servlet-name>
<servlet-class>give class name with package name</servlet-
class>
</servlet>

<servlet-mapping>
<servlet-name>xmlservlet</servlet-name>
<url-pattern>/xmlservletpath</url-pattern>
</servlet-mapping>

There is another way to map the URL and that can be done using
annotations. Please watch the video to understand how this can
be done.

How to pass parameters to servlets?

created a servlet class and in doGet() write the following code

response.setContentType("text/html")
PrintWriter out = response.getWriter();
out.println("Hello! User!")

Output – Hello! User!

235
Now let’s see how to pass parameters using the following
methods

1. GET
2. POST

GET method –

http://localhost:8080/SimpleServletProject/xmlservletpath?user
Name=Pankaj

Now in the servlet pick the request parameter sent from the
browser

String userName = request.getParameter("userName");


out.println("Hello! "+userName);

Now let’s see how to pass more parameters

http://localhost:8080/SimpleServletProject/xmlservletpath?user
Name=Pankaj&userId=xyz

String userName = request.getParameter("userName");


String userId = request.getParameter("userId");

out.println("Hello! "+userName+" Your Id is "+userId);

236
POST -

For this we will have to create a form using html

Right click on web content folder and create a html file and call
that as simpleform.html

<form method="POST" action="xmlservletpath">


<input name = "userName"/>
<input type = "submit"/>
</form>

next create doPost() in servlet and write the following code.

PrintWriter out = request.getWriter();


String userName = request.getParameter("userName");
out.println("Hello from POST method "+userName);

Lets now enhance the previous code -

<form method="POST" action="xmlservletpath">


User Name: <input name = "userName"/>
Full Name: <input name = "Fullname" />
Profession:
<inputtype="radio"name="prof"
value="Developer">Developer</input>

237
<input type="radio" name="prof"
value="Architect">Architect</input>
<select name="location" mulitple size=3>
<option value="Bangalore">Bangalore</option>
<option value="Chennai">Chennai</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Hyderabad">kochi</option>
<option value="Hyderabad">panaji</option>
</select>

<input type = "submit"/>


</form>

Next, in servlet doPost method add the following code.

PrintWriter out = request.getWriter();


String userName = request.getParameter("userName");
String fullName = request.getParameter("fullName");
String prof = request.getParameter("prof");
//String location = request.getParameter("location");
String[] location = request.getParametervalues("location");
//out.println("you are are at "+ location);
out.println("you are are at "+ location.lenght + "places");
for (int i=0;i<location.lenght; i++) {
out.prinln(location[i]);
}
out.println("you are a "+ prof);

238
out.println("Hello from POST method "+ userName + "!" +
fullName);

When to use Get and Post methods

GET is used when you want the data from database whereas
when you want to submit data to the database server then we use
POST method.

For POST method browser will throw warning message when we


refresh the browser, because are resubmitting the data, but GET
method upon refreshing the browser will not throw ant warning
message

Understanding Request, Session and context

What is Tomcat container?


Servlet runs within the tomcat containers, when browser makes
http request

When an http request is made to tomcat, it will creates two


objects:

1. request
2. response

239
Imagine one more browser makes request then new request and
response is processed using threads for better performance. We
will not every time create new objects every time when the
request in made. Further in the same chapter we will discuss on
this more clearly.

Very important, http is stateless protocol i.e. application on the


server will not remember the user. How do we make the
application server remember user.

Example - what if I want to remember userID throughout the


application, once logged in.

To do this Tomcat provides Session object

Example –

response.setContentType("text/html");
PrintWriter out = reponse.getWriter();
String userName = request.getParameter("name");
HTTPSession session = request.getSession();
if (userName !="" && userName!=null){
session.setAttribute("savedUserName",userName);
}
writer.println("Request parameter has username as "+
userName);

240
writer.println("session parameter has username as "+
(String) session.getAttribute("savedUserName"));

Sessions will remember the object one per user, but what if we
want data to be remembered across all/different the users, then
we have to use, then we have to use context object

Example –
Context is again implemented by tomcat

ServletContext context = request.getServletContext();


context.setAttribute("savedUserName", username);
PrintWriter out = request.getWriter();
out.println(context.getAttribute("savedUserName"));

241
Servlet life cycle and its working–

Before init and service, these are methods which run before
doGet and doPost

Init and service methods are present in the class Generic Servlet,
HTTPServlet is inherited from GenericServlet, doPost and doGet
are present in HTTPServlet, Servlet which we create will
override doGet and doPost.

When a user sends the request to the servlet for the first time,
then init () method will be called which will create request and

242
response object, then further based on request further service ()
method will decide whether to call doGet or doPost in the servlet.

243
Java Server Pages

244
When servlets can be used to build dynamic application then
question arises why we jsp to build dynamic application. To
know the answer for this we should first understand the draw
backups of servlets.

In servlets html is embedded in java code. The pro

245
Top Interview questions in java

1. What is the difference between JDK and JRE?


2. What are classes?
3. What is inheritance? Explain with one practical example?
4. What is overriding? Explain with a practical example?
5. What is the difference between final, finally and finalize?
6. What is garbage collector in java?
7. What are the different kinds of variables a class can
consist ?

246
8. What do you mean by constructor? How it can developed?
9. What are access modifiers in java?
10. What is the difference between static and non-static
members in java?
11. Explain Threads in java?
12. What are mutable and immutable objects in java? Give an
example?
13. What are exceptions? Give practical example for the
same?
14. What is the difference throw and throws keyword in java?
15. What are interface?
16. What are abstract class?
17. Difference between interface and abstract class?
18. What is the purpose of collection?

19. Difference between array and collection?


20. Difference between collection and collections?
21. What are packages? Why it is used?
22. What is this keyword?
23. What is super keyword?
24. What is the difference this and super keyword?
25. What are the different ways to create thread?
26. Explain Thread Dead locks?
27. Explain Thread life cycle?
28. What are thread pool? Give practical example where it is
implemented?

247
29. How to read and write into a text file?
30. What is JIT?
31. Why JAVA is platform independent?
32. What is break statement?
33. What is cloning?
34. Can constructor be inherited?
35. What is the difference between ArrayList and LinkedList?
36. What is type casting
37. Does construct return a value?
38. Can we run program without main method?
39. What are static blocks?
40. What is the difference between multiprocessing and
multithreading?
41. What are different types of data type present in java?
42. Does java support multiple inheritance? And why was that
not implemented in java?
43. What is iterator class?
44. Mentions basic interfaces in Collection frame work?
45. What is the internal implementation of hash map?
46. Give one example of where priority queue can be used?
47. What is the difference between list and set interface in
collection?
48. Why heap and stack memory are required in java?
49. What is the difference between exception and error in
java?
50. Give one practical example on how finally blocks are
useful?

248
51. What is the difference between string and string buffer
class?
52. What is the difference between string buffer and string
builder class?
53. What is the output for the following program1 –

53.1 public class UnaryOperators {

public static void main(String[] args) {

int i = 10;
int j = i++;
System.out.println(j);
System.out.println(i);
}

53.2 public class UnaryOperators {

public static void main(String[] args) {

249
int i = 10;
int j = i++ + ++i + i++ + i-- + --i + i++ ;
System.out.println(j);
System.out.println(i);
}

54. Write a code to print string in reverse order?


55. What is the difference between following string
comparison operators –
55.1 equals
55.2 ==
55.3 CompareTo

56. What are packages in java? Why do we require that?


57. What is singleton design?

250
Key Highlight
 Real time examples
 Simplified training approach
 Video Tutorial
 Hundreds of Examples
 Most commonly asked interview questions

251
In this complete video lecture series author Pankaj P Mutha will
show you everything you need to develop, compile and run java
programs. You will also find that the most complicated programs
are simplified and made clear so that students enjoy there
learning.

Testing Campus InfoTech Publications


Bangalore

252
253

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