0% found this document useful (0 votes)
2 views

JAVA - Copy

The document outlines the features of Java, emphasizing its simplicity, object-oriented nature, security, portability, and multithreading capabilities. It details the structure of a Java program, including package and import sections, class definitions, and the main method, alongside an explanation of Java tokens, data types, and object-oriented programming concepts such as inheritance, polymorphism, method overloading, and encapsulation. Additionally, it provides examples of various programming constructs and their syntax within Java.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA - Copy

The document outlines the features of Java, emphasizing its simplicity, object-oriented nature, security, portability, and multithreading capabilities. It details the structure of a Java program, including package and import sections, class definitions, and the main method, alongside an explanation of Java tokens, data types, and object-oriented programming concepts such as inheritance, polymorphism, method overloading, and encapsulation. Additionally, it provides examples of various programming constructs and their syntax within Java.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

FEATURES OF JAVA

Simple: A very simple, easy to learn and understand language for


programmers who are already familiar with OOP concepts.

Object-oriented: Java is object oriented. Java inherits features of C+


+. OOP features of java are influenced by C++. OOP concept forms
the heart of java language that helps java program in survive the
inevitable changes accompanying software development.

Secure, Portable and Robust: Java programs are safe and secure to
download from internet.
At the core of the problem is the fact that malicious code can cause its
damage due to unauthorized access gained to system resources. Java
achieved this protection by confining a program to the Java execution
environment and not allowing it access to other parts of the computer.

Multithreaded: Java supports multithreaded programming, which allows a


programmer to write programs that performs multiple tasks simultaneously.
JAVA PROGRAMMING FORMAT

Package Section: It must be the first line of a java program or can be omitted if the class is
to be kept only in the default package.
The package statement defines a namespace in which classes are stored, based on
functionality.
If omitted, the classes are put into the default package, which has no name.
Import Section: Specifies the location to use a class or package into a program.
Class / Interface section: A java program may contain several classes or interface.
Class with Main Method: Every Java stand-alone program requires the main method as
the starting point of the program. This is an essential part of a Java program. There may be
many classes in a Java program code file, and only one class defines the main method.
Example:
// ----- Package Section -------
Package mypack;
// -------- Import Section -------
import java.util.Date; // This line will import only one class from the util package
import java.awt.*; // This line will import all classes available in awt package
// ----------- Class / Interface Section ----------
class A {
// Class Body
}
interface B {
// Interface Body
}
// ----------- Main Method Section ----------
public class Test{
public static void main(String[] args){
// body of main method
}
}
Java Tokens
Tokens are the basic building blocks of the java programming language that are used in
constructing expressions, statements and blocks.

Keywords: these words are already been defined by the language and have a predefined
meaning and use. Key words cannot be used as a variable, method, class or interface

Identifiers: Identifiers are used to name a variable, method, block, class or


interface etc. Java is case-sensitive. Identifier may be any sequence of uppercase
and lowercase letters, numbers, or the underscore characters.
Rules for defining identifier:
All variable names must begin with a letter of the alphabet. The dollar sign
and the underscore are used in special case.
After the first initial letter, variable names may also contain letters and the digits
0 to 9. No spaces or special characters are allowed.
Uppercase characters are distinct from lowercase characters. Variable names are
case-sensitive.
Examples: num1, name, Resi_addr, Type_of_road, Int etc.

Literals: Literals are the value assigned to a variable


Example: 10, “Mumbai”, 3.14, ‘Y’, ‘\n’ etc.
Operators: Operators are the symbols that performs operations.
Java contains different types of operators like Arithmetic Operator (+,-,*,/,%), Logical
Operator (&&, ||, ~, ), Relational Operator(<, <=, >, >=,!=, ==), Bitwise Operators (&, |,
~), Shift Operators (<<, >>, >>>) , Assignment Operators(=, +=, -+, *=, /=, %=),
Conditional Operator (?:).
Separators: Separators are used to separate words, expressions, sentences, blocks etc.

Symbol Name Description

Space Used to separate tokens.

; Semicolon Used to separate the statements

() Parentheses Used to contain the lists of parameters in method definition and


invocation. Also used for defining the precedence in
expressions, containing expressions in control statements, and
surrounding cast types.

{} Braces Used to contains the values of automatically initialized arrays.


Also used to define a block of code, for classes, methods, and
local scopes.

[] Brackets Used to declare array types. Also used when dereferencing array
values.

, Comma Separates consecutive identifiers in a variable declarations. Also


used to chain statements together inside a for statement

