0% found this document useful (0 votes)
3 views126 pages

OOPs Using Java

The document provides a comprehensive overview of Object-Oriented Programming (OOP) using Java, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also introduces Java language constructs, including variables, data types, operators, and exception handling, along with the use of the Eclipse IDE for development. Additionally, it explains the principles of OOP and compares procedural programming with object-oriented programming.

Uploaded by

harishthube4477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views126 pages

OOPs Using Java

The document provides a comprehensive overview of Object-Oriented Programming (OOP) using Java, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also introduces Java language constructs, including variables, data types, operators, and exception handling, along with the use of the Eclipse IDE for development. Additionally, it explains the principles of OOP and compares procedural programming with object-oriented programming.

Uploaded by

harishthube4477
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 126

OBJECT ORIENTED PROGRAMMING USING JAVA

1. Introduction and Features


Fundamentals of object oriented programming – procedure oriented programming Vs. object
oriented programming (OOP), Object oriented programming concepts – Classes, object, object
reference, abstraction, encapsulation, inheritance, polymorphism, Introduction of eclipse (IDE)
for developing programs in Java

2. Language Constructs
variables, types and type declarations, data types : Integer, floating point type, character,
Boolean , all Operators, iteration and jump statement, if then else clause; conditional
expressions, input using scanner class and output statement, loops, switch case, arrays,
methods.

3. Classes and Objects


Class fundamentals, constructors, declaring objects (Object & Object Reference), creating and
accessing variables and methods, static and non static variables/methods defining packages,
Creating and accessing a package, Importing packages, Understanding CLASSPATH, auto boxing ,
String , String Buffer

4. Inheritance
Definition of inheritance, protected data, private data, public data, constructor chaining, order
of invocation, types of inheritance, single inheritance, multilevel inheritance, hierarchical
inheritance, hybrid inheritance , access control (Private Vs PublicVs Protected Vs Default)

5. Abstract Class and Interface


Defining an interface, difference between classes and interface, Key points of Abstract class &
interface, difference between an abstract class & interface, implementation of multiple
inheritance through interface.

6. Polymorphism
Method and constructor overloading, method overriding, up-casting and downcasting.
7. Exception Handling
Definition of exception handling, implementation of keywords like try, catches, finally, throw&
throws, built in exceptions, creating own exception sub classes importance of exception
handling in practical implementation of live projects

8. Multithreading
Difference between multi threading and multi tasking, thread life cycle, creating threads, thread
priorities, synchronizing threads.

Chapter 1 :Introduction and Features


Fundamentals of Object Oriented Programming

Object-oriented programming is a programming paradigm where everything is represented as


an object.

Objects pass messages to each other. Each object decides what to do with a received message.
OOP focuses on each object’s states and behaviours.

What are Objects?


An object is an entity that has states and behaviours.
For example, dog, cat, and vehicle. To illustrate, a dog has states like age, colour, name, and
behaviours like eating, sleeping, and running.

What are Classes?


A class is a template or blueprint from which objects are created.

Principles of Object-Oriented Programming


These are the four main principles of the object-oriented programming paradigm.
Understanding them is essential to becoming a successful programmer.

1. Encapsulation

2. Inheritance

3. Abstraction

4. Polymorphism

Procedure oriented programming


Procedure oriented programming is a set of functions. In this program Clanguage is used. To
perform any particular task, set of function are compulsory. For example , a program may
involve collecting data from user, performing some kind of calculation on that data and printing
the data on screen when is requested. Calculating, reading or printing can be written in a
program with the help of different functions on different tasks.POP method also emphases the
functions or the subroutines.
Procedural Oriented Programming Object Oriented Programming

In procedural programming, program is In object oriented programming, program


divided into small parts called functions. is divided into small parts called objects.

Procedural programming follows top down Object oriented programming


approach. follows bottom up approach.

Object oriented programming have access


There is no access specifier in procedural specifiers like private, public, protected
programming. etc.

Adding new data and function is not easy. Adding new data and function is easy.

Procedural programming does not have any


proper way for hiding data so it is less Object oriented programming provides
secure. data hiding so it is more secure.
Procedural Oriented Programming Object Oriented Programming

In procedural programming, overloading is Overloading is possible in object oriented


not possible. programming.

In procedural programming, function is more In object oriented programming, data is


important than data. more important than function.

Procedural programming is based on unreal Object oriented programming is based


world. on real world.

Classes in Java : Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car has attributes, such
as weight and colour, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Main.java

Create a class named "Main" with a variable x:

