SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot (20)

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java basic
Java basicJava basic
Java basic
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
 
Thread presentation
Thread presentationThread presentation
Thread presentation
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Java Notes
Java NotesJava Notes
Java Notes
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 

Viewers also liked

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
 
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
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 

Viewers also liked (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
 
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
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 

Similar to 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
 

Similar to 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
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

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