. Period Used to separate packages names from subpackages and classes.


Also used to separate a variable or method from a reference
variable.
Java Statements
A statement specifies an action in a Java program. Statements in Java can be broadly
classified into three categories:

Declaration: A declaration statement is used to declare a variable, method or class.


example:
int num; double PI = 3.14; String name=”University of Mumbai; int
showResult(int a, int b);
Expression: expression is a construct made up of variables, operators, and method
invocations, which are constructed according to the syntax of the language, that evaluates to
a single value.
example:
Arithmetic Expression: (A+B)*C-(D%E)*(-F+G)
Logical Expression: (m > n && x < y) != (m <= n || x >= y)
Flow Control: By default, all the statements in a java program are executed in the order they
appear in the program code. However sometime a set of statements need to be executed and
a part to be skipped, also some part need to be repeated as long as a condition is true or till
some fix number of iteration.
program control statements can be put into the following categories: Branching / selection,
Looping / iteration, and jump control.
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your program’s execution based upon conditions known only
during run time.

 if
The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths.

General Syntax:
if (condition)
statement1 / { if Block }; else
statement2 / { else Block};

Example:
class ifelsetest{
public static void main(String[] args)
{
int num=10;
if(num%2 == 0)
{
System.out.println(“Number is EVEN”);
}
else {
System.out.println(“Number is ODD”);
}
}
}
 The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-else-
if ladder.
General Syntax:

if(condition)
statement;
else
if(condition)
statement;
else if(condition)
Statement;
.
.
.
.
else statement;

Example:
class ladderifelsetest
{
public static void main(String[] args)
{

int num=10;
if(num> 0)
{
System.out.println(“Number is +VE”);
}
else if(num<0)
{
System.out.println(“Number is -VE”);
}
else {
System.out.println(“Number is ODD”);
}
}
}

Java Data Types

byte, short, int, and long, which are for whole-valued signed numbers.
byte 8 1 byte –128 to 127
short 16 2 byte –32,768 to 32,767
int 32 4 byte –2,147,483,648 to
2,147,483,647
long 64 6 byte –9,223,372,036,854,775,808 to
9,223,372,036,854,775,80
7
float and double, which represent numbers with fractional precision.
float 32 4 byte 1.4e–045 to 3.4e+038
double 64 8 byte 4.9e–324 to 1.8e+308

OOPS

1) Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code.

2) Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.

3) Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
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.
1) Single Inheritance Example
When a class inherits another class, it is known as a single inheritance.
Example
Dog class inherits the Animal class
class Animal
{
Public void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
Public void bark()
{
System.out.println("barking...");}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

2) Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance.
Example
BabyDog class inherits the Dog class which again inherits the Animal class
class Animal
{
Public void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
Public void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
Public void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}

3) Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance.
Example
Dog and Cat classes inherits the Animal class
class Animal
{
Public void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
Public void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
Public void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Dog g = new dog();
g.eat();
g.bark();

Cat c=new Cat();


c.meow();
c.eat();

}
}

4) Polymorphism
Advantages of Polymorphism

Code Reusability
Methods in subclasses to override methods in their superclass, enabling code reuse
Flexibility and Extensibility
Allows subclasses to provide their own implementations of methods defined in the
superclass, making it easier to extend and customize behavior without modifying existing
code.
Reduced Code Complexity
Helps reduce code complexity by promoting a modular and hierarchical class structure,
making it easier to understand, maintain, and extend large-scale software systems.
Types of Polymorphism

There are two types of polymorphism in Java:

1. Compile-time polymorphism
2. Runtime polymorphism.

Compile- Time Polymorphism in Java

In Java, method overloading is used to achieve compile-time polymorphism. A class can


have numerous methods with the same name but distinct parameter lists
The compiler uses the amount and kind of parameters provided to it during compilation to
decide which method to call. This choice is made during compilation, which is why it's
called "compile-time polymorphism."
Runtime Polymorphism in Java
Runtime polymorphism 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.
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.
class Bike
{
void run(){System.out.println("running");}
}
class Splendor extends Bike
{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[])


