You are on page 1of 57

Nimble Tech

Success With Ease …


www.nimbletech.org Mail- nimbletechsolutions@gmail.com

What is Java
Java is a programming language and a platform.Java is a high level, robust, secured
and object-oriented programming language.

Where it is used?
1. Desktop Applications such as acrobat reader, media player, antivirus etc.

2. Web Applications such as irctc.co.in, javatpoint.com etc.

3. Enterprise Applications such as banking applications.

4. Mobile

5. Embedded System

6. Smart Card

7. Robotics

8. Games etc

Types of Java Applications


There are mainly 4 type of applications that can be created using java programming:

1) Standalone Application

It is also known as desktop application or window-based application. An application that we


need to install on every machine such as media player, antivirus etc.

2) Web Application

An application that runs on the server side and creates dynamic page, is called web
application.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

3) Enterprise Application

An application that is distributed in nature, such as banking applications etc.It has the
advantage of high level security, load balancing and clustering.

4) Mobile Application

An application that is created for mobile devices.

Simple Program of Java


We can write a simple hello java program easily after installing the JDK.To create a simple
java program, you need to create a class that contains main method.

For executing any java program, you need to

o install the JDK if you don't have installed it.

o set path of the jdk/bin directory.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Click on Ok to complete.

o create the java program

o compile and run the java program

class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

In Eclipse , Right click on the class and goto Run As ->Java Application. The output will be
printed in the console.
Output:Hello Java

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Understanding first java program


Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

o class keyword is used to declare a class in java.

o public keyword is an access modifier which represents visibility.

o static is a keyword, if we declare any method as static, it is known as static method.


The core advantage of static method is that there is no need to create object to
invoke the static method. The main method is executed by the JVM, so it doesn't
require to create object to invoke the main method. So it saves memory.

o void is the return type of the method, it means it doesn't return any value.

o main represents startup of the program.

o String[] args is used for command line argument. We will learn it later.

o System.out.println() is used to print statement.

At compile time

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

At run time

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Difference between JDK, JRE and JVM

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Internal Architecture of JVM


It contains classloader, memory area, execution engine etc.

The native method interface and native libraries are required for cross platform
communication.

1) Class loader

Class loader is a subsystem of JVM that is used to load class files.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

2) Class(Method) Area

ClassArea stores per-class structures such as the field and method data, the code for
methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack
It holds local variables and partial results

5) Program Counter Register

It contains the address of the Java virtual machine instruction currently being executed.

6) Execution Engine
It contains:

1) A virtual processor
2) Interpreter
3) Just-In-Time(JIT) compiler

Variable and Datatype in Java


Variable is a name of memory location. There are three types of variables: local, instance
and static.There are two types of datatypes in java, primitive and non-primitive.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Local Variable
A variable that is declared inside the method is called local variable.

Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.

Static variable
A variable that is declared as static is called static variable. It cannot be local.

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

There are two types of data types

o primitive data types

o non-primitive data types

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java Naming conventions


Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method etc.

Note: It is not forced rule we can or cannot follow it.

Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color
interface name should start with uppercase letter and be an adjective e.g. Runnable,
Remote,

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main()
variable name should start with lowercase letter e.g. firstName
package name should be in lowercase letter e.g. java, lang
constants name should be in uppercase letter. e.g. RED, YELLOW

Java OOPs Concepts


Object

Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism.In Java we
use method overloading and method overriding to achieve polymorphism.

Abstraction

Hiding internal details and showing functionality is known as abstraction.In java, we


use abstract class and interface to achieve abstraction.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation.A java class is the example of encapsulation.

Method Overloading in Java


If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

1) Example of Method Overloading by changing the no. of


arguments

class Calculation{
void sum(int a,int b)
{
System.out.println(a+b);
}

void sum(int a,int b,int c)


{
System.out.println(a+b+c);
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}

2) Example of Method Overloading by changing data type of


argument
class Calculation{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);

}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Constructor in Java
Constructor in java is a special type of method that is used to initialize the object. It is
invoked at the time of object creation.There are basically two rules defined for the
constructor.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

