Java Book
Java Book
Complete
Reference
Java
Complete Video Lecture Series
First Edition
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
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)
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.
11
Now run javac command in command prompt window to check
is path variable set properly.
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
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 {
}
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
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();
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
Example –
public class A {
Output – 10
27
within the object. Hence reference variable is required to access
that.
Example –
public class A {
}
}
Output -10
Example –
public class A {
28
public static void main(String[] args) {
int i=10;
System.out.println(i);
}
}
Output – 10
29
Note – String is a class.
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 {
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");
}
}
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 {
Example –
public class A {
A a = new A();
System.out.println(a.test());
}
35
{
return 20.3;
}
}
Example –
public class A {
A a1 = new A();
System.out.println(a1.test());
System.out.println(a1);
public A test()
{
A a2 = new A();
return a2;
}
}
1. Auto up casting
2. Explicit Down casting
Glass 1 Glass 2
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.
public class A {
short i=10;
int j=i;
System.out.println(j);
}
}
public class A {
38
public static void main(String[] args) {
long i=10;
int j=(int)i;
System.out.println(j);
}
}
public class A {
A a = new A();
System.out.println(a.test());
39
}
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 {
A a = new A();
System.out.println(a.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.
1. Class A
2. Class B
public class A {
class B extends A {
42
public static void main(String[] args) {
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
43
2. Select the page location where ad should be displayed
Example –
}
public void addEmailId(String emailId) {
44
PaidAds postAd = new PaidAds();
postAd.addDescription("Want to sell four wheeler");
postAd.addcontactNumber("9632629455");
postAd.addEmailId("[email protected]");
postAd.addManager("Smith");
postAd.addPageName("HomePage");
}
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.
1. Auto up casting
2. Explicit down casting
Eample –
public class A {
class B extends A {
46
public class A {
public void test2() {
System.out.println("Inside Test 2");
}
}
class B extends A{
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 –
49
class SecondClass extends FirstClass {
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.
System.out.println("checkBooks- unlimited/year");
}
51
}
public void netBanking() {
52
public void averageBalance() {
OutPut –
53
class SavingsAccountPlanTwo. To achieve this I am overriding
the methods rateOfInterest and averageBalance.
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 –
54
}
Output –
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
58
The output of ALU is always Boolean value true/false.
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
If (condition) {
Example 1 –
For the above program we will not get any output, because the
condition i>j will return false upon comparison.
Example 2 –
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.
if (i>j) {
System.out.println("i is greater");
} else {
System.out.println("j is greater");
}
}
}
Output – j is greater
62
Example –
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 {
63
int caseval=1;
switch (caseval) {
Output –
Inside Case One
Execution Completed
64
Loops – When you want to repeat certain statements repeatedly
then we use loops.
1. For
2. While
import java.util.Scanner;
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.
import java.util.Scanner;
}
}
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 –
Example 1 –
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 –
int i = 10;
int j = i++ + i++;
System.out.println(j); //22
System.out.println(i); //12
Output –
21
12
Example 3 –
int i = 10;
int j = i++ + i++ + i++;
71
System.out.println(j); //33
System.out.println(i); //13
Output –
33
13
Example 1 –
int i = 10;
int j = ++i;
System.out.println(j);
System.out.println(i);
}
}
72
Output –
11
11
Example 2 –
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.
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 –
int i = 10;
int j = i--;
System.out.println(j);
System.out.println(i);
}
}
Output –
10
9
Example 2 -
75
int i = 10;
int j = i-- + i-- - i--;
System.out.println(j);
System.out.println(i);
Output –
11
7
76
}
Output –
9
9
Example 2 –
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
int i = 10;
int j = --i - --i + --i + i-- + i--;
System.out.println(j);
System.out.println(i);
Output-
21
5
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.
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();
82
class manager {
Example – abstract
package com.testingcampus.example;
83
package com.testingcampus.example;
@Override
public void test1() {
System.out.println("Inside Test1");
@Override
public void test2() {
System.out.println("Inside Test2");
84
}
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.
System.out.println(age1);
System.out.println(age2);
System.out.println(age3);
System.out.println(age4);
Note- Variables can only store one value at a time and will store
the most recent value in it.
Example –
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
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
age[0]=27;
age[1]=25;
age[2]=29;
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 –
age[0]=27;
age[1]=25;
age[2]=29;
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.
age[0]=27;
age[1]=25;
age[2]=29;
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 –
Example 1 –
public ConstructorExamples() {
System.out.println("Inside the constructor");
}
Output –
Inside the constructor
96
Example 2-
public class ConstructorExamples {
Output –
My Name is: Pankaj
Example 3 – Constructor overloading
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);
}
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-
System.out.println(cm);
cm.test();
Example 2 –
100
System.out.println("Inside Test2");
}
public void test1() {
this.test2();
System.out.println("Inside Test1");
}
}
2. This cannot be used in static blocks.
this.test2();
System.out.println("Inside Test1");
}
101
public static void main(String[] args) {
this.test1();
Output –
3. If you don’t use this, then compiler will place this operator
automatically.
Example –
test2();
System.out.println("Inside Test1");
}
Output –
Inside Test2
Inside Test1
103
Example -1
public ConstructorExamples() {
104
Example 2 –
public ConstructorExamples() {
this("Pankaj");
System.out.println("Inside no argument Constructor");
}
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 {
107
}
Output –
Inside test method - parentClassTOConstructorExamples
Inside test – ConstructorExamples
Example –
class parentClassTOConstructorExamples {
public parentClassTOConstructorExamples() {
System.out.println("Inside Constructor -
parentClassTOConstructorExamples");
}
}
108
public ConstructorExamples() {
super();
System.out.println("Inside Constructor -
ConstructorExamples");
}
int i;
109
public static void main(String[] args) {
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 {
To import the class present inside the package we write the code
as shown below –
import com.testingcampus.example.A;
public class B {
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
Accessing Members
115
Different No No No Yes
Package
non-
subclass
116
Exception handling in java
117
What are Exception?
Both runtime and straight away exceptions are inherited from the
class Exception, And Exception class is inherited from the class
Throwable.
RUNTIME Exceptions
119
exception as it is mathematical expression and because of
exception none of the further lines of code will execute.
int j = 10;
int i = 0;
int k = j/i;
System.out.println("k");
System.out.println("Execution Compeleted");
120
public class ExceptionExamples {
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");
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 –
ExceptionExamples a=null;
a.test();
}
122
ExceptionExamples a = null;
try {
a.test();
}
catch (NullPointerException e) {
System.out.println("Object is not created for
the class ExceptionExamples");
}
123
Example –
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)
try {
int i = Integer.parseInt(str);
}
catch (NumberFormatException e) {
System.out.println("Invalid conversion");
System.out.println("Execution Completed");
Example –
125
public static void main(String[] args) {
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println("Execution Completed");
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
Example –
127
class A {
public void test() {
System.out.println("Inside Test");
}
}
class A {
public void test() {
System.out.println("Inside Test");
}
}
128
public class ExceptionExamples extends A{
try {
ExceptionExamples ex = (ExceptionExamples) new A();
ex.test();
}
catch (ClassCastException e){
System.out.println(e);
}
System.out.println("Execution Completed");
}
}
Example –
public class ExceptionExamples {
129
public static void main(String[] args) {
Class.forName("A");
System.out.println("Execution Completed");
}
}
at ExceptionExamples.main(ExceptionExamples.java:11)
130
public class ExceptionExamples {
try {
Class.forName("A");
System.out.println("class Loaded.....");
} catch (ClassNotFoundException e) {
}
}
Example –
class A {
131
public class ExceptionExamples {
try {
Class.forName("A");
System.out.println("class Loaded.....");
A.test();
} catch (ClassNotFoundException e) {
}
}
Output –
class Loaded.....
Inside Test
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.
Example – 1
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.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();
}
135
Please see the program written above to understand IO and
FileNotFound Exception. Please watch the video lectures to
understand this more clearly.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileHandling {
try {
file.write(data);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
136
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class ABC {
137
}
}
Example –
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
138
class ABC {
try {
file.write(b);
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
139
public class ThrowAndThrows {
public insufficientFunds() {
System.out.println("Low Balance!!!!");
}
140
}
try {
throw new insufficientFunds();
} catch (insufficientFunds e) {
e.printStackTrace();
}
}
Output –
Low Balance!!!!
insufficientFunds
at BankAccount.main(BankAccount.java:7)
141
whether exception are thrown are not we have to execute certain
statements. There is where we make use of finally block.
Example –
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 –
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
146
Purpose of thread is to write programs to achieve better multi-
tasking. There are two ways to create threads in java
package com.testingcampus.example;
147
for (int i=0;i<100;i++) {
System.out.println("Task 2 - "+i);
}
package com.testingcampus.example;
148
th.start();
}
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{
149
for (int i=0;i<100;i++) {
System.out.println(i);
}
}
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 {
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());
}
}
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 –
int balance;
public static void main(String[] args) {
@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();
}
154
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.
155
Example -
int balance;
public static void main(String[] args) {
@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();
}
157
public synchronized void sub() {
for (int i=0;i<10000;i++){
balance = balance-1;
}
Output – Balance:Rs.0
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 –
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() {
notify();
}
Output - Total:499500
160
Example - NotifyAll
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 {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+" Priority:
"+t.getPriority()+" is restarted to active");
}
162
}
163
public class C extends Thread{
S s3;
public C(S s3) {
this.s3 = s3;
}
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
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
Example –
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
165
public class Shared {
A a1 = new A(s1,s2);
166
B b1 = new B(s1,s2);
a1.start();
b1.start();
}
Shared s1,s2;
Shared s1,s2;
167
B(Shared s1, Shared s2) {
this.s1 = s1;
this.s2 = s2;
Output –
test1 begin
test2 begin
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
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
Example –
import java.util.ArrayList;
import java.util.Iterator;
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;
174
data.add("Campus");
data.add("Training");
data.add("Institute");
System.out.println(str);
Output –
Testing
Campus
Training
Institute
175
Example –
import java.util.ArrayList;
import java.util.Iterator;
Iterator it = data.iterator();
data.remove(1);
System.out.println(str);
176
}
Output –
Testing
Training
Institute
Example –
import java.util.Iterator;
import java.util.LinkedList;
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
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
import java.util.HashSet;
import java.util.Iterator;
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 –
Example –
import java.util.HashSet;
181
System.out.println(set);
}
}
Output –
[null, Smith, Pankaj, 10]
Example –
import java.util.LinkedHashSet;
182
set.add(10);
set.add(null);
set.add("Pankaj");
System.out.println(set);
}
}
Example –
import java.util.TreeSet;
183
set.add("Smith");
set.add("Adam");
set.add("Ram");
System.out.println(set);
}
}
Output –
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;
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-
import java.util.ArrayList;
import java.util.Collections;
list.add("Pankaj");
list.add("Adam");
list.add("Carl");
list.add("Patrick");
188
Collections.sort(list);
System.out.println(list);
}
}
Output –
import java.util.ArrayList;
import java.util.Collections;
list.add("Pankaj");
list.add("Adam");
list.add("Carl");
189
list.add("Patrick");
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 –
Example –
String S = "PANkaj";
System.out.println(S.toLowerCase());
System.out.println(S.toUpperCase());
192
}
Output –
pankaj
PANKAJ
Example –
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 –
String S = "Pankaj";
System.out.println(S.startsWith("Pa"));
System.out.println(S.endsWith("k"));
Output –
true
false
194
Example –
String S = "Pankaj";
System.out.println(S.charAt(2));
System.out.println(S.charAt(1));
n
a
Example –
public class StringExamples {
195
String S = "Pankaj";
System.out.println(S.length());
;
Output –
6
Example –
int a = 10;
String s = String.valueOf(a);
System.out.println(s);
196
}
Output –
10
Example –
197
private final String name ;
return age;
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.
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
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
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.
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
String s1 = "Pankaj";
String s2 = "Trainer";
System.out.println(s1.concat(s2));
Output –
203
PankajTrainer
9. substring –
Example –
public class StringExamples {
Output –
Pankaj
Rainers
204
2. public String substring(int startIndex,int endIndex):
Example –
205
String s2 = new String("Pankaj ");
s2.concat("Trainer");
System.out.println(s2);
}
}
Output –
Hello Java
Pankaj
206
}
Output –
HJavaello
Example –
}
}
Output –
207
HJava
Example –
Output –
Ho
Example –
208
public class ExampleStringBuffer {
}
}
Output –
olleH
StringBuilder –
Example -
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.
Example –
@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
214
Example –
int i ;
public void test1() {
System.out.println("Inside Test1");
}
e1.test1();
e2.test2();
Output –
Inside Test1
215
Inside Test2
216
Hash Code
Example –
217
public class ExampleHashCode {
System.out.println("e1 "+e1.hashCode());
System.out.println("e2 "+e2.hashCode());
Output –
e1 1432605192
e2 208811780
218
Annotations
219
how it works and why it is used. Let me answer these questions
first so that you will get more clarity about annotations.
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
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;
}
}
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");
}
}
223
Web Application Development
224
Web site is static in nature. Here we do not do any data
manipulations.
225
Servlets
227
If servers tab is not available then go to Window >> Show view
>> others >> servers
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.
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 –
Going forward you can use the following URL in the browser to
access the servlet –
http://localhost:8080/Servlets/FirstServlet
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.
response.setContentType("text/html")
PrintWriter out = response.getWriter();
out.println("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
http://localhost:8080/SimpleServletProject/xmlservletpath?user
Name=Pankaj&userId=xyz
236
POST -
Right click on web content folder and create a html file and call
that as simpleform.html
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>
238
out.println("Hello from POST method "+ userName + "!" +
fullName);
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.
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.
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
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.
245
Top Interview questions in java
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?
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 –
int i = 10;
int j = i++;
System.out.println(j);
System.out.println(i);
}
249
int i = 10;
int j = i++ + ++i + i++ + i-- + --i + i++ ;
System.out.println(j);
System.out.println(i);
}
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.
252
253