{
Bike b = new Splendor();
b.run();
}
}
Output
running safely with 60km

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
Method overloading increases the readability of the program.
Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
class Adder
{
Public static int add(int a,int b)
{
return a+b;
}
Public static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder
{
Public static int add(int a, int b)
{
return a+b;
}
Public static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}

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.
OR
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 real example of Java Method Overriding

class Bank
{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}

class ICICI extends Bank


{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Difference between method overloading and method overriding in java

Method overloading is used to increase the readability of the program.


Method overriding is used to provide the specific implementation of the method that is
already provided by its super class.
Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
In case of method overloading, parameter must be different.
In case of method overriding, parameter must be same.
Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
Return type can be same or different in method overloading. But you must have to change
the parameter.
Return type must be same or covariant in method overriding.

5) Encapsulation in Java

Encapsulation is defined as the wrapping up of data under a single unit.


It is a protective shield that prevents the data from being accessed by the code outside this
shield.
Encapsulation is a way of hiding the implementation details of a class from outside access
and only exposing a public interface that can be used to interact with the class.
Encapsulation ensures that the internal workings of a class are hidden
Encapsulation is achieved by declaring the instance variables of a class as private, which
means they can only be accessed within the class.
To allow outside access to the instance variables, public methods called getters and setters
are defined, which are used to retrieve and modify the values of the instance variables
Examples:
class Person {
private String name;
private int age;

public String getName()


{
return name;
}

public void setName(String name)


{
this.name = name;
}

public int getAge()


{
return age;
}

public void setAge(int age)


{
this.age = age;
}
}

public class Main {


public static void main(String[] args)
{
Person person = new Person();
person.setName("John");
person.setAge(30);

System.out.println("Name: " + person.getName());


System.out.println("Age: " + person.getAge());
}
}

class Account
{
private long acc_no;
private String name, email;
private float amount;
public long getAcc_no()
{
return acc_no;
}
public void setAcc_no(long acc_no)
{
this.acc_no = acc_no;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public float getAmount()
{ return amount;
}
public void setAmount(float amount)
{
this.amount = amount;
}
}

public class GFG {


public static void main(String[] args)
{
Account acc = new Account();
acc.setAcc_no(90482098491L);
acc.setName("ABC");
acc.setEmail("[email protected]");
acc.setAmount(100000f);

System.out.println(
acc.getAcc_no() + " " + acc.getName() + " "
+ acc.getEmail() + " " + acc.getAmount());
}
}
Advantages of Encapsulation

Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details.
Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirements.
Reusability

6) Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. It shows only essential things to the user and hides the internal
details
Ways to achieve Abstraction
Using Abstract Class (0 to 100%)

Using Interface (100%)


Abstract Class in Java
An abstract class in Java acts as a partially implemented class that itself cannot be
instantiated. It exists only for subclassing purposes, and provides a template for its
subcategories to follow.

Abstract classes can have implementations with abstract methods. Abstract methods are
declared to have no body, leaving their implementation to subclasses.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Syntax
public abstract class Shape
{
// Abstract method
public abstract double area();
// Concrete method
public void display()
{
System.out.println("This is a shape.");
}
}
Examples

Abstract Class that has an Abstract Method

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Abstract class that has abstract and non-abstract methods
abstract class Bike
{
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely..");
}
}

class TestAbstraction2
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

Interface in Java

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.
Interfaces can have abstract methods and variables. It cannot have a method body.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
A class extends another class, an interface extends another interface, but a class implements
an interface.

Examples:

1)
interface printable
{
void print();
}
class Example1 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
Example1 obj = new Example1();
obj.print();
}
}

2)
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Multiple Inheritance in Java by Interface
Multiple inheritance is not supported in the case of class because of ambiguity. However, it
is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
A7 obj = new A7();
obj.print();
obj.show();
}
}
Static Method in Interface
interface Drawable
{
void draw();
static int cube(int x)
{
return x*x*x;
}
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}
}

Difference between abstract class and interface


Abstract class Interface

Interface can have only abstract methods. Since


1) Abstract class can have abstract and non-
Java 8, it can have default and static
abstract methods.
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 interfaces. only.

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

Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Usage of Java super Keyword
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor.
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
class Student extends Person {
Student()
{
super();
System.out.println("Student class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
When to use a final variable?
Final variables must be used only for the values that we want to remain constant
throughout the execution of the program.
public class ConstantExample
{
public static void main(String[] args)
{
final double PI = 3.14159;
System.out.println("Value of PI: " + PI);
}
}
2) Java Final Method
When a method is declared with final keyword, it is called a final method in Java. A final
method cannot be overridden.
We must declare methods with the final keyword for which we are required to follow the
same implementation throughout all the derived classes.
class Bike
{
final void run()
{
System.out.println("running");
}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error

3) Java Final classes


When a class is declared with the final keyword in Java, it is called a final class. A final
class cannot be extended(inherited).
Other use of final with classes is to create an immutable class like the
predefined String class. One cannot make a class immutable(data cannot be accidentally or
maliciously modified) without making it final.
final class Bike
{
// methods and fields
}

class Honda1 extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[])


{
Honda1 honda= new Honda1();
honda.run();
}
}