publicclassMain{

int x =5;

Object in Java :It is a basic unit of Object-Oriented Programming and represents the real life entities.
A typical Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :

1. State: It is represented by attributes of an object. It also reflects the properties of an


object.
2. Behaviour: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object: dog

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behaviou8r of the class. But the values of those attributes, i.e. the state are unique
for each object. A single class may have any number of instances.
Example:

difference between object and reference


When you create an object of a class as −

Student obj = new Student();

The objects are created in the heap area and, the reference obj just points out to the object of the
Student class in the heap, i.e. it just holds the memory address of the object (in the heap).
And since the String is also an object, under name, a reference points out to the actual String value
(“Krishna”).

In short, object is an instance of a class and reference (variable) points out to the object created in the
heap area.

Abstraction
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather
than its individual components.

In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction
using interfaces.

Abstract classes and Abstract methods :

1. An abstract class is a class that is declared with abstract keyword.


2. An abstract method is a method that is declared without an implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
4. A method defined abstract must always be redefined in the subclass, thus
making overriding compulsory OR either make subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with abstract
keyword.
6. There can be no object of an abstract class.That is, an abstract class can not be directly
instantiated with the new operator.
7. An abstract class can have parametrized constructors and default constructor is always
present in an abstract class.
Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class. Therefore, it is also
known as data hiding.
To achieve encapsulation in Java −
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.

Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
Java Inheritance Example

Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

Eclipse
Eclipse is an IDE tool that helps us to develop software. According to the Wikipedia definition,
an integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. You can also
write code in a text editor and compile and execute from command line; but compared to a text
editor, eclipse provides many additional useful features to make the development of software
easier and faster. IDE normally consists of a source code editor, build automation tools and a
debugger. Most modern IDEs like eclipse also offer intelligent code completion features.

Eclipse is mostly used to develop applications in Java, but by means of various plug-ins, Eclipse
may also be used to develop applications in other programming languages like Ada, C, C++,
COBOL, Fortran, Haskell, JavaScript, Lasso, Perl, PHP, Python, R, Ruby (including Ruby on Rails
framework), Scala, Clojure, Groovy, Scheme, and Erlang.

Most of us use eclipse just to create or edit java code, but eclipse has lot more features than just
creating or editing code, for instance, debugging, code repository integration etc. Eclipse also provides
many shortcuts to make the software development faster. The more you know about eclipse, its
features, its shortcuts etc., we can develop software much faster than otherwise, and thus increase our
productivity.
Chapter 2 :Language And Constructs

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 boolean - stores values with two states: true or false

Syntax
type variable = value;

Example
Create a variable called name of type String and assign it the value "John":

String name ="John";

System.out.println(name);

Operators in Java

Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift <<>>>>>

Relational comparison <><= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive ^
OR

bitwise inclusive |
OR

Logical logical AND &&


logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10
Java Unary Operator Example 2: ++ and --
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21
Java Unary Operator Example: ~ and !
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Output:

-11
9
false
true
Java Arithmetic Operators

Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}

Output:

15
5
50
2
0
Java Arithmetic Operator Example: Expression
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}
}

Output:

21
Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example


class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}

Output:

40
80
80
240
Java Right Shift Operator

The Java right shift operator >> is used to move left operands value to right by the number of
bits specified by the right operand.

Java Right Shift Operator Example


class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}

Output:

2
5
2
Java Shift Operator Example: >> vs >>>
class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}

Output:

5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check second condition if first condition is false. It checks
second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}

Output:

false
false
Java AND Operator Example: Logical && vs Bitwise &
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}

Output:

false
10
false
11
Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Output:

true
true
true
10
true
11
Java Ternary Operator

Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot
in Java programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example


class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

Output:

Another Example:

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

Output:

5
Java Assignment Operator

Java assignment operator is one of the most common operator. It is used to assign the value on
its right to the operand on its left.
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:

14
16
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}

Output:

13
9
18
9
Java Assignment Operator Example: Adding short
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:

Compile time error

After type cast:

1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Output:

20

Java Iterator

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
It is called an "iterator" because "iterating" is the technical term for looping.To use an Iterator,
you must import it from the java.util package.

The iterator() method can be used to get an Iterator for any collection:

Example

// Import the ArrayList class and the Iterator class

importjava.util.ArrayList;
importjava.util.Iterator;