Types of java constructors

Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax : MyClass(){}

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Syntax : MyClass(String nm,int sal){

this.name =nm; this.salary = sal;

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

We can also have overloaded constructor like

Syntax : MyClass(String nm){

this.name =nm;

Note :Constructor can be used for object creation, calling a method or starting a thread.We
can perform any operation in the constructor as you perform in the method.

Java static keyword


The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class.

1) static variable
 The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees.

 The static variable gets memory only once in class area at the time of class loading.

 It makes our program memory efficient.

2) static method
 A static method belongs to the class rather than object of a class.

 A static method can be invoked without the need for creating an instance of a class.

 static method can access static data member and can change the value of it.

3) static block
 Is used to initialize the static data member.

 It is executed before main method at the time of classloading.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

 Syntax :

static {

// Any Code for initializing the static member or any method call

4) static class
 Top level class cannot be static only nested class can be. Nested class means class
inside another class.

Inheritance in Java
 Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
 When we inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
 Inheritance in java is used for method overriding and code reusability.

Syntax :

class Subclass-name extends Superclass-name


{
//methods and fields
}

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.
 Method overriding is used for runtime polymorphism

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Rules for Java Method Overriding


1. method must have same name as in the parent class

2. method must have same parameter as in the parent class.

3. must be IS-A relationship (inheritance).

Instance initializer block


Instance Initializer block is used to initialize the instance data member. It run each time
when object of the class is created.

Example :

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

There are mainly three rules for the instance initializer block.

1. The instance initializer block is created when instance of the class is created.

2. The instance initializer block is invoked after the parent class constructor is invoked
(i.e. after super() constructor call).

3. The instance initializer block comes in the order in which they appear.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Final Keyword In Java


 The java final keyword can be used in three context mainly variable,method
and class.
 If used in variable context then we cannot change the value of it.
 If used in method context then we cannot override the method.
 If used in class context then we cannot extend the class.

Example :

final int speedlimit=90;//final variable

final void show(){System.out.println("showing");} //final method

final class MyFinalClass{}//final class

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.
 The determination of the method to be called is based on the object being referred to
by the reference variable.

