OOPs Using Java
OOPs Using 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.
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)
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.
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.
1. Encapsulation
2. Inheritance
3. Abstraction
4. Polymorphism
Adding new data and function is not easy. Adding new data and function is easy.
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.
Create a Class
Main.java
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 :
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:
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.
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 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
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":
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.
additive +-
equality == !=
bitwise exclusive ^
OR
bitwise inclusive |
OR
Ternary ternary ?:
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
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.
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.
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.
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.
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:
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
importjava.util.ArrayList;
importjava.util.Iterator;
publicclassMain{
publicstaticvoidmain(String[]args){
// Make a collection
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
Iterator<String> it =cars.iterator();
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:
classBreakLoopDemo
{
publicstaticvoidmain(String args[])
if(i == 5)
break;
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:
classBreakLabelDemo
publicstaticvoidmain(String args[])
booleant = true;
// label first
first:
second:
third:
// Before break
// second label
if(t)
breaksecond;
System.out.println("This won't execute.");
// First 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:
// continue in an if statement
classContinueDemo
publicstaticvoidmain(String args[])
{
// If the number is even
if(i%2== 0)
continue;
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:
classReturn
publicstaticvoidmain(String args[])
{
booleant = true;
if(t)
return;
// after return
6. Output:
7.Before the return.
You can use these conditions to perform different actions for different decisions.
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){
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if(condition){
}else{
}
Example
if(time <18){
System.out.println("Good day.");
}else{
System.out.println("Good evening.");
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if(condition1){
}elseif(condition2){
}else{
Example
if(time <10){
System.out.println("Good morning.");
}elseif(time <20){
System.out.println("Good day.");
}else{
System.out.println("Good evening.");
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
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
The example below uses the weekday number to calculate the weekday name:
Example
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;
Try it Yourself »
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 specifies some code to run if there is no case match:
Example
switch(day){
case6:
System.out.println("Today is Saturday");
break;
case7:
System.out.println("Today is Sunday");
break;
default:
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.
We can declare, instantiate and initialize the java array together by:
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
System.out.println(cars.length);
// Outputs 4
// Arrays.compareUnsigned() method
importjava.util.Arrays;
publicclassMain {
publicstaticvoidmain(String[] args)
+ Arrays.compareUnsigned(intArr, intArr1));
2. Output:
3.
4.
// Arrays.copyOf() method
importjava.util.Arrays;
publicclassMain {
publicstaticvoidmain(String[] args)
{
// Get the Array
+ Arrays.toString(intArr));
+ 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
o for loop
o while loop
o 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.
classwhileLoopDemo
{
publicstaticvoidmain(String args[])
intx = 1;
while(x <= 4)
// 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:
classforLoopDemo
publicstaticvoidmain(String args[])
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-
publicclassenhancedforloop
publicstaticvoidmain(String args[])
for(String x:array)
{
System.out.println(x);
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:
classdowhileloopDemo
{
publicstaticvoidmain(String args[])
intx = 21;
do
x++;
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
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");
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!
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.
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.
Step 6) Error = ? This is because it is not possible to access instance variable "a" from java static
class method "increment".
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
}
}
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
Value of a = 10
Value of b = 20
Java Package
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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
4. Subpackage
6. -classpath switch
9. Static Import
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
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:
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).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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
1. import package.*;
2. import package.classname;
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.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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.
Step 1: Click on the Windows button and choose Control Panel. Select System.
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;.;
PATH CLASSPATH
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 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.
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.
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:
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:
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 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.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
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 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 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.
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.
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.
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:
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...
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.
class Temp
// default constructor 1
Temp()
// calls constructor 2
this(5);
// 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);
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 :
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.
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.
Parent(){
System.out.println("Parent()...");
Child(){
System.out.println("Child()...");
new Child();
OUTPUT:
Constructor call order…
Parent()…
Child()…
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.
Design(){
System.out.println("Design()...");
}
}
Coding(){
System.out.println("coding()...");
Testing()
System.out.println("Testing()...");
new Testing();
OUTPUT:
Constructor call order…
Design()…
coding()…
Testing()…
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
The major difference between public and private modifiers is its visibility. Java categories the
visibility for class members as follows:
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:
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{
packagexyzpackage;
importabcpackage.*;
classTestextendsAddition{
publicstaticvoidmain(Stringargs[]){
Testobj=newTest();
System.out.println(obj.addTwoNumbers(11,22));
}
}
Output:
33
The members, methods and classes that are declared public can be accessed from anywhere.
This modifier doesn’t put any restriction on the access.
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{
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.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
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.
Members of a class can be public, private, All the members of the interface are public by
protected or default. default.
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.
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.
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%).
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
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.
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{}
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:
return a + b;
double a, double b)
return a + b;
// Driver code
{
// Here, the first addition
// function is called
System.out.println(add(2, 3));
// function is called
System.out.println(add(2.0, 3.0));
Output:
5
5.0
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:
Student Id : 0
Student Name : null
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.
Output:
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:
Here, the func() method is overloaded. These methods have the same name but accept
different 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
classMethodOverloading{
publicstaticvoidmain(String[] args){
display(1);
display("Hello");
}
}
Output:
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.
// 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();
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.
In this page, we will learn about Java exceptions, its type and the difference between checked
and unchecked exceptions.
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
3) Error
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.
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.
Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
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
classMultithreadingDemo extendsThread {
publicvoidrun()
try{
System.out.println(
+ " is running");
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
// Main Class
publicclassMultithread {
publicstaticvoidmain(String[] args)
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
classMultithreadingDemo implementsRunnable {
publicvoidrun()
try{
System.out.println(
+ " is running");
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
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
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
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class e
Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed b
only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
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.
Types of Synchronization
1. Process Synchronization
2. 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