publicclassMain{

publicstaticvoidmain(String[]args){

// Make a collection

ArrayList<String> cars =newArrayList<String>();

cars.add("Volvo");

cars.add("BMW");

cars.add("Ford");

cars.add("Mazda");

// Get the iterator

Iterator<String> it =cars.iterator();

// Print the first item

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

Jump:
jump: Java supports three jump statement: break, continue and return. These three
statements transfer control to other part of the program.
1. Break: In Java, break is majorly used for:
 Terminate a sequence in a switch statement (discussed above).
 To exit a loop.
 Used as a “civilized” form of goto.
Using break to exit a Loop
Using break, we can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the
innermost loop.

Example:

// Java program to illustrate using

// break to exit a loop

classBreakLoopDemo

{
publicstaticvoidmain(String args[])

// Initially loop is set to run from 0-9

for(inti = 0; i< 10; i++)

// terminate loop when i is 5.

if(i == 5)

break;

System.out.println("i: "+ i);

System.out.println("Loop complete.");

Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Using break as a Form of Goto
Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. Java uses label. A Label is use to identifies a
block of code.
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, break statement can be use to jump out of target block.
Note: You cannot break to any label which is not defined for an enclosing block.
Syntax:
break label;
Example:

// Java program to illustrate using break with goto

classBreakLabelDemo

publicstaticvoidmain(String args[])

booleant = true;
// label first

first:

// Illegal statement here as label second is not

// introduced yet break second;

second:

third:

// Before break

System.out.println("Before the break statement");

// break will take the control out of

// second label

if(t)

breaksecond;
System.out.println("This won't execute.");

System.out.println("This won't execute.");

// First block

System.out.println("This is after second block.");

Output:
Before the break.
This is after second block.
2. Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the
code in its body for this particular iteration. This is, in effect, a goto just past the
body of the loop, to the loop’s end. The continue statement performs such an
action.
Example:

// Java program to illustrate using

// continue in an if statement

classContinueDemo

publicstaticvoidmain(String args[])

for(inti = 0; i< 10; i++)

{
// If the number is even

// skip and continue

if(i%2== 0)

continue;

// If number is odd, print it

System.out.print(i + " ");

3. Output:
4.1 3 5 7 9
5. Return:The return statement is used to explicitly return from a method. That is, it
causes a program control to transfer back to the caller of the method.
Example:

// Java program to illustrate using return

classReturn

publicstaticvoidmain(String args[])
{

booleant = true;

System.out.println("Before the return.");

if(t)

return;

// Compiler will bypass every statement

// after return

System.out.println("This won't execute.");

6. Output:
7.Before the return.

Java Conditions and If Statements

Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if(condition){

// block of code to be executed if the condition is true

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if(condition){

// block of code to be executed if the condition is true

}else{

// block of code to be executed if the condition is false

}
Example

int time =20;

if(time <18){

System.out.println("Good day.");

}else{

System.out.println("Good evening.");

// Outputs "Good evening."

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if(condition1){

// block of code to be executed if condition1 is true

}elseif(condition2){

// block of code to be executed if the condition1 is false and condition2 is true

}else{

// block of code to be executed if the condition1 is false and condition2 is false

Example

int time =22;

if(time <10){

System.out.println("Good morning.");

}elseif(time <20){
System.out.println("Good day.");

}else{

System.out.println("Good evening.");

// Outputs "Good evening."

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often
used to replace simple if else statements:

Syntax

variable=(condition)?expressionTrue:expressionFalse;

Instead of writing:

Example

int time =20;

if(time <18){

System.out.println("Good day.");

}else{

System.out.println("Good evening.");

}
Java Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax

switch(expression){

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

Example

int day =4;

switch(day){

case1:

System.out.println("Monday");

break;
case2:

System.out.println("Tuesday");

break;

case3:

System.out.println("Wednesday");

break;

case4:

System.out.println("Thursday");

break;

case5:

System.out.println("Friday");

break;

case6:

System.out.println("Saturday");

break;

case7:

System.out.println("Sunday");

break;

// Outputs "Thursday" (day 4)

Try it Yourself »

The break Keyword

When Java reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more
testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.

The default Keyword

The default keyword specifies some code to run if there is no case match:

Example

int day =4;

switch(day){

case6:

System.out.println("Today is Saturday");

break;

case7:

System.out.println("Today is Sunday");

break;

default:

System.out.println("Looking forward to the Weekend");

// Outputs "Looking forward to the Weekend"


Java Scanner

Scanner class in Java is found in the java.util package. Java provides various ways to read input
from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular
expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long, double, byte, float, short, etc .
The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(),
nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get
a single character from the scanner, you can call next().charAt(0) method which returns a single
character.

Example 1

Let's see a simple example of Java Scanner where we are getting a single input from the user.
Here, we are asking for a string through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }
Example 2
1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){
4. String s = "Hello, This is JavaTpoint.";
5. //Create scanner Object and pass string in it
6. Scanner scan = new Scanner(s);
7. //Check if the scanner has a token
8. System.out.println("Boolean Result: " + scan.hasNext());
9. //Print the string
10. System.out.println("String: " +scan.nextLine());
11. scan.close();
12. System.out.println("--------Enter Your Details-------- ");
13. Scanner in = new Scanner(System.in);
14. System.out.print("Enter your name: ");
15. String name = in.next();
16. System.out.println("Name: " + name);
17. System.out.print("Enter your age: ");
18. int i = in.nextInt();
19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
21. double d = in.nextDouble();
22. System.out.println("Salary: " + d);
23. in.close();
24. }
25. }
Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation


2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}

10. Output:

11. 33
12. 3
13. 4
14. 5

Array Length

To find out how many elements an array has, use the length property:

Example

String[] cars ={"Volvo","BMW","Ford","Mazda"};

System.out.println(cars.length);

// Outputs 4

Arrays class in Java


 Difficulty Level : Easy
 Last Updated : 24 Apr, 2019
The Arrays class in java.util package is a part of the Java Collection Framework. This class
provides static methods to dynamically create and access Java arrays. It consists of only static
methods and the methods of Object class. The methods of this class can be used by the class
name itself.
 Fill an array with a particular value.
 Sort an Arrays.
 Search in an Arrays.
 And many more.
Arrays class provides several static methods that can be used to perform these tasks directly
without the use of loops.
1. compareUnsigned(array 1, array 2): This method compares two arrays
lexicographically, numerically treating elements as unsigned.

// Java program to demonstrate

// Arrays.compareUnsigned() method

importjava.util.Arrays;

publicclassMain {

publicstaticvoidmain(String[] args)

// Get the Arrays

intintArr[] = { 10, 20, 15, 22, 35};

// Get the second Arrays

intintArr1[] = { 10, 15, 22};

// To compare both arrays


System.out.println("Integer Arrays on comparison: "

+ Arrays.compareUnsigned(intArr, intArr1));

2. Output:
3.
4.

5.Integer Arrays on comparison: 1


6. copyOf(originalArray, newLength) : This method copies the specified array,
truncating or padding with the default value (if necessary) so the copy has the
specified length.

// Java program to demonstrate

// Arrays.copyOf() method

importjava.util.Arrays;

publicclassMain {

publicstaticvoidmain(String[] args)

{
// Get the Array

intintArr[] = { 10, 20, 15, 22, 35};

// To print the elements in one line

System.out.println("Integer Array: "

+ Arrays.toString(intArr));

System.out.println("\nNew Arrays by copyOf:\n");

System.out.println("Integer Array: "

+ Arrays.toString(

Arrays.copyOf(intArr, 10)));

7. Output:
8.Integer Array: [10, 20, 15, 22, 35]
9.
10. New Arrays by copyOf:
11.
12. Integer Array: [10, 20, 15, 22, 35, 0, 0, 0, 0, 0]

Loops in Java

In programming languages, loops are used to execute a set of instructions/functions repeatedly


when some conditions become true. There are three types of loops in Java.

o for loop
o while loop
o do-while loop

Java For Loop vs While Loop vs Do While Loop

Comparison for loop while loop do while loop

Introduction The Java for loop is a control The Java while loop is The Java do while
flow statement that iterates a control flow loop is a control flow
a part of statement that statement that
the programs multiple executes a part of executes a part of the
times. the programs programs at least
repeatedly on the once and the further
basis of given execution depends
boolean condition. upon the given
boolean condition.

When to If the number of iteration is If the number of If the number of


use fixed, it is recommended to iteration is not fixed, iteration is not fixed
use for loop. it is recommended to and you must have to
use while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.

Syntax for(init;condition;incr/decr){ while(condition){ do{


// code to be executed //code to be //code to be
} executed executed
} }while(condition);

Example //for loop //while loop //do-while loop


for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);

Syntax for for(;;){ while(true){ do{


infinitive //code to be executed //code to be //code to be
loop } executed executed
} }while(true);
1. while loop: A while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax :
2.while (boolean condition)
3.{
4. loop statements...
5.}
Flowchart:

 While loop starts with the checking of condition. If it evaluated to true,


then the loop body statements are executed otherwise first statement
following the loop is executed. For this reason it is also called Entry
control loop
 Once the condition is evaluated to true, the statements in the loop body
are executed. Normally the statements contain an update value for the
variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks
the end of its life cycle.

// Java program to illustrate while loop

classwhileLoopDemo
{

publicstaticvoidmain(String args[])

intx = 1;

// Exit when x becomes greater than 4

while(x <= 4)

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

// Increment the value of x for

// next iteration

x++;

Output:
Value of x:1
Value of x:2
Value of x:3
Value of x:4
6. for loop: for loop provides a concise way of writing the loop structure. Unlike a
while loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}
Flowchart:

1. Initialization condition: Here, we initialize the variable in use. It marks


the start of a for loop. An already declared variable can be used or a
variable can be declared, local to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It
must return a boolean value. It is also an Entry Control Loop as the
condition is checked prior to the execution of the loop statements.
3. Statement execution: Once the condition is evaluated to true, the
statements in the loop body are executed.
4. Increment/ Decrement: It is used for updating the variable for next
iteration.
5. Loop termination:When the condition becomes false, the loop
terminates marking the end of its life cycle.

// Java program to illustrate for loop.

classforLoopDemo

publicstaticvoidmain(String args[])

// for loop begins when x=2

// and runs till x <=4

for(intx = 2; x <= 4; x++)

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

Output:
Value of x:2
Value of x:3
Value of x:4
Enhanced For loop
Java also includes another version of for loop introduced in Java 5. Enhanced for
loop provides a simpler way to iterate through the elements of a collection or
array. It is inflexible and should be used only when there is a need to iterate
through the elements in sequential manner without knowing the index of currently
processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e
it ensures that the values in the array can not be modified, so it can be said as read
only loop where you can’t update the values as opposite to other loops where
values can be modified.
We recommend using this form of the for statement instead of the general form
whenever possible.(as per JAVA doc.)
Syntax:
for (T element:Collectionobj/array)
{
statement(s)
}
Lets take an example to demonstrate how enhanced for loop can be used to
simpify the work. Suppose there is an array of names and we want to print all the
names in that array. Let’s see the difference with these two examples
Enhanced for loop simplifies the work as follows-

// Java program to illustrate enhanced for loop

publicclassenhancedforloop

publicstaticvoidmain(String args[])

String array[] = {"Ron", "Harry", "Hermoine"};

//enhanced for loop

for(String x:array)
{

System.out.println(x);

/* for loop for same function

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

System.out.println(array[i]);

*/

Output:
Ron
Harry
Hermoine
do while: do while loop is similar to while loop with only difference that it checks
for condition after executing the statements, and therefore is an example of Exit
Control Loop.
Syntax:
do
{
statements..
}
while (condition);
Flowchart:

1. do while loop starts with the execution of the statement(s). There is no


checking of any condition for the first time.
2. After the execution of the statements, and update of the variable value,
the condition is checked for true or false value. If it is evaluated to true,
next iteration of loop starts.
3. When the condition becomes false, the loop terminates which marks
the end of its life cycle.
4. It is important to note that the do-while loop will execute its statements
atleast once before any condition is checked, and therefore is an
example of exit control loop.

// Java program to illustrate do-while loop

classdowhileloopDemo
{

publicstaticvoidmain(String args[])

intx = 21;

do

// The line will be printed even

// if the condition is false

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

x++;

while(x < 20);

Output:
Value of x: 21
Chapter 3- Classes and Objects
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java
supports the following fundamental concepts −

 Polymorphism
 Inheritance
 Encapsulation
 Abstraction
 Classes
 Objects
 Instance
 Method
 Message Passing
In this chapter, we will look into the concepts - Classes and Objects.
 Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance
of a class.
 Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type support.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
publicclassDog{
String breed;
int age;
Stringcolor;

voidbarking(){
}
voidhungry(){
}

voidsleeping(){
}
}
A class can contain any of the following variable types.
 Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
 Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In
the above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into
classes of the Java Language.
Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
Following is an example of a constructor −
Example
publicclassPuppy{
publicPuppy(){
}

publicPuppy(String name){
// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instance of a
class.
Note − We have two different types of constructors. We are going to discuss constructors in
detail in the subsequent chapters.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
 Declaration − A variable declaration with a variable name with an object type.
 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Following is an example of creating an object −
Example
publicclassPuppy{
publicPuppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :"+ name );
}

publicstaticvoidmain(String[]args){
// Following statement would create an object myPuppy
PuppymyPuppy=newPuppy("tommy");
}
}
If we compile and run the above program, then it will produce the following result −
Output
Passed Name is :tommy

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();

Example
This example explains how to access instance variables and methods of a class.

publicclassPuppy{
intpuppyAge;

publicPuppy(String name){
// This constructor has one parameter, name.
System.out.println("Name chosen is :"+ name );
}

publicvoidsetAge(int age ){
puppyAge= age;
}

publicintgetAge(){
System.out.println("Puppy's age is :"+puppyAge);
returnpuppyAge;
}

publicstaticvoidmain(String[]args){
/* Object creation */
PuppymyPuppy=newPuppy("tommy");

/* Call class method to set puppy's age */


myPuppy.setAge(2);

/* Call another class method to get puppy's age */


myPuppy.getAge();

/* You can access instance variable as follows as well */


System.out.println("Variable Value :"+myPuppy.puppyAge);
}
}
If we compile and run the above program, then it will produce the following result −
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
What is Static Method in Java?

Static method in Java is a method which belongs to the class and not to the object. A static
method can access only static data. It is a method which belongs to the class and not to the
object(instance). A static method can access only static data. It cannot access non-static data
(instance variables).

 A static method can call only other static methods and can not call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any object
 A static method cannot refer to "this" or "super" keywords in anyway

Syntax :

<class-name>.<method-name>

Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.

Lets learn the nuances of the static keywords by doing some excercises!

Example: How to call static variables & methods

publicclassDemo{
publicstaticvoidmain(Stringargs[]){
Students1=newStudent();
s1.showData();
Students2=newStudent();
s2.showData();
//Student.b++;
//s1.showData();
}
}

classStudent {
inta; //initialized to zero
staticintb; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}

publicvoidshowData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}

}
This code is editable. Click Run to Compile + Execute

Run

Step 2) Save & Compile the code. Run the code as, java Demo.

Step 3) Expected output show below

Following diagram shows, how reference variables & objects are created and static variables
are accessed by the different instances.
Step 4) It is possible to access a static variable from outside the class using the
syntax ClassName.Variable_Name. Uncomment line # 7 &8 .Save , Compile & Run . Observe
the output.

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
Step 5) Uncomment line 25,26 &27 .Save , Compile & Run.

error: non-static variable a cannot be referenced from a static context a++;

Step 6) Error = ? This is because it is not possible to access instance variable "a" from java static
class method "increment".

What is Static Block in Java?

The static block is a block of statement inside a Java class that will be executed when a class is
first loaded into the JVM. A static block helps to initialize the static data members, just like
constructors help to initialize instance members.

class Test{
static {
//Code goes here
}
}

Following program is the example of java static block.

publicclassDemo {
staticinta;
staticintb;
static {
a=10;
b=20;
}
publicstaticvoidmain(Stringargs[]) {

System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);

}
This code is editable. Click Run to Compile + Execute

Run

you will get following output of the program.

Value of a = 10
Value of b = 20

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
Next →← Prev

Java Package
1. Java Package

2. Example of package

3. Accessing package

1. By import packagename.*

2. By import packagename.classname

3. By fully qualified name

4. Subpackage

5. Sending class file to another directory

6. -classpath switch

7. 4 ways to load the class file or jar file

8. How to put two public class in a package

9. Static Import

10. Package class

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in
etc. If you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the cur

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;

3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
Classpath
Classpath is a parameter in the Java Virtual Machine or the Java compiler that specifies the
location of user-defined classes and packages. The parameter may be set either on
the command-line, or through an environment variable.

The third-party applications (MySQL and Oracle) that use the JVM can modify the CLASSPATH
environment variable to include the libraries they use. The classes can be stored in directories or
archives files. The classes of the Java platform are stored in rt.jar.

There are two ways to ways to set CLASSPATH: through Command Prompt or by setting Environment
Variable.

Let's see how to set CLASSPATH of MySQL database:

Step 1: Click on the Windows button and choose Control Panel. Select System.

Step 2: Click on Advanced System Settings.

Step 3: A dialog box will open. Click on Environment Variables.


Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a
semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable
name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector Java.jar;.;

Remember: Put ;.; at the end of the CLASSPATH.

Difference between PATH and CLASSPATH

PATH CLASSPATH

PATH is an environment variable. CLASSPATH is also an environment variable.

It is used by the operating system It is used by Application ClassLoader to locate the .class file.
to find the executable files (.exe).

You are required to include the You are required to include all the directories which
directory which contains .exe contain .class and JAR files.
files.

PATH environment variable once The CLASSPATH environment variable can be overridden by
set, cannot be overridden. using the command line option -cp or -CLASSPATH to both
javac and java command.

Autoboxing and Unboxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive
types and their corresponding object wrapper classes. For example, converting an int to
an Integer, a double to a Double, and so on. If the conversion goes the other way, this is
called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';

The rest of the examples in this section use generics. If you are not yet familiar with the syntax
of generics, see the Generics (Updated) lesson.

Consider the following code:

List<Integer> li = new ArrayList<>();


for (int i = 1; i< 50; i += 2)
li.add(i);

Although you add the int values as primitive types, rather than Integer objects, to li, the code
compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the
Java compiler does not issue a compile-time error. The compiler does not generate an error
because it creates an Integer object from i and adds the object to li. Thus, the compiler converts
the previous code to the following at runtime:

List<Integer> li = new ArrayList<>();


for (int i = 1; i< 50; i += 2)
li.add(Integer.valueOf(i));

Converting a primitive value (an int, for example) into an object of the corresponding wrapper
class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive
value is:

 Passed as a parameter to a method that expects an object of the corresponding


wrapper class.
 Assigned to a variable of the corresponding wrapper class.
Java String

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Java StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
Important methods of StringBuffer class
Modifier and Method Description
Type

public append(String s) is used to append the specified string with this


synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, String is used to insert the specified string with this string
synchronized s) at the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float),
insert(int, double) etc.

public replace(int startIndex, is used to replace the string from specified


synchronized int endIndex, String str) startIndex and endIndex.
StringBuffer

public delete(int startIndex, is used to delete the string from specified


synchronized int endIndex) startIndex and endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.

public char charAt(int index) is used to return the character at the specified
position.

public int length() is used to return the length of the string i.e. total
number of characters.

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int beginIndex, is used to return the substring from the specified
int endIndex) beginIndex and endIndex.

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.

1) StringBufferappend() method

The append() method concatenates the given argument with this string.

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
2) StringBufferinsert() method

The insert() method inserts the given string with this string at the given position.
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBufferreplace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
4) StringBufferdelete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.