Output:Compile Time Error

Can we declare a constructor final?


No, because constructor is never inherited.

What is final parameter?


If you declare any parameter as final, you cannot change the value of it.

class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

Output: Compile Time Error

‘this’ reference in Java


In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this”
in Java is a keyword that refers to the current object instance.
It can be used to call current class methods and fields, to pass an instance of the current
class as a parameter, and to differentiate between the local and instance variables.
Improve code readability and reduce naming conflicts.
Using ‘this’ keyword to refer to current class instance variables

class Test {
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
}
Output
a = 10 b = 20

Using ‘this’ keyword to invoke the current class method

class Test {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display function");
}
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
Output
Inside show function
Inside display function

Exception Handling in Java


Exception is an event that occurs during the execution of a program i.e. at run time that
disrupts the normal flow of instructions.
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.
Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
Major reasons why an exception Occurs
 Invalid user input
 Out of bound
 Null reference
 Arithmetic errors
 Type mismatch
 Opening an unavailable file
 Database errors

Types of Exceptions

1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that the
compiler verifies that the code handles these exceptions either by catching them or declaring
them in the method signature using the throws keyword.

ClassNotFoundException: It is thrown when an application tries to load a class through its


string name using methods like Class.forName(), but the class with the specified name
cannot be found in the classpath.
FileNotFoundException is another exception occurs when we try to access that file which is
not available in the system.

IOException: An exception is thrown when an input/output operation fails, such as when


reading from or writing to a file.

SQLException: It is thrown when an error occurs while accessing a database.

2. Unchecked Exceptions
Unchecked exceptions, also known as runtime exceptions, are not checked at compile-
time. These exceptions usually occur due to programming errors, such as logic errors or
incorrect assumptions in the code.

NullPointerException: It is thrown when trying to access or call a method on an object


reference that is null.

ArrayIndexOutOfBoundsException: It occurs when we try to access an array element


with an invalid index.

ArithmeticException: It is thrown when an arithmetic operation fails, such as division


by zero.

The try-catch Block


One of the primary mechanisms for handling exceptions in Java is the try-catch block.
The try block contains the code that may throw an exception, and the catch block is used
to handle the exception if it occurs.

1) A scenario where ArithmeticException occurs

public class ArithmeticExceptionExample


{
public static void main(String[] args)
{
int dividend = 10;
int divisor = 0;
try {
int result = dividend / divisor; // Division by zero
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
2) A scenario where NullPointerException occurs

public class NullPointerExceptionExample


{
public static void main(String[] args)
{
String str = null; // Initializing a String variable to null
try {
int length = str.length(); // Attempting to call a method on a null reference
System.out.println("Length of the string: " + length);
}
catch (NullPointerException e) {
System.out.println("Error: Null reference encountered.");
}
}
}

3) A scenario where ArrayIndexOutOfBoundsException occurs

public class ArrayIndexOutOfBoundsExceptionExample {


public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5}; // Initializing an array with 5 elements
try {
int index = 10; // Accessing an index that is out of bounds
int value = numbers[index]; // Attempting to access an element at an invalid index
System.out.println("Value at index " + index + ": " + value);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index is out of bounds.");
}
}
}

Java Catch Multiple Exceptions

public class MultipleCatchBlock3 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested
try block.
Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.
For example
The inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
int b =39/0;
System.out.println(b);
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}

Java finally block

 Java finally block is always executed whether an exception is handled or not.


Therefore, it contains all the necessary statements that need to be printed regardless of
the exception occurs or not.

 The finally block follows the try-catch block.


Why use Java finally block?

o Finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.

Case 1: When an exception does not occur

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code does not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("Finally block is always executed");
}
System.out.println("Rest of the code...");
}
}
Output:
5
Finally block is always executed
Rest of the code…

Case 2: When an exception occurr but not handled by the catch block

public class TestFinallyBlock1{


public static void main(String args[]){

try {
System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handles Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println (e);
}

//executes regardless of exception occurred or not


finally {
System.out.println ("finally block is always executed");
}
System.out.println ("rest of the code...");
}
}
Output:

Case 3: When an exception occurs and is handled by the catch block


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

try {
System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occurred or not


finally {
System.out.println("finally block is always executed");
}

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


}
}
Output:

Java Exception Propagation


An exception is first thrown from the top of the stack and if it is not caught, it drops down
the call stack to the previous method. If not caught there, the exception again drops down to
the previous method, and so on until they are caught or until they reach the very bottom of
the call stack. This is called exception propagation.

class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:

exception handled
normal flow..
.
In the above example exception occurs in the m() method where it is not handled, so it is
propagated to the previous n() method where it is not handled, again it is propagated to the
p() method where exception is handled.

Java throw Keyword


The "throw" keyword in Java is used to explicitly throw an exception. It disrupts the normal
flow of the program by transferring control to the nearest catch block that can handle the
thrown exception.
public class TestThrow {
public static void checkNum(int num) {
if (num < 1) {
// throw the exception
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
}
}

Output:
Java throws keyword
throws is a keyword in Java that is used in the signature of a method to indicate that this
method might throw one of the listed type exceptions.
In a program, if there is a chance of raising an exception then the compiler always warns us
about it and compulsorily we should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be caught or declared to be
thrown. To prevent this compile time error we can handle the exception in two ways:

1. By using try catch


2. By using the throws keyword

We can use the throws keyword to delegate the responsibility of exception handling to the
caller (It may be a method or JVM) then the caller method is responsible to handle that
exception.

Example 1 (Checked exception)


Java program to illustrate error in case of unhandled exception

class tst {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output
error: unreported exception InterruptedException; must be caught or declared to be thrown

In the above program, we are getting compile time error because there is a chance of
exception if the main thread is going to sleep, other threads get the chance to execute the
main() method which will cause InterruptedException.

by using the throws keyword we handled the InterruptedException

class tst {
public static void main(String[] args)
throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output
Hello Geeks

Example 2 (Unchecked exception)


public class TestThrows {
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}
Output:

Difference between throw and throws in Java


Java throws keyword
Java throw keyword
is used in the method
is used throw an
signature to declare
exception explicitly in
1. Definition an exception which
the code, inside the
might be thrown by
function or the block
the function while the
of code.
execution of the code.

Using throws
Type of exception
keyword, we can
Using throw keyword,
declare both checked
we can only
and unchecked
propagate unchecked
2. Uses exceptions. However,
exception i.e., the
the throws keyword
checked exception
can be used to
cannot be propagated
propagate checked
using throw only.
exceptions only.
The keyword throw is The keyword throws
3. Declaration used within the is used with the
method. method signature.

We can declare
multiple exceptions
We are allowed to using throws keyword
throw only one that can be thrown by
Internal
4. exception at a time the method.
Implementation
i.e. we cannot throw
multiple exceptions. For example, main()
throws IOException,
SQLException.

Difference between Error and Exception

In Java, Exception, and Error both are subclasses of the Java Throwable class that belongs
to java.lang package. But there exist some significant differences between them.

Both errors and exceptions are a type of runtime error,

 An Error indicates a serious problem that a reasonable application cannot be caught


or handled.
 Exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.

Multithreading

Multiprocessing and multithreading, both are used to achieve multitasking.


Multiprocessing : Process-based multitasking is a heavyweight process and occupies
different address spaces in memory. Hence, while switching from one process to another, it
will require some time be it very small, causing a lag because of switching. This happens as
registers will be loaded in memory maps and the list will be updated.
Multithreading : Thread-based multitasking is a lightweight process and occupies the
same address space. Hence, while switching cost of communication will be very less.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread. Thread
class extends Object class and implements Runnable interface.

Methods of thread class are shown below

Methods Action Performed

isDaemon() It checks whether the current thread is daemon or not

start() It is used to start the execution of the thread.

run() It is used to do an action for a thread.

It is a static method that puts the thread to sleep for a certain time been
sleep()
passed as an argument to it

wait() It sets the thread back in waiting state.

notify() It gives out a notification to one thread that is in waiting state

notifyAll() It gives out a notification to all the thread in the waiting state

setDaemon() It set the current thread as Daemon thread

stop() It is used to stop the execution of the thread

resume() It is used to resume the suspended thread.

Life cycle of a Thread


New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other
is running.

o Runnable: A thread that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant
of time. It is the duty of the thread scheduler to provide the thread time to run.
o A program implementing multithreading acquires a fixed slice of time to each
individual thread. Each and every thread runs for a short span of time and when that
allocated time slice is over, the thread voluntarily gives up the CPU to the other
thread, so that the other threads can also run for their slice of time. Whenever such a
scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen
thread is then given the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation.

To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the
waiting state for a specific span of time, and not forever.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is
dead, and there is no way one can respawn (active after kill) the dead thread.
In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the
state of a thread.

You might also like