SlideShare uma empresa Scribd logo
1 de 53
Basics of Java
Prerequisites
For this you should have a basic knowledge of Object Oriented Principles (OOPs).
Let’s start with the basics
Object
A real world Entity which has a state and a
behavior
Class
A class is a collection of Objects. It serves as
a template for creating, or instantiating,
specific objects within a program.
E.g:- A Car class can have a model, color, manufacturedYear as
state and drive, reverse as behaviours. Ferrari is a real world
Object that we can create from that class
Fundamentals of OOP
▪ Abstraction – Hiding Internal details and showing only the functionality
Abstract classes, Interfaces are ways of achieving this
▪ Encapsulation – Binding and wrapping code and data together
Java class (having private fields and public accessors,mutators) are an
example for this
▪ Polymorphism – One task is performed in different ways
Method overriding and overloading are ways to achieve this
▪ Inheritance – One object acquires all the propertiese and behaviours of a parent
object
- Inheritance provides code reusability and used to achieve runtime polimorphism
- Java doesn’t allow multiple inheritance
Features of Java
 Simple
Syntax is based on C++
Many confusing features are removed (e.g: pointers, Multiple inheritance)
Not required to remove unreferenced objects since Automatic Garbage Collection
is there
 Portable
Write Once Run Anywhere (WORA)
 Distributed
RMI and EJB are used to create distributed Apps
 Multi Threaded
 Object Oriented
 Platform Independent
Java code is compiled by the compiler and converted into bytecode. This is
platform independent thus can be run on multiple platforms
 Secured
No pointers
Program run inside Virtual machine sandbox
 Robust
Strong (e.g:- uses strong memory management AGC)
Understand
Java platform
and
environment
Java Compilers, VM and API
Compiler
Debugger
Java Applet
Viewer
JVM
rt.jar Java.exe
libraries
JRE
JDK
JVM - Provides runtime environment in which java bytecode can be executed
JRE - Provides runtime environment. Implements JVM
JDK - Java Developer Kit contains tools needed to develop the Java programs, and JRE to
run the programs.
Basic Structure of a Java
program
public class HelloWorld{
public static void main(String[] args){
System.out.println(“Hello World”);
}
}
Access modifier Class name Method name
Argument
list(expects an
array of String
arguments)
 System is a final class in the java.lang package
 Out is a static member of System class and is an instance
of java.io.PrintStream
 Println is a method available in java.io.PrintStream class
 Here the println() method in the PrintStream class is
overridden
Few important keywords in
Java
▪ Variable - A Java variable is a piece of memory that can contain a data
value. A variable thus has a data type.
▪ Data Type – They further explain the kind of data that needs to be stored
e.g :- int, char
▪ Literals – Source code representation of a fixed value
e.g :- int age=20;
▪ Default Values – If variables are not assigned with a value then compiler
will add a value automatically
e.g :- default value for String is null, default value for boolean is false
 Identifiers – Name of the variable
 Keywords – Reserved words in java