publicclass ParentClass {

publicvoid display() {
System.out.println("Parent Class is called");

publicclass ChildClass extends ParentClass {

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

@Override
publicvoid display() {
System.out.println("Child Class is called");
}

Class TestMain {

public static void main(String[] args){

//Scenario 1

ParentClass pc = new ParentClass();

pc.display(); //It will call the parent class method the object created of
parent type( new ParentClass())

//Scenario 2

ChildClass cc = new ChildClass();

cc.display();// It will call the parent class method the object created of
child type( new ChildClass())

//Scenario 3

ParentClass pc =new ChildClass();

pc.display(); // It will call the parent class method the object created of
child type( new ChildClass())

//Scenario 4

ChildClass cc = new ParentClass();// Compile error

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Abstraction in Java
 Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
 For example as driver of a car he is only concerned about driving it carefully using all
its features not worry about how gear works etc.
 There are two ways to achieve abstraction in java :

 Abstract class (0 to 100%)

 Interface (100%)

Abstract class in Java


 A class that is declared as abstract is known as abstract class.
 It needs to be extended and its method implemented.
 It cannot be instantiated.

Example :

abstract class Car{


abstract void gear();
}
class BMW extends Car{
void gear (){System.out.println("Auto transmission gear..");}
public static void main(String args[]){
Carobj = new BMW ();
obj.gear();
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

 The abstract class can also be used to provide some implementation of the interface.
 In such case, the end user may not be forced to override all the methods of the
interface.

Interface in Java
 The interface in java is a mechanism to achieve fully abstraction.
 There can be only abstract methods in the java interface not method body.
 It is used to achieve fully abstraction and multiple inheritance in Java.
 It cannot be instantiated just like abstract class.

Example :
interface Printable{
void print();
}

class A6 implements Printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

}
}

Understanding all java access modifiers

Access Modifier within class within package outside package outside package
by subclass only
Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Java access modifiers with method overriding


 If you are overriding any method, overridden method (i.e. declared in subclass) must
not be more restrictive.

class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//Compile Time Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

}
}

 The default modifier is more restrictive than protected. That is why there is compile
time error.

Encapsulation in Java
 Encapsulation in java is a process of wrapping code and data together into a single
unit.
 Java class is an example of encapsulation in Java as we have both data or fields and
method inside a class.

Control & Loop Structures in Java


o if statement

o if-else statement

o nested if statement

o if-else-if ladder

Java IF Statement
It executes the if statement if condition is true.

Syntax :

if(condition){
//code to be executed
}

Java IF-else Statement


It executes the if block if condition is true otherwise else block.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

if(condition){
//code if condition is true
}else{
//code if condition is false
}

Java IF-else-ifStatement
The if-else-if ladder statement executes one condition from multiple statements.

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
...
else{
//code to be executed if all the conditions are false
}

Java Switch Statement


 The Java switch statement is executes one statement from multiple conditions.
 It is like if-else-if ladder statement.

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}

 It executes all statement after first match if break statement is not used with switch
cases.

Java For Loop


The Java for loop is used to iterate a part of the program several times.

Syntax for simple for loop :

for(initialization;condition;incr/decr){
//code to be executed
}
 The loop will check the initialization parameter, then check the condition if it is true
execute the statement , incr/decr then once again check the condition to continue
the loop.
 If the condition is false then the control will come out of loop.

public class ForLoopExample {


public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}

For-each loop syntax :


The for-each loop is used to traverse array or collection in java.
Syntax :

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

for(Type var:array){
//code to be executed
}

public class ForEachLoopExample {


public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}

Java While Loop


 The Java while loop is used to iterate a part of the program several times.
 If the number of iteration is not fixed, use while loop.
Syntax:
while(condition){
//code to be executed
}

public class WhileLoopExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java do-while Loop


 The Java do-while loop is used to iterate a part of the program several times.
 The only difference to while loop is it ensures at least it is executed once.

public class DoWhileLoopExample {


public static void main(String[] args) {
int i=10;
do{
System.out.println(i);
i++;
}while(i<=20);
}
}

Java Break Statement


 The Java break is used to break loop or switch statement.
 It breaks the current flow of execution at the specified condition.

public class JavaBreakExample {


public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==6){
break;
}
System.out.println(i);
}
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java Continue Statement


 The Java continue statement is used to continue loop.
 It continues the current flow of the program and skips the remaining code at
specified condition.

public class JavaContinueExample {


public static void main(String[] args) {
for(int i=1;i<=8;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}

Exception Handling in Java


 Exception Handling is a mechanism to handle errors such as ClassNotFound, IO,
SQL, Remote etc.
 Error cannot be handled programmatically but exception can be handled.
 The core advantage of exception handling is to maintain the normal flow of
the application.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Hierarchy of Java Exception classes

There are mainly two types of exceptions:

1) Checked Exception

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

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java Exception Handling Keywords


There are 5 keywords used in java exception handling.

1. try

2. catch

3. finally

4. throw

5. throws

Java try-catch
 Java try block is used to enclose the code that might throw an exception.
 It must be used within the method.
 Java try block must be followed by either catch or finally block.

try{
//code that may throw exception
}catch(Exception_class_Name ref){}

or

try{
//code that may throw exception
}finally{}

Java Multi catch block


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

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

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

 At a time only one Exception is occurred and one catch block is executed.
 All catch blocks should be ordered from most specific to most general i.e Arithmeatic
Exception should come before Exception.

public class TestMultipleCatchException{


public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common exception");}
catch(ArithmeticException e){System.out.println("Arithmetic Exception");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("Array Exception");}
System.out.println("rest of the code...");
}
}
Output: Compile-Time error

 We can also have nested try-catch block means try inside another try block.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java finally block


 Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
 Java finally block is always executed whether exception is handled or not.
 Java finally block follows try or catch block.
 The finnaly block will not be executed if program exits by System.exit() or any fatal
error.

Java throw keyword


 The Java throw keyword is used to explicitly throw an exception.
 Either checked or uncheked exception can be thrown by throw keyword.
 The throw keyword is mainly used to throw custom exception.
Syntax : throw new IOException("sorry some error”);

public class Throw{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("You are eligible for voting");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java throws keyword


 The Java throws keyword is used to declare an exception.
 Throws keyword is used in method signature to declare an exception.
 There can be multiple throws keyword and also it can declare both checked and un-
checked exception.

Syntax :
void show() throws IOException{
//method code
}

 It provides information to the caller of the method about the exception.

 In case we declare the exception, if exception does not occur, the code will be
executed fine.

 In case we declare the exception if exception occurs, an exception will be thrown at


runtime because throws does not handle the exception.

Exception Handling with Method Overriding in


Java
If the superclass method does not declare an exception

 If the parentclass method does not declare an exception, childclass overridden


method may or may not declare any exception.If it doesnot then no issues but
cannot declare the checked exception only declare unchecked exception.

If the superclass method declares an exception

 If the parentclass method declares an exception, childclass overridden method can


declare same, subclass exception or no exception but cannot declare parent
exception.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java Custom Exception


 If we are creating our own Exception that is known as custom exception or user-
defined exception.
 By the help of custom exception, we can have our own exception and message.
 Example :

class MyException extends Exception{


MyException(String s){
super(s);
}
}
 If we want to make our custom exception class as Checked then make it extend
Exception else RuntimeException.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Java I/O
 Java I/O (Input and Output) is used to process the input and produce the output
based on the input.
 Stream is used to make I/O operation fast.
 We can perform file handling in java by java IO API.
 A stream is a sequence of data and is composed of bytes.
 In java, 3 streams are created for us automatically.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

OutputStream
Java application uses an output stream to write data to a destination, it may be a
file,console or socket.

OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an
output stream of bytes.

FileInputStream and FileOutputStream

 FileInputStream and FileOutputStream classes are used to read and write data in file.
 FileOutputStream is an output stream for writing data to a file.

import java.io.*;
class TestIOWrite{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
String s="Testing the Java I/O";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){system.out.println(e);}
}
}

 FileInputStream classis used for reading streams of raw bytes.

import java.io.*;
class TestIORead{

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

public static void main(String args[]){


try{
FileInputStream fin=new FileInputStream("abc.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.println((char)i);
}
fin.close();
}catch(Exception e){system.out.println(e);}
}
}

ByteArrayOutputStream

 ByteArrayOutputStream class is used to write data into multiple files.


 The ByteArrayOutputStream holds a copy of data and forwards it to multiple
streams.

import java.io.*;
class BAOStream{
public static void main(String args[])throws Exception{
FileOutputStream fout1=new FileOutputStream("f1.txt");
FileOutputStream fout2=new FileOutputStream("f2.txt");

ByteArrayOutputStream bout=new ByteArrayOutputStream();


bout.write(600);
bout.writeTo(fout1);
bout.writeTo(fout2);

bout.flush();
System.out.println("success...");
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

SequenceInputStream

 SequenceInputStream class is used to read data from multiple streams unlike


ByteArrayOutputStream which writes into multiple stream.
 It reads data of streams one by one.

import java.io.*;
class SInputStreamClass{
public static void main(String args[])throws Exception{
FileInputStream fin1=new FileInputStream("f1.txt");
FileInputStream fin2=new FileInputStream("f2.txt");

SequenceInputStream sis=new SequenceInputStream(fin1,fin2);


int i;
while((i=sis.read())!=-1){
System.out.println((char)i);
}
sis.close();
fin1.close();
fin2.close();
}
}

BufferedOutputStream
 BufferedOutputStream class uses an internal buffer to store data.
 It is similar to any other OutputStream.

import java.io.*;
class Test{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("f1.txt");

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

BufferedOutputStream bout=new BufferedOutputStream(fout);


String s="Testing BufferedOutput Stream";
byte b[]=s.getBytes();
bout.write(b);

bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

BufferedInputStream
 It internally uses buffer to make the performance fast.

import java.io.*;
class TestRead{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("f1.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.println((char)i);
}
bin.close();
fin.close();

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

}catch(Exception e){system.out.println(e);}
}
}

FileWriter and FileReader


 FileWriter and FileReader classes are used to write and read data from text files.
 If you have to read and write the textual information then use the above classes.

import java.io.*;
class SimpleFileWriter{
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("abc.txt");
fw.write("Hi I am Michael Obama");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success");
}
}

Reading data from keyboard


There are many ways to read data from keyboard.

 InputStreamReader

 Console

 Scanner

 DataInputStream etc.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

InputStreamReader class
InputStreamReader class can be used to read data from keyboard.

BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.

Example of both :

import java.io.*;
class SampleIO{
public static void main(String args[])throws Exception{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Consoleclass
The Java Console class is be used to get input from console. It provides methods to read
text and password.

import java.io.*;
class ReadConsole{
public static void main(String args[]){
Console c=System.console();

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

System.out.println("Enter your name: ");


String n=c.readLine();
System.out.println("Welcome "+n);
}
}

Collections in Java
 Collections in java is a framework that provides an architecture to store and
manipulate the group of objects.
 All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Hierarchy of Collection Framework

ArrayList class
 Java ArrayList class uses a dynamic array for storing the elements.
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be


occurred if any element is removed from the array list.

import java.util.*;
class TestArrayList{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements


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

for(String obj:al) // another way of traversing elements of an arraylist


System.out.println(obj);
}
}
}

 User defined objects can also be added and traversed in the same way as any
wrapper objects.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

LinkedList class
 LinkedList class uses doubly linked list to store the elements.

 LinkedList class can contain duplicate elements.

 LinkedList class maintains insertion order.

 In Java LinkedList class, manipulation is fast because no shifting needs to be


occurred.

import java.util.*;
public class TestLinkedList{
public static void main(String args[]){

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


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

HashSet class
 It uses hashtable to store the elements.

 It contains unique elements only.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

import java.util.*;
class TestHashSet{
public static void main(String args[]){

HashSet<String> al=new HashSet<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

LinkedHashSet class
 It contains unique elements only like HashSet.

 It maintains insertion order.

TreeSet class
 It contains unique elements only like HashSet.
 It maintains ascending order.
 The objects added to TreeSet should implement Comparable interface(interface used
for sorting) else at runtime it will throw ClassCastException.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

Map Interface
 A map contains values on the basis of key i.e. key and value pair.
 Each key and value pair is known as an entry.
 Map contains only unique keys.
 Entry is the subInterface of Map.
 It will be accessed by Map.Entry name. It provides methods to get key and value.

HashMap class
 A HashMap contains values based on the key.

 It contains only unique elements.

 It may have one null key and multiple null values.

 It maintains no order.

import java.util.*;
class TestHashMap{
public static void main(String args[]){

HashMap<Integer,String> hm=new HashMap<Integer,String>();

hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

LinkedHashMap class
 It also contains only unique elements.

 It may have one null key and multiple null values.

 It is same as HashMap instead maintains insertion order.

TreeMap class
 It contains only unique elements.

 It cannot have null key but can have multiple null values.

 It is same as HashMap instead maintains ascending order on the basis of the keys.

 The keys to a TreeMap should implement Comparable interface else it will give
ClassCastExeption.

Sorting in Collection
We can sort the elements of:

1. String objects

2. Wrapper class objects

3. User-defined class objects

import java.util.*;
class TestSort{
public static void main(String args[]){

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

ArrayList<String> al=new ArrayList<String>();


al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");

Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Comparable interface
 Java Comparable interface is used to order the objects of user-defined class.
 It provide single sorting sequence only i.e. we can sort the elements on based on
single data member only.

class Student implements Comparable<Student>{


int rollno;
String name;
int age;

Student(int rollno,String name,int age){


this.rollno=rollno;
this.name=name;

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

this.age=age;
}

public int compareTo(Student st){


if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

import java.util.*;
import java.io.*;
public class SortStudentAge{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}

Comparator interface
 Java Comparator interface is used to order the objects of user-defined class.

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

 It provides multiple sorting sequence i.e. you can sort the elements on the basis of
any data member.

class Student{
int rollno;
String name;
int age;

Student(int rollno,String name,int age){


this.rollno=rollno;
this.name=name;
this.age=age;
}
}

This class defines comparison logic on age.


import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

This class defines comparison logic on name.


import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;

return s1.name.compareTo(s2.name);
}
}

import java.util.*;
import java.io.*;

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

ArrayList al=new ArrayList();


al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));

System.out.println("Sorting by Name...");

Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)
Nimble Tech
Success With Ease …
www.nimbletech.org Mail- nimbletechsolutions@gmail.com

System.out.println("sorting by age...");

Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}

www.facebook.com/nimbletech Mob: 78292-60602(Bangalore)


97786-60602(Bhubaneswar)
90380-60602(Kolkata)
90400-60602(Online)

You might also like