1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Chapter 4- Inheritance
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Java Inheritance Example

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Java - Access Modifiers


Java provides a number of access modifiers to set access levels for classes, variables, methods,
and constructors. The four access levels are −

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).
Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
Example
Variables and methods can be declared without any modifiers, as in the following examples −

String version ="1.5.1";

booleanprocessOrder(){
returntrue;
}
Private Access Modifier - Private
Methods, variables, and constructors that are declared private can only be accessed within the
declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class, if public getter methods
are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.
Example
The following class uses private access control −

publicclassLogger{
privateString format;

publicStringgetFormat(){
returnthis.format;
}

publicvoidsetFormat(String format){
this.format= format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String), which sets its
value.
Public Access Modifier - Public
A class, method, constructor, interface, etc. declared public can be accessed from any other
class. Therefore, fields, methods, blocks declared inside a public class can be accessed from
any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the public
class still needs to be imported. Because of class inheritance, all public methods and variables
of a class are inherited by its subclasses.
Example
The following function uses public access control −

publicstaticvoidmain(String[] arguments){
// ...
}

Constructor chaining
Constructor chaining is the process of calling one constructor from another constructor with
respect to current object.
Constructor chaining can be done in two ways:
 Within same class: It can be done using this() keyword for constructors in same
class
 From base class: by using super() keyword to call constructor from the base class.

 Why do we need constructor chaining ?


This process is used when we want to perform multiple tasks in a single constructor
rather than creating a code for each task in a single constructor we create a separate
constructor for each task and make their chain which makes the program more
readable.
 Constructor Chaining within same class using this() keyword :

// Java program to illustrate Constructor Chaining

// within same class Using this() keyword

class Temp

// default constructor 1

// default constructor will call another constructor


// using this keyword from same class

Temp()

// calls constructor 2

this(5);

System.out.println("The Default constructor");

// parameterized constructor 2

Temp(int x)

// calls constructor 3

this(5, 15);

System.out.println(x);

// parameterized constructor 3

Temp(int x, int y)
{

System.out.println(x * y);

public static void main(String args[])

// invokes default constructor first

new Temp();

Output:
75
5
The Default constructor
Rules of constructor chaining :
1. The this() expression should always be the first line of the constructor.
2. There should be at-least be one constructor without the this() keyword
(constructor 3 in above example).
3. Constructor chaining can be achieved in any order.

Order Of Invocation :

Order of execution of constructors in inheritance relationship is from base /parent class to


derived / child class.

We know that when we create an object of a class then the constructors get called
automatically.
Cases-1: Constructor call order in single inheritance java

If we create an object of the child class in the program, then, the body of constructor of parent
class will execute first, then body of child class will be executed. In simple word, we can say that
the parent constructor get called first, then of the child class.

Have a look at this constructor call orders image give below.

In the picture, there are parent and child class with main program. And with “new child() ”
statement the constructor has been invoked. How the controls flows in the program for parent
child constructors calls is shown by arrow diagram.

Here are the steps how the program control flows in the image.

1. You create an object of child class in main() as “new Child()”


2. Control goes to child constructor, but, its body is not getting executed.
3. Control goes to parent constructor, body of it get executed.
4. Then, control comes back to child constructor and body get executed.
5. Then, the controls come back to “new Child()” statement and exit.

order of execution of constructors in Java


inheritance
Java code example
class Parent {

Parent(){

System.out.println("Parent()...");

class Child extends Parent {

Child(){

System.out.println("Child()...");

public class TestConstructorCallOrder {


public static void main(String[] args) {

//Create object of Child class object

System.out.println("Constructor call order...");

new Child();

OUTPUT:
Constructor call order…
Parent()…
Child()…

Cases-2: Constructor call order in Multilevel inheritance

If we create object of bottom most derived class i.e. of Testing class in main() program, then
constructors of Design class, Coding class and then Testing class will be called.

Java code example


class Design {

Design(){

System.out.println("Design()...");

}
}

class Coding extends Design {

Coding(){

System.out.println("coding()...");

class Testing extends Coding {

Testing()

System.out.println("Testing()...");

public class TestConstructorCallOrder {


public static void main(String[] args) {

//Create object of bottom most class object

System.out.println("Constructor call order...");

new Testing();

OUTPUT:
Constructor call order…
Design()…
coding()…
Testing()…

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

You must have seen public, private and protected keywords while practising java programs,
these are called access modifiers. An access modifier restricts the access of a class, constructor,
data member and method in another class. In java we have four access modifiers:
1. default
2. private
3. protected
4. public

Difference Between Public and Private Access Specifier in Java

The major difference between public and private modifiers is its visibility. Java categories the
visibility for class members as follows:

o Subclasses in the same package


o Non-subclasses in the same package
o Subclasses in different packages
o Classes neither in the same package nor subclasses

Private access modifier

The scope of private modifier is limited to the class only.


1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class
from outside of the class.

Let’s see an example to understand this:

Private access modifier example in java

This example throws compilation error because we are trying to access the private data
member and method of class ABC in the class Example. The private data member and method
are only accessible within the class.

classABC{
privatedoublenum=100;
privateintsquare(int a){
return a*a;
}
}
publicclassExample{
publicstaticvoidmain(Stringargs[]){
ABC obj=newABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:

Compile- time error

Protected Access Modifier

Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is
similar to default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.
Protected access modifier example in Java

In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class
extends class Addition and the protected modifier allows the access of protected members in
subclasses (in any packages).
Addition.java

packageabcpackage;
publicclassAddition{

protectedintaddTwoNumbers(int a,int b){


returna+b;
}
}
Test.java

packagexyzpackage;
importabcpackage.*;
classTestextendsAddition{
publicstaticvoidmain(Stringargs[]){
Testobj=newTest();
System.out.println(obj.addTwoNumbers(11,22));
}
}
Output:

33

Public access modifier

The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.

public access modifier example in java

Lets take the same example that we have seen above but this time the method
addTwoNumbers() has public modifier and class Test is able to access this method without even
extending the Addition class. This is because public modifier has visibility everywhere.
Addition.java
packageabcpackage;

publicclassAddition{

publicintaddTwoNumbers(int a,int b){


returna+b;
}
}
Test.java

packagexyzpackage;
importabcpackage.*;
classTest{
publicstaticvoidmain(Stringargs[]){
Additionobj=newAddition();
System.out.println(obj.addTwoNumbers(100,1));
}
}
Output:

101
Chapter 5- Abstract class and Interface
Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

How to declare an interface?


Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
12.
What are the differences between a class and an interface in Java?
Java 8Object Oriented ProgrammingProgramming
Following are the notable differences between class and an interface.
Class Interface

A class describes the attributes and behaviors An interface contains behaviors that a class
of an object. implements.

A class may contain abstract methods,


An interface contains only abstract methods.
concrete methods.

Members of a class can be public, private, All the members of the interface are public by
protected or default. default.

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java only.
interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).

Multiple inheritance by Interface in Java


Java 8Object Oriented ProgrammingProgramming

An interface contains variables and methods like a class but the methods in an interface are
abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements
multiple interfaces or also if an interface itself extends multiple interfaces.
A program that demonstrates multiple inheritance by interface in Java is given as follows:
Example

interfaceAnimalEat{

voideat();

interfaceAnimalTravel{

voidtravel();

classAnimalimplementsAnimalEat,AnimalTravel{

publicvoideat(){

System.out.println("Animal is eating");

publicvoidtravel(){

System.out.println("Animal is travelling");

publicclassDemo{

publicstaticvoidmain(Stringargs[]){

Animal a =newAnimal();

a.eat();

a.travel();

}
Output
Animal is eating
Animal is travelling

Now let us understand the above program.


The interface AnimalEat and AnimalTravel have one abstract method each i.e. eat() and travel().
The class Animal implements the interfaces AnimalEat and AnimalTravel. A code snippet which
demonstrates this is as follows:

interfaceAnimalEat{

voideat();

interfaceAnimalTravel{

voidtravel();

classAnimalimplementsAnimalEat,AnimalTravel{

publicvoideat(){

System.out.println("Animal is eating");

publicvoidtravel(){

System.out.println("Animal is travelling");

In the method main() in class Demo, an object a of class Animal is created. Then the methods
eat() and travel() are called. A code snippet which demonstrates this is as follows:

publicclassDemo{

publicstaticvoidmain(Stringargs[]){

Animal a =newAnimal();
a.eat();

a.travel();

Chapter 6 - POLYMORPHISM
Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an


overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent
class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }

Output:

running safely with 60km.

Compile Time Polymorphism


Compile Time Polymorphism: Whenever an object is bound with their functionality at the
compile-time, this is known as the compile-time polymorphism. At compile-time, java knows
which method to call by checking the method signatures. So this is called compile-time
polymorphism or static or early binding. Compile-time polymorphism is achieved
through method overloading.

// Java program to demonstrate


// compile-time polymorphism

public class GFG {

// First addition function

public static int add(int a, int b)

return a + b;

// Second addition function

public static double add(

double a, double b)

return a + b;

// Driver code

public static void main(String args[])

{
// Here, the first addition

// function is called

System.out.println(add(2, 3));

// Here, the second addition

// function is called

System.out.println(add(2.0, 3.0));

Output:
5
5.0

Constructor overloading in Java

In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every
constructor can perform a different task.

Example
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David
Use of this () in constructor overloading

However, we can use this keyword inside the constructor, which can be used to invoke the
other constructor of the same class.

Consider the following example to understand the use of this keyword in constructor
overloading.

1. public class Student {


2. //instance variables of the class
3. int id,passoutYear;
4. String name,contactNo,collegeName;
5.
6. Student(String contactNo, String collegeName, int passoutYear){
7. this.contactNo = contactNo;
8. this.collegeName = collegeName;
9. this.passoutYear = passoutYear;
10. }
11.
12. Student(int id, String name){
13. this("9899234455", "IIT Kanpur", 2018);
14. this.id = id;
15. this.name = name;
16. }
17.
18. public static void main(String[] args) {
19. //object creation
20. Student s = new Student(101, "John");
21. System.out.println("Printing Student Information: \n");
22. System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.contactNo+"\
nCollege Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);
23. }
24. }

Output:

Printing Student Information:


Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018

Java Method Overloading

In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called
overloaded methods and this feature is called method overloading. For example:

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but accept
different arguments.

How to perform method overloading in Java?

Here are different ways to perform method overloading:

1. Overloading by changing the number of arguments

classMethodOverloading{
privatestaticvoiddisplay(int a){
System.out.println("Arguments: " + a);
}
privatestaticvoiddisplay(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}

publicstaticvoidmain(String[] args){
display(1);
display(1, 4);
}
}

Output:

Arguments: 1
Arguments: 1 and 4

2. By changing the data type of parameters

classMethodOverloading{

// this method accepts int


privatestaticvoiddisplay(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


privatestaticvoiddisplay(String a){
System.out.println("Got String object.");
}

publicstaticvoidmain(String[] args){
display(1);
display("Hello");
}
}

Output:

Got Integer data.


Got String object.
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

// A Simple Java program to demonstrate


// method overriding in java

// Base Class
classParent {
voidshow()
{
System.out.println("Parent's show()");
}
}

// Inherited class
classChild extendsParent {
// This method overrides show() of Parent
@Override
voidshow()
{
System.out.println("Child's show()");
}
}

// Driver class
classMain {
publicstaticvoidmain(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = newParent();
obj1.show();

// If a Parent type reference refers


// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = newChild();
obj2.show();
}
}

Output:
Parent's show()
Child's show()
Rules for method overriding:
1. Overriding and Access-Modifiers : The access modifier for an overriding method
can allow more, but not less, access than the overridden method. For example, a
protected instance method in the super-class can be made public, but not private,
in the subclass. Doing so, will generate compile-time error.

1. Upcasting: Upcasting is the typecasting of a child object to a parent object.


Upcasting can be done implicitly. Upcasting gives us the flexibility to access the
parent class members but it is not possible to access all the child class members
using this feature. Instead of all the members, we can access some specified
members of the child class. For instance, we can access the overridden methods.
2.Downcasting: Similarly, downcasting means the typecasting of a parent object to a
child object. Downcasting cannot be implicitly.
The following image illustrates the concept of upcasting and downcasting:

Chapter 7 - EXCEPTION HANDLING


Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

In this page, we will learn about Java exceptions, its type and the difference between checked
and unchecked exceptions.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by
two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception

2. Unchecked Exception

3. Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions


e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g.OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with
method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.

1. public class JavaExceptionExample{


2. public static void main(String args[]){

3. try{
4. //code that may raise exception

5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}

7. //rest code of the program


8. System.out.println("rest of the code...");

9. }
10. }
Chapter 8 - MULTITHREADING
Multitasking:
Multitasking is when a CPU is provided to execute multiple tasks at a time. Multitasking
involves often CPU switching between the tasks, so that users can collaborate with each
program together. Unlike multithreading, In multitasking, the processes share separate
memory and resources. As multitasking involves CPU switching between the tasks rapidly, So
the little time is needed in order to switch from the one user to next.
Multithreading:
Multithreading is a system in which many threads are created from a process through which
the computer power is increased. In multithreading, CPU is provided in order to execute
many threads from a process at a time, and in multithreading, process creation is performed
according to cost. Unlike multitasking, multithreading provides the same memory and
resources to the processes for execution.

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU. Each part of such program is called a
thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create
an object of our new class and call start() method to start the execution of a thread. Start()
invokes the run() method on the Thread object.
Java

// Java code for thread creation by extending

// the Thread class

classMultithreadingDemo extendsThread {

publicvoidrun()

try{

// Displaying the thread that is running

System.out.println(

"Thread "+ Thread.currentThread().getId()

+ " is running");

catch(Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}
}

// Main Class

publicclassMultithread {

publicstaticvoidmain(String[] args)

intn = 8; // Number of threads

for(inti = 0; i< n; i++) {

MultithreadingDemo object

= newMultithreadingDemo();

object.start();

Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

Java

// Java code for thread creation by implementing

// the Runnable Interface

classMultithreadingDemo implementsRunnable {

publicvoidrun()

try{

// Displaying the thread that is running

System.out.println(

"Thread "+ Thread.currentThread().getId()

+ " is running");

catch(Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

}
}

// Main Class

classMultithread {

publicstaticvoidmain(String[] args)

intn = 8; // Number of threads

for(inti = 0; i< n; i++) {

Thread object

= newThread(newMultithreadingDemo());

object.start();

Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java n
terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() metho
2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class e
Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed b
only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...

2) Java Thread Example by implementing Runnable interface


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
Output:thread is running...

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on
scheduling it chooses.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PR
Example of priority of a Thread:
1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5.
6. }
7. public static void main(String args[]){
8. TestMultiPriority1 m1=new TestMultiPriority1();
9. TestMultiPriority1 m2=new TestMultiPriority1();
10. m1.setPriority(Thread.MIN_PRIORITY);
11. m2.setPriority(Thread.MAX_PRIORITY);
12. m1.start();
13. m2.start();
14.
15. }
16. }
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }
Output: 5
10
15
20
25
100
200
300
400
500

You might also like