▪ short
▪ byte
▪ int
▪ long
▪ double
▪ float
▪ char
▪ boolean
Basic Data Types in Java
Data Types
Primitive Data Types Reference Data Types
▪ Objects such as String,
Array, HashMap etc.
▪ Default value is null
▪ Reference can be used to
access the object
integer types
floating points
Operators and
Assignments
In Java
Operators
Assignment
operators
Arithmetic
operators
Relational
operators
Logical
operators
Miscellaneous
operators
Conditional Instance of
Bitwise
operators
=
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
|=
+
-
*
/
%
++
--
==
!=
>
<
>=
<=
&&
||
! ?:
&
|
^
~
<<
>>
>>>
instanceof
Loop control
and Decision
making in
Java
Decision making in java
If
e.g:-
if(num%2 ==0){
//print even
}
If-else
e.g:-
if(num%2 ==0){
//print even
}
else{
//print odd
}
If- else if - else
e.g:-
if(num%2 ==0){
//print even
}
else if(num%2 !=0){
//print odd
}
else{
//print invalid input
}
switch
e.g:-
char grade=‘A’;
switch(g){
case ‘A’ : //print ‘Pass’
break;
case ‘F’ : //print ‘Fail’
break;
default: //print ‘Invalid’
}
Loops in Java
while
e.g:-
int x=0;
while(x<words.length){
//print words[x]
x++;
}
do-while
e.g:-
int x=0;
do{
//print words[x]
x++;
} while(x<words.length);
for
e.g:-
for(int x=0 ; x<words.length ; x++){
//print words[x]
}
foreach
e.g:-
for(String word : words){
//print word
}
String words[]={“apple” , “banana”, “grapes”};
Break and Continue
keywords in Java
Break
e.g:-
int x=0;
while(x<words.length){
if(words[x].equals(“banana”)){
break;
}
else{
System.out.println(words[x]);
}
x++;
}
Continue
e.g:-
int x=0;
while(x<words.length){
if(words[x].equals(“banana”)){
continue;
}
else{
System.out.println(words[x]);
}
x++;
}
String words[]={“apple” , “banana”, “grapes”};
apple apple
grapes
OUT
Constructors in Java
 Constructor is a special type of method that is used to initialize the object
 There are rules to define a constructor
- Constructor name must be as same same as the class name
- Must not have an explicit return type
 There are two types of Constructors in Java
- Default constructor
- Parameterized constructor
 If there is no constructor in a class, compiler will automatically create a
default constructor
 Defaulot construtor will set default values for class variables wheras if
you want to set values of your own then go for a parameterized
constructor
Constructor Overloading in
Java
 A class can have any number of Constructors
 Number of parameters and type of them differentiate each one another
e.g:-
Ways to copy objects in
Java
There are three ways to copy one object to another in java
1. Copy by constructor
Ways to copy objects in
Java...
2. By assigning values of on object to another
Ways to copy objects in
Java...
3. By clone() method of Object class
Method Overloading in java
 If a class have multiple methods by same name but different parameters it
is known as ‘Method Overloading’
 Method Overloading increaces the readability of the program
 There are two ways that we can overload methods
- By changing the no of arguments
- By changing the data type
Method Overloading in
java…
e.g:- By changing the no of arguments
Method Overloading in
java…
e.g:- By changing the data type
Method Overloading in
java…
 Can we overload methods by changing their return types?
NO, method overloading cannot be achieved by changing the return type of
the methods.
e.g:- int sum(int a, int b){};
double sum(int a, int b){};
int result=sum(10,30); //Compile time error!
 Can we overload main() method of a java program?
YES. You can have any number of main methods in your java class through
method overloading. This is achieved by changing the parameters of the
main method
Method Overloading & Type
promotion
One type is promoted to another type implicitly if no matching data type is
found
byte
short
int
long
char float
double
Since no method with two int arguments are found, the compiler will automatically
considers the method with int, double (second int literal will be promoted to double)
Method Overriding in Java
 If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding
in java.
 Method overriding is used for runtime polymorphism
 Rules for method overriding in Java
- Method must have the same name as in the parent class
- Method must have same parameter as in the parent class
- There must be an IS-A relationship (inheritance)
 We can override methods by changing their return type only if their
return type is covariant (subtype of the super method’s return type)
Method Overriding in
Java… Example
•
• run() method is overridden in Bike
class with its own implementation
• super keyword is used to access
the parent class method
• During runtime it decides which
method to invoke. This is called
runtime polymorphism
• Static methods cannot be
overridden in java
• Thus main() method cannot be
overridden.
Method Overriding Vs
Method Overloading
Method Overloading Method Overriding
Used to increase the readability of the program Used to provide the specific implementation of the
method that is already provided by its super class
Is performed within the class Occurs in two classes that have an IS-A
relationship (Inheritance)
In case of method overloading, parameter must be
different
In case of method overriding, parameter must be
same
Is an example for compile time polymorphism Is an example for runtime polymorphism
In Java, method overloading cannot be performed
by changing the return type. Return type must be
same or different but you have to change the
parameter
Type must be same or Covariant in method
overriding
‘Super’ Keyword in Java
 Super is a reference variable that is used to refer immediate parent class
Object
 e.g:- When you create a Student object, a Person
object also being created automatically.
 There are three main usages of ‘super’ key word in Java
Person
Student
‘Super’ Keyword in Java…
1. ‘super’ is used to refer immediate parent class instance variable
‘Super’ Keyword in Java…
2. super() is used to invoke immediate parent class constructor
‘Super’ Keyword in Java…
3. Super is used to invoke immediate parent clas method
Access Modifiers in Java
Access Modifier Within Class Within Package
private Yes No
Default Yes Yes
Protected Yes Yes
Public Yes Yes
Note that there is no keyword call Default. A variable/
method defined without any access modifier is a
variable to any other classes in the same package.
E.g:- the fields of an interface are implicitly public static
final, the methods of an interface are by default public
Can’t apply to classes and interfaces . Fields and
methods that are marked as protected in a superclass,
only its subclasses can access them.
Access Modifiers in Java…
Where to use protected access modifier?
• If the openSpeaker() method is
marked as public, then any class
can access it.
• If openSpeaker() method is marked
as private then it is accessible only
within the AudioPlayer class
• To allow only its subclasses to use
it, we have to mark it as protected
Access control and
Inheritance
These rules must be enforced in inheritance
 Methods declared public in super class must be marked as public in all of
its subclasses
 Methods declared protected in super class can either be marked as
protected or public in its subclasses
 Methods declared private are not inherited at all, so theres no rule for
them.
Arrays in Java
 Java Array is an object that contains similar type of data
 We can store a fixed set of elements in Java Array
 Array in Java is indexed based, first element is stored at index 0.
0 1 2 3 4 indicesFirst index
Array length
Arrays in Java…
Advantages of Java Array
 Code optimization (we can retrieve or sort data easily)
 Random Access
Disadvantages
 Size limit – we can store only fixed size of elements in java array. It
doesn’t grow as we store elements at runtime
 Types of Arrays in Java
1. Single dimensional Array
2. Multidimensional Array
Arrays in Java…
Declaration syntax for single dimensional Array
dataType[] arr;
dataType []arr;
dataType arr[];
Declaration syntax for multi dimensional Array
dataType[][] arrayRefVar;
dataType [][]arrayRefVar;
dataType arrayRefVar [][];
dataType []arrayRefVar [];
Arrays in Java…
Initializing Single dimensional
Arrays in Java
int arr;
arr=new int[10];
arr[0]=23;
arr[1]=54; etc…
OR
int arr[]={23,54};
Initializing Multi dimensional
Arrays in Java
int[][] arr;
arr=new int[3][3];
arr[0][0]=10;
arr[0][1]=30;
OR
Int arr[][]={{1,2,3},{4,6,7}, …};
Collection Framework in Java
 Collection in java is a framework that provides an architecture to store
and manipulate the group of Objects
 Java collection framework provides many interfaces e.g:- Set, List, Queue,
Dequeue etc
 And classes e.g:- ArrayList, Vector, LinkedList, HashSet, TreeSet etc.
Collection Framework in Java
Hierarchy of Collection Framework
Iterator Interface
 An iterator over a collection. Iterator takes the place of Enumeration in
the Java Collections Framework. Iterators differ from enumerations in
two ways:
- Iterators allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics.
- Method names have been improved.
 This interface is a member of the Java Collections Framework.
 Methods that are available in iterator interface
- public Boolean hasNext()  returns true if iterator has more elements
- public Object hasNext()  returns the element and moves the cursor
pointer to the next element
- public void remove()  it removes the last element returned by the
iterator
Exception Handling in Java
 Exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
 In Java, Exception is an event that distrupts the normal flow of the
program. It as an Object which is thrown at runtime.
What is Exception Handling?
 It’s a mecahnism to handle runtime errors such as ClassNotFound, SQL,
Remote etc.
Advantages of Exception Handling
The core advantage of exception handling is to maintain the normal flow of
the application
Heirarchy of the Java Exception
classes
Object
Throwable
Exception Error
Checked Exception Unchecked Exception
(RuntimeException)
OutOfMemoryError
VirtusaMachineErrorIOException
ArithmeticException
NullPointerException
AssertionErrorSQLException
Types of Exceptions in Java
 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.
 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.
 Error
* Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Few examples where Exceptions
may occur
 ArithmeticException
This occurs where any number is devided by zero
int x=100/0;
 NullPointerException
If we have null value in any varible and performing any operation by the
variable causes a NullPointerException
String x=null;
System.out.println(x.length());
Few examples where Exceptions
may occur…
 NumberFormatException
The wrong formatting of any value causes this Exception
String xyz=“apple”;
int number=Integer.parseInt(xyz);
 ArrayIndexOutOfBoundsException
If a value entered in a wrong index of an array, it causes this Exception
Int arr[]=new int[5];
arr[7]=100;
Keywords used in Java Exception
handling
 try
Java try block is used to enclose the code that might throw an
Exception. It must be used within the method. Must be followed either
by catch or finally block
 catch
Java catch block is used to handle the Exception. It must be used after
the try block only.
 finally
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 must
be followed by try or catch block.
Keywords used in Java Exception
handling…
 throw
throw keyword is used to throw Exception from any method or static
block in Java
 throws
throws keyword, used in method declaration, denoted which
Exception can possible be thrown by this method.
Examples of Exception handling
using try-catch blocks
catch single Exception
Examples of Exception handling
using try-catch blocks
catch multiple Exception
Examples of Exception handling
using try-catch blocks, throw and
throws
End of Tutorial
Thank You

Mais conteúdo relacionado

Mais procurados (20)

Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
C# operators
C# operatorsC# operators
C# operators
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 

Destaque

Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
02 java basics
02 java basics02 java basics
02 java basicsbsnl007
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Model–driven system testing service oriented systems
Model–driven system testing service oriented systemsModel–driven system testing service oriented systems
Model–driven system testing service oriented systemsRifad Mohamed
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsEPAM
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesAAKASH KUMAR
 
C Programming basics
C Programming basicsC Programming basics
C Programming basicsJitin Pillai
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programmingChitrank Dixit
 
Intro to C++ Basic
Intro to C++ BasicIntro to C++ Basic
Intro to C++ BasicShih Chi Lin
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 

Destaque (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
02 java basics
02 java basics02 java basics
02 java basics
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Model–driven system testing service oriented systems
Model–driven system testing service oriented systemsModel–driven system testing service oriented systems
Model–driven system testing service oriented systems
 
Object Oriented Concepts in Real Projects
Object Oriented Concepts in Real ProjectsObject Oriented Concepts in Real Projects
Object Oriented Concepts in Real Projects
 
Java basic
Java basicJava basic
Java basic
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Intro to C++ Basic
Intro to C++ BasicIntro to C++ Basic
Intro to C++ Basic
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 

Semelhante a Basics of Java

OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Learn java
Learn javaLearn java
Learn javaPalahuja
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxDrYogeshDeshmukh1
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxIndu65
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptxRaazIndia
 

Semelhante a Basics of Java (20)

Java basics training 1
Java basics training 1Java basics training 1
Java basics training 1
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
java
java java
java
 
Learn java
Learn javaLearn java
Learn java
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Basic syntax
Basic syntaxBasic syntax
Basic syntax
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
JAVA-PPT'S.pptx
JAVA-PPT'S.pptxJAVA-PPT'S.pptx
JAVA-PPT'S.pptx
 

Último

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 

Último (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 

Basics of Java

  • 2. Prerequisites For this you should have a basic knowledge of Object Oriented Principles (OOPs). Let’s start with the basics Object A real world Entity which has a state and a behavior Class A class is a collection of Objects. It serves as a template for creating, or instantiating, specific objects within a program. E.g:- A Car class can have a model, color, manufacturedYear as state and drive, reverse as behaviours. Ferrari is a real world Object that we can create from that class
  • 3. Fundamentals of OOP ▪ Abstraction – Hiding Internal details and showing only the functionality Abstract classes, Interfaces are ways of achieving this ▪ Encapsulation – Binding and wrapping code and data together Java class (having private fields and public accessors,mutators) are an example for this ▪ Polymorphism – One task is performed in different ways Method overriding and overloading are ways to achieve this ▪ Inheritance – One object acquires all the propertiese and behaviours of a parent object - Inheritance provides code reusability and used to achieve runtime polimorphism - Java doesn’t allow multiple inheritance
  • 4. Features of Java  Simple Syntax is based on C++ Many confusing features are removed (e.g: pointers, Multiple inheritance) Not required to remove unreferenced objects since Automatic Garbage Collection is there  Portable Write Once Run Anywhere (WORA)  Distributed RMI and EJB are used to create distributed Apps  Multi Threaded  Object Oriented  Platform Independent Java code is compiled by the compiler and converted into bytecode. This is platform independent thus can be run on multiple platforms  Secured No pointers Program run inside Virtual machine sandbox  Robust Strong (e.g:- uses strong memory management AGC)
  • 6. Compiler Debugger Java Applet Viewer JVM rt.jar Java.exe libraries JRE JDK JVM - Provides runtime environment in which java bytecode can be executed JRE - Provides runtime environment. Implements JVM JDK - Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs.
  • 7. Basic Structure of a Java program public class HelloWorld{ public static void main(String[] args){ System.out.println(“Hello World”); } } Access modifier Class name Method name Argument list(expects an array of String arguments)  System is a final class in the java.lang package  Out is a static member of System class and is an instance of java.io.PrintStream  Println is a method available in java.io.PrintStream class  Here the println() method in the PrintStream class is overridden
  • 8. Few important keywords in Java ▪ Variable - A Java variable is a piece of memory that can contain a data value. A variable thus has a data type. ▪ Data Type – They further explain the kind of data that needs to be stored e.g :- int, char ▪ Literals – Source code representation of a fixed value e.g :- int age=20; ▪ Default Values – If variables are not assigned with a value then compiler will add a value automatically e.g :- default value for String is null, default value for boolean is false  Identifiers – Name of the variable  Keywords – Reserved words in java
  • 9. ▪ short ▪ byte ▪ int ▪ long ▪ double ▪ float ▪ char ▪ boolean Basic Data Types in Java Data Types Primitive Data Types Reference Data Types ▪ Objects such as String, Array, HashMap etc. ▪ Default value is null ▪ Reference can be used to access the object integer types floating points
  • 13. Decision making in java If e.g:- if(num%2 ==0){ //print even } If-else e.g:- if(num%2 ==0){ //print even } else{ //print odd } If- else if - else e.g:- if(num%2 ==0){ //print even } else if(num%2 !=0){ //print odd } else{ //print invalid input } switch e.g:- char grade=‘A’; switch(g){ case ‘A’ : //print ‘Pass’ break; case ‘F’ : //print ‘Fail’ break; default: //print ‘Invalid’ }
  • 14. Loops in Java while e.g:- int x=0; while(x<words.length){ //print words[x] x++; } do-while e.g:- int x=0; do{ //print words[x] x++; } while(x<words.length); for e.g:- for(int x=0 ; x<words.length ; x++){ //print words[x] } foreach e.g:- for(String word : words){ //print word } String words[]={“apple” , “banana”, “grapes”};
  • 15. Break and Continue keywords in Java Break e.g:- int x=0; while(x<words.length){ if(words[x].equals(“banana”)){ break; } else{ System.out.println(words[x]); } x++; } Continue e.g:- int x=0; while(x<words.length){ if(words[x].equals(“banana”)){ continue; } else{ System.out.println(words[x]); } x++; } String words[]={“apple” , “banana”, “grapes”}; apple apple grapes OUT
  • 16. Constructors in Java  Constructor is a special type of method that is used to initialize the object  There are rules to define a constructor - Constructor name must be as same same as the class name - Must not have an explicit return type  There are two types of Constructors in Java - Default constructor - Parameterized constructor  If there is no constructor in a class, compiler will automatically create a default constructor  Defaulot construtor will set default values for class variables wheras if you want to set values of your own then go for a parameterized constructor
  • 17. Constructor Overloading in Java  A class can have any number of Constructors  Number of parameters and type of them differentiate each one another e.g:-
  • 18. Ways to copy objects in Java There are three ways to copy one object to another in java 1. Copy by constructor
  • 19. Ways to copy objects in Java... 2. By assigning values of on object to another
  • 20. Ways to copy objects in Java... 3. By clone() method of Object class
  • 21. Method Overloading in java  If a class have multiple methods by same name but different parameters it is known as ‘Method Overloading’  Method Overloading increaces the readability of the program  There are two ways that we can overload methods - By changing the no of arguments - By changing the data type
  • 22. Method Overloading in java… e.g:- By changing the no of arguments
  • 23. Method Overloading in java… e.g:- By changing the data type
  • 24. Method Overloading in java…  Can we overload methods by changing their return types? NO, method overloading cannot be achieved by changing the return type of the methods. e.g:- int sum(int a, int b){}; double sum(int a, int b){}; int result=sum(10,30); //Compile time error!  Can we overload main() method of a java program? YES. You can have any number of main methods in your java class through method overloading. This is achieved by changing the parameters of the main method
  • 25. Method Overloading & Type promotion One type is promoted to another type implicitly if no matching data type is found byte short int long char float double Since no method with two int arguments are found, the compiler will automatically considers the method with int, double (second int literal will be promoted to double)
  • 26. Method Overriding in Java  If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding in java.  Method overriding is used for runtime polymorphism  Rules for method overriding in Java - Method must have the same name as in the parent class - Method must have same parameter as in the parent class - There must be an IS-A relationship (inheritance)  We can override methods by changing their return type only if their return type is covariant (subtype of the super method’s return type)
  • 27. Method Overriding in Java… Example • • run() method is overridden in Bike class with its own implementation • super keyword is used to access the parent class method • During runtime it decides which method to invoke. This is called runtime polymorphism • Static methods cannot be overridden in java • Thus main() method cannot be overridden.
  • 28. Method Overriding Vs Method Overloading Method Overloading Method Overriding Used to increase the readability of the program Used to provide the specific implementation of the method that is already provided by its super class Is performed within the class Occurs in two classes that have an IS-A relationship (Inheritance) In case of method overloading, parameter must be different In case of method overriding, parameter must be same Is an example for compile time polymorphism Is an example for runtime polymorphism In Java, method overloading cannot be performed by changing the return type. Return type must be same or different but you have to change the parameter Type must be same or Covariant in method overriding
  • 29. ‘Super’ Keyword in Java  Super is a reference variable that is used to refer immediate parent class Object  e.g:- When you create a Student object, a Person object also being created automatically.  There are three main usages of ‘super’ key word in Java Person Student
  • 30. ‘Super’ Keyword in Java… 1. ‘super’ is used to refer immediate parent class instance variable
  • 31. ‘Super’ Keyword in Java… 2. super() is used to invoke immediate parent class constructor
  • 32. ‘Super’ Keyword in Java… 3. Super is used to invoke immediate parent clas method
  • 33. Access Modifiers in Java Access Modifier Within Class Within Package private Yes No Default Yes Yes Protected Yes Yes Public Yes Yes Note that there is no keyword call Default. A variable/ method defined without any access modifier is a variable to any other classes in the same package. E.g:- the fields of an interface are implicitly public static final, the methods of an interface are by default public Can’t apply to classes and interfaces . Fields and methods that are marked as protected in a superclass, only its subclasses can access them.
  • 34. Access Modifiers in Java… Where to use protected access modifier? • If the openSpeaker() method is marked as public, then any class can access it. • If openSpeaker() method is marked as private then it is accessible only within the AudioPlayer class • To allow only its subclasses to use it, we have to mark it as protected
  • 35. Access control and Inheritance These rules must be enforced in inheritance  Methods declared public in super class must be marked as public in all of its subclasses  Methods declared protected in super class can either be marked as protected or public in its subclasses  Methods declared private are not inherited at all, so theres no rule for them.
  • 36. Arrays in Java  Java Array is an object that contains similar type of data  We can store a fixed set of elements in Java Array  Array in Java is indexed based, first element is stored at index 0. 0 1 2 3 4 indicesFirst index Array length
  • 37. Arrays in Java… Advantages of Java Array  Code optimization (we can retrieve or sort data easily)  Random Access Disadvantages  Size limit – we can store only fixed size of elements in java array. It doesn’t grow as we store elements at runtime  Types of Arrays in Java 1. Single dimensional Array 2. Multidimensional Array
  • 38. Arrays in Java… Declaration syntax for single dimensional Array dataType[] arr; dataType []arr; dataType arr[]; Declaration syntax for multi dimensional Array dataType[][] arrayRefVar; dataType [][]arrayRefVar; dataType arrayRefVar [][]; dataType []arrayRefVar [];
  • 39. Arrays in Java… Initializing Single dimensional Arrays in Java int arr; arr=new int[10]; arr[0]=23; arr[1]=54; etc… OR int arr[]={23,54}; Initializing Multi dimensional Arrays in Java int[][] arr; arr=new int[3][3]; arr[0][0]=10; arr[0][1]=30; OR Int arr[][]={{1,2,3},{4,6,7}, …};
  • 40. Collection Framework in Java  Collection in java is a framework that provides an architecture to store and manipulate the group of Objects  Java collection framework provides many interfaces e.g:- Set, List, Queue, Dequeue etc  And classes e.g:- ArrayList, Vector, LinkedList, HashSet, TreeSet etc.
  • 41. Collection Framework in Java Hierarchy of Collection Framework
  • 42. Iterator Interface  An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: - Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. - Method names have been improved.  This interface is a member of the Java Collections Framework.  Methods that are available in iterator interface - public Boolean hasNext()  returns true if iterator has more elements - public Object hasNext()  returns the element and moves the cursor pointer to the next element - public void remove()  it removes the last element returned by the iterator
  • 43. Exception Handling in Java  Exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.  In Java, Exception is an event that distrupts the normal flow of the program. It as an Object which is thrown at runtime. What is Exception Handling?  It’s a mecahnism to handle runtime errors such as ClassNotFound, SQL, Remote etc. Advantages of Exception Handling The core advantage of exception handling is to maintain the normal flow of the application
  • 44. Heirarchy of the Java Exception classes Object Throwable Exception Error Checked Exception Unchecked Exception (RuntimeException) OutOfMemoryError VirtusaMachineErrorIOException ArithmeticException NullPointerException AssertionErrorSQLException
  • 45. Types of Exceptions in Java  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.  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.  Error * Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 46. Few examples where Exceptions may occur  ArithmeticException This occurs where any number is devided by zero int x=100/0;  NullPointerException If we have null value in any varible and performing any operation by the variable causes a NullPointerException String x=null; System.out.println(x.length());
  • 47. Few examples where Exceptions may occur…  NumberFormatException The wrong formatting of any value causes this Exception String xyz=“apple”; int number=Integer.parseInt(xyz);  ArrayIndexOutOfBoundsException If a value entered in a wrong index of an array, it causes this Exception Int arr[]=new int[5]; arr[7]=100;
  • 48. Keywords used in Java Exception handling  try Java try block is used to enclose the code that might throw an Exception. It must be used within the method. Must be followed either by catch or finally block  catch Java catch block is used to handle the Exception. It must be used after the try block only.  finally 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 must be followed by try or catch block.
  • 49. Keywords used in Java Exception handling…  throw throw keyword is used to throw Exception from any method or static block in Java  throws throws keyword, used in method declaration, denoted which Exception can possible be thrown by this method.
  • 50. Examples of Exception handling using try-catch blocks catch single Exception
  • 51. Examples of Exception handling using try-catch blocks catch multiple Exception
  • 52. Examples of Exception handling using try-catch blocks, throw and throws