Java
J2SE- Java Standard Edition --> used to develop applications
J2EE- Java Enterprise Edition --> used to develop servers.
J2ME- Java Micro Edition --> used to develop applications for mobile
applications.
We have popular Java IDEs are NetBeans, Eclipse, IntelliJ, etc.
Source code ----compiled----> Byte Code -----JVM----> Machine Code
We can enter the main method by
public class Demo{
public static void main(String args[]){
//Statements
}
}
Note: We have to give the className as File name then it is executable else we get
error in compilation.
Anatomy of JAVA Programming
class name --> Same withe the file name
Main Method --> The program is executed from the main method.
Statements --> Represents action to be done.
Statement terminator --> ;
Reserved words --> Keywords
Comments --> Can write comments Block
Class:
class [file name]{
public static void main(String args[]){
//Statements
Main:
class [file name]{
public static void main(String args[]){
//Statements
Statements:
System.out.println("Hello World");
Statement Terminator:
class [file name]{
public static void main(String args[]){
System.out.println("Hello World") ; -->Terminator
Reserved words: class, main, void, static, public, private, protected, etc.
Comments: Comments never be executed these are used to provide the information
to the coding people.
// Single line comments.
/*_______________________
_________________________*/ --> MultiLine Comments
/**_______________________*/ --> Documentation comments
Program Errors:
Syntax Errors or compilation errors: These are detected by the compiler during
compilation.
Runtime Errors:
Execution aborts or stops while Running
Logical Errors:
Everything will do good but gives a wrong output.
Data Types in JAVA
Variables--> Named computer memory location
Location have address, Bytes have address, bytes can be more than one long byte.
Declaration of dataTypes:
int, short, long, byte, bite, float, double, char, boolean
Primitive data types--> boolean, byte, char, double, float, int, long, short
Assignment operator(=)
int A=36;
initializes A value as 36
Comparison Operators:
The result of operators is always boolean
< less than
> greater than
== equal to
<= less than or equal to
>= greater than or equal to
!= not equal to
When we try to do arithmetic with different data types then the compilation error
occurs, to overcome this we can use type casting
Type Casting
Forces as values of one datatypes to be used as a value of another type.
EX:
double d=189.66;
float f=(float)189.66;
Access Modifiers
public --> Accessed by all the packages
private --> Can be accessed within the class, we can use it generating getters and
setters methods.
protected --> Can be accessed in any class by importing the package
static --> does not require initialization before it can be used and remains in the
place after use, without being destroyed.
Variable Types
Variable: Name of the location of memory used to hold a data value. Different
types of data require different amount of memory. Compiler job is to reserve
sufficient memory.
Valid Variable names
Starts with a letter (a-z or A-Z), does not allow any special characters at the
starting. For exception we can use _, $ in between the name
Followed by zero more letters, $, _, or (0-9)
Java is case sensitive language
Operations can be classified into
1. Arithmetic
2. Relational
3. Logical
4. Assignment
5. Increment and decrement
6. Conditional
7. Bitwise
8. Special
Arithmetic
+ --> Addition or unary plus
- --> subtraction or unary minus
* --> multiplication
/ --> Division
% --> Modulus division
Relational
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
!= not equal
Logical
&& --> and
|| --> or
! --> not
Increment and Decrement
++ --> increment
-- --> decrement
Conditional (Ternary)
let a and b are int
a=b? "correct" : "wrong"
if they a and b are equal prints correct else point wrong
these are user defined statements
Control Flow
if and if-else statement
if(condition){
//statement
}
if(condition){
//statement
}else {
//statement
}
switch
used instead of if-else-if
switch(expression){
case value1: //statement
break;
case valuen://statement
break;
default: //statement
Loops
Loops allows us to execute a statement multiple times, Often they are referred as
loops like conditions statements, they are controlled by boolean expressions.
Types of Loops
1. While Loop
2. do loop
3. do while loop
4. for loop
5. enhanced for loop
While Loop
while(condition){
//statements
If the condition is true statement is executed, then the condition is executed again,
if it is still true. The statement will execute untill the condition is false.
ex:
int count = 1;
while (count<=3) {
System.out.println(count);
count++;
Infinite Loops are caused due to Logical error.
The loop must eventually make condition false. If not, it is called as infinite loops
user have to interrupt program.
Nested Loops
Similar to nested if statements, loops can be nested as well body of loop contain
another loop.
For each iteration of outer loop, the loops iterate completely.
Do-While
do {
//statement
} while (condition)
The statement is executed initially and the condition is evaluated.
Similar to Opposite of while loop.
ex:
int count=0;
do {
count++;
System.out.println(count);
} while(count<3);
For Loop
for (initialization; condition; update) {
//statement
}
ex:
for (int i=0; i<=3; i++) {
System.out.println(i);
The initialization can be used to initialize or declare the variable, as like while loop
condition, for loop is tested prior. Executed zero or more times.
Access Modifier
An Access modifier specifies which class can access in a given classes and its
fields, constructors and methods.
Class, fields, constructors and methods can have one of the four different JAVA
access modifiers.
1. public
2. private
3. default
4. protected
Only class level variable can be controlled by access modifiers.
Modifiers
1. public
2. protected
3. private
NOTE: Non-inner class can only be public
Public: Can be used in any JAVA program without restriction.
Private: May only used by instance of class that declares a variable or methods or
object of the class in main method.
Protected: Only variables, methods, and inner classes can be declared as
protected. Available to all classes in the same package. Available to all subclasses
(even they are in different packages).
Private modifier
class Data{
//private variable
private String name;
public class Main{
public void main(String args[]){
//Create an object of Data
Data obj = new Data();
//accessing the variable(or) calling variables
obj.name="Programmer";
}
Getters and Setters
class Data{
private String name;
//get method
public String getName(){
return this.name;
//Set Method
public String setName(String name){
this.name=name;
return name;
public class Main{
public static void main(String args[]){
Data d=new Data();
//Accessing Getters and Setters
d.setName("Rupesh");
System.out.println(d.getName());
Public
public class Animal{
//public variable
public int legCount;
//public method
public void display(){
System.out.println(legCount);
public class Main{
public static void main(String args[]){
//accessing the public class
Animal animal = new Animal();
//accessing variable
animal.display();
Default
If we do not explicitly specify any access modifier for classes, methods, variables,
etc., then by default the default access modifier is considered.
class Logger{
void message(){
System.out.println("This is a message");
}
If we try to use the Logger class in another class outside of default package, we
will get a compilation error.
Final Modifier
Final features may not be overwritten, A final class may not be sub-classed, A final
variable cannot be changed once it has been assigned a value.
ex:
class Warlus{
int weight;
Warlus(int w){
weight=w;
class Tester{
final Warlus w1=new Warlus(1500);
void test(){
//wrong
w1=new Warlus(1400);
//correct
w1.weight=1800;
Abstract Modifier
An abstract class cannot be instantiated. This is a way to differ implementation to
subclass. Classes with one or more methods declared abstract cannot be
instantiated. A clas that is declared to implement all the methods of that interface
must be abstract.
ex:
abstract class Stock{
protected int count=0;
public abstract void push(Object O);
public abstract void pop();
public abstract Object Hop();
public abstract boolean isFull();
public boolean isEmpty(){
return count==0;
Static Modifier
Associated with a class, not a particular instance of a class
public class staticTest{
static int x=0;
staticTest(){
x++;
No matter how may instances of staticTest we have the 'x' variable is same for all.
Accessing Static Variable
staticTest st=new staticTest();
st.x=69;
//or
staticTest.x=69;
Static methods cannot use non-static features of their class.
They can access the class's static data, Since static methods are with an instance od
a class there is no "this" variable.
Static Initializers
public class Demo{
int x=5;
static {
x=69;
public static void main(String args[]){
System.out.println("x = "+ x);
} What is the value printed? --> 69
Access Modifier within class within package outside package by outside
subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Fundamentals of Characters and Strings
Characters
Building blocks of non-numeric data --> 'a', '$', '4'
String
Sequence of characters treated as Single unit may include letters, digits, special
characters, etc.
Object of class String
String name="Frankin Stein";
class String
provides nine constructors
Method length
Determine String length, String always knows their size, Strings don't have length
instance variable
ex: str.length();
Method charAt
Get character at specific location in String, str.charAt(index of char)
Method getChar
Get entire set of characters in String, str.getChars(start, firtafter, chrArray, start);
Comparing Strings
not use == ( gives true when the strings are at same address i.e., same string)
Primitives contain values, Objects contain addresses
Method equals(true if a and b are identical)
Method compareTo()
str.compareTo(str1); 0 if str and str1 are same, negative if a<b, positive if a>b.
Method regionMatches()
str.regionMatches(start, b, start, num of chars)
(true if the strings are identical)
Location of Characters and substring in Strings Search for character in String
Method indexOf()
indexOf(char), indexOf(char, start), indexOf(String), indexOf(String, start)
Method LastIndexOf()
lastIndexOf(char), lastIndexOf(chart, start)
lastIndexOf(String), lastIndexOf(string, start)
Extracting Substring from String
subString(startIndex)
subString(startIndex, endIndex)
Note: startIndex starting index is 0 and endIndex starting index is 1.
Concatenating Strings
str.contat(str1);
Miscellaneous String methods
Return modified copies of string
-replace(char, char);
-toUpperCase();
-toLowerCase();
-trim(); --> Remove all spaces at the beginning and ending of the string
Return character Array
-toCharArray();
Method valueOf()
-Returns String representation of object, data, etc.
- toString() cannot be used with primitives, but value of can.
No. Method Description
1 char charAt(int index) It returns char value for the
particular index
2 int length() It returns string length
3 static String format(String format, Object... args) It returns a formatted string.
4 static String format(Locale l, String format, It returns formatted string with
Object... args) given locale.
5 String substring(int beginIndex) It returns substring for given begin
index.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
7 boolean contains(CharSequence s) It returns true or false after
matching the sequence of char
value.
8 static String join(CharSequence delimiter, It returns a joined string.
CharSequence... elements)
9 static String join(CharSequence delimiter, It returns a joined string.
Iterable<? extends CharSequence> elements)
10 boolean equals(Object another) It checks the equality of string with
the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified string.
13 String replace(char old, char new) It replaces all occurrences of the
specified char value.
14 String replace(CharSequence old, CharSequence It replaces all occurrences of the
new) specified CharSequence.
15 static String equalsIgnoreCase(String another) It compares another string. It
doesn't check case.
16 String[] split(String regex) It returns a split string matching
regex.
17 String[] split(String regex, int limit) It returns a split string matching
regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value
index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
21 int indexOf(String substring) It returns the specified substring
index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring
index starting with given index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase
using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase
using specified locale.
27 String trim() It removes beginning and ending
spaces of this string.
28 static String valueOf(int value) It converts given type into string. It
is an overloaded method.
String Buffer
When String object is created, its contents cannot be changed.
String buffer is used for creating and manipulating dynamic String data. i.e.,
modifiable String, can store characters based on capacity-- Capacity expands
dynamically to handle additional characters.
Uses operator + and += for String concatenation.
StringBuffer Constructors
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String It creates a String buffer with the specified string..
str)
StringBuffer(int It creates an empty String buffer with the specified capacity as length.
capacity)
Modifier and Type Method Description
public synchronized append(String s) It is used to append the specified string with
StringBuffer this string. The append() method is
overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public synchronized insert(int offset, String It is used to insert the specified string with
StringBuffer s) this string at the specified position. The
insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public synchronized replace(int startIndex, It is used to replace the string from specified
StringBuffer int endIndex, String str) startIndex and endIndex.
public synchronized delete(int startIndex, int It is used to delete the string from specified
StringBuffer endIndex) startIndex and endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int It is used to ensure the capacity at least equal
minimumCapacity) to the given minimum.
public char charAt(int index) It is used to return the character at the
specified position.
public int length() It is used to return the length of the string i.e.
total number of characters.
public String substring(int It is used to return the substring from the
beginIndex) specified beginIndex.
public String substring(int It is used to return the substring from the
beginIndex, int specified beginIndex and endIndex.
endIndex)
Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable)
String. The Java StringBuilder class is same as StringBuffer class
except that it is non-synchronized. It is available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as
length.
Important methods of StringBuilder class
Method Description
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public StringBuilder It is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)
public StringBuilder delete(int It is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number
of characters.
public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int It is used to return the substring from the specified
beginIndex, int endIndex) beginIndex and endIndex.
Arrays
Array is collection of related data items.
Creating an Array
-Declare an array
-Create memory location
-Putting values to memory locations
Syntax:
- <types> [] variable_name;
ex:
Double[]myList;
Double myList[];
Both are equivalent. --> Memory is not allocated at this point.
Defining
variable name=new type[ArraySize];
ex: Number =new int[5];
MyList=new int[10];
Assigining Variables
DataType arrayName[]={List og values};
int a[]={1, 2, 3, 4, 5, 6, 7, 8, 9};
- Array index starts from 0 to (array size -1)
- int is of 4 bytes, total space = 4*arraySize;
Defining and declaring at single statement
Double []myList=new Double[10];
Reusing of Arrays
ex: Long [] primes =new Long[20];
primes[0]=2;
prime= new Long[50];
1. //Java Program to multiply two matrices
2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11.//multiplying and printing multiplication of 2 matrices
12.for(int i=0;i<3;i++){
13.for(int j=0;j<3;j++){
14.c[i][j]=0;
15.for(int k=0;k<3;k++)
16.{
17.c[i][j]+=a[i][k]*b[k][j];
18.}//end of k loop
19.System.out.print(c[i][j]+" "); //printing matrix element
20.}//end of j loop
21.System.out.println();//new line
22.}
23.}}
Vargs
Vargs is a short name for variable arguments.
Arguments of method can accept orbitary number of values, Arguments that can
accept variable number of value is called varargs
Passing Varargs in Strings
Varargs useful for any method that needs to deal with an indeterminate number of
Objects.
ex: String.format("This is an integer : %d", myInt);
String.format("This is an integer: %d and a String : %s", myInt, myString);
Parameters in varargs
Parameters are specified after the method name, inside parameters as required.
If we pass an Array to varargs and required its elements to be recognized as
individual arguments.
ex:
class varargs{
static void display(String ... values){
System.out.println("Display method is used);
OOPs
Inheritance
Terminology: Inheritance is a fundamental object oriented concept.
A class can be defined as subclass of another class
- Subclass inherits all data attributes of its superclass.
- Subclass inherits all methods of superclass.
- Subclass inherits all associations of its subclass.
The Subclass can:
- Add new functionality
- User inherited functionality
- Override inherited functionality.
What happens in Inheritance?
When an object is created using new, the system must allocate enough memory to
hold all its instance variables. This includes any instance variables.
ex:
class person{
String name="John Smith";
String dob="Jan 13, 1954";
class Employee extends person{
name="Sally Halls";
dob="Mar 15, 1968";
long empId=37518;
double sal=65000.00;
String startDate="Dec 15, 2000";
--> Employee is kind of person.
Inheritance is declared using "extends" keyword.
If Inheritance is not defined the class extends a class called object.
public class person{
private String name;
private Date dob;
public class Employee extends person{
private int empID;
private int sal;
private Date startDate;
//Accessing Inheritance for Objects
Employee anEmployee=new Employee();
Hierarchy
Inheritance creates a class hierarchy more general and more abstract.
Classes lower in hierarchy are more specific and concrete.
There is no limit to the numbers to the number of subclass a clas can have.
Constructors and Initialization
Classes use constructor to initialize instance variables. When a subclass Object is
created, its constructor is called. It is the responsibility of subclass constructor to
invoke the appropriate superclass constructor, so that the instance variables defined
in the superclass are properly initialized.
Super class constructor can be called using the "super" keyword in a manner
similar to "this". It must be the first line of code in the constructor. If a call to super
is not made the system will automatically attempt invoke the non-argument
constructor of the superclass.
ex:
public class bankAccount{
private String ownerName;
private String accountNumber;
private float Balance;
public bankAccount(int anAccountNumber, String aName){
accountNumber=anAccountNumber;
ownerName=aName;
}
}
public class overdraftAccount extends BankAccount{
private float overdraftLimit;
public BankAccount(int anAccountNumber, String aName, float aLimit){
super(anAccountNumber, aName);
overdraftLimit=aLimit;
Method Overloading
Subclass inherit all methods from their superclass, sometimes, the implementation
of the method in the superclass does not provide the functionality required by the
subclass. To Override a method, provide implementation in the subclass the
method in the subclass must have the exact same signature as the method it is
overriding.
ex:
public class BankAccount{
private String ownerName;
private int accountNumber;
protected float balance;
public void depbalosit(float anAmount){
if ( anAmount>0.0){
balance=balance+anAmount;
}
public float withdraw(float anAmount){
if(anAmount>0.0&&(balance>anAmount)){
balance=balance-anAmount;
public float getBalance(){
return balance;
public class overDrafetAccount extends BankAccount{
private float limit;
public void withdraw(float anAmount){
if(anAmount>0.0 && getBalance()+limit>anAmount){
balance=balance-anAmount;
Object Reference and Inheritance
Inheritance defines " a kind of " relationship
A superclass reference can refer to an instance of the superclass OR an instance of
ANY class which inherits from super class.
BankAccount anAccount=new BankAccount();
BankAccount account1=new OverDraftAccount(332, " ", 1000);
Final Method and Final Classes
Methods can be qualified with final modifier
- Final methods cannot be overridden.
- This can be useful for security purposes.
public final boolean validatePassword(String username, String password){
//Statements
Classes can be qualified with final modifier.
- The class cannot be extended.
- This can be used to improve performance because, there wiil be no subclass, ther
will be no poly-morphism.
public final class color{
//Statements
}
PolyMorphism
The ability to take on different forms.
- Manipulate objects of various classes and invoke methods on an object without
knowing that object's type.
Method calls and polymorphism
Assume the Dog class inherits Animal class, redefining the "Make noise" Method.
MyAnimal<--- My Dog
MyAnimal.MakeNoice();
PolyMorphism vs Inheritance
Inheritance is required in order to acquire polymorphism( we must have class
hierarchy).
-Reusing class definitions via extensions and redefinition.
Polymorphism is not required in order to acquire inheritance. An Object of Class A
acts as an Object of Class B can be ancestor to A.
Processing collections
One of the main benefits of polymorphism is the ability to easily process
collections.
We will consider cause (queue) of bank account in the next example..
Banking class hierarchy
Bank Account
/ \
Savings Account Checking Account
/ / \
Cool Savings Money market Account New Account
CD Account
Abstract and Interface
What is an Abstract class?
Abstract classes are created through process called generalization.
- Common features (methods or variables) are factored out of object classifications
(i.e. classes).
- Those features are formalized in class. This becomes the superclass.
- The classes from which the common features were taken become subclassed to
the newly created superclass.
- Often the superclass does not have a meaning or doesn't directly relate to a thing
in the real world.
- It is an artifact of the generalization process.
- Because of this, abstract cannot be instantiated. They act as place holder for
Abstraction.
Abstract classes uses
- Abstract classes are used heavily in design patterns.
- Creational patterns: Abstract class provides interface for creating objects. The
subclasses do the actual object creation.
- Structural patterns: how objects are structured is handled by an abstract class,
what the objects do is handled by the subclasses.
- The careful not to over use abstract classes.
- Abstract class increases the complexity of the design.
-Every subclass increases complexity of design.
- Ensure that you receive acceptable return in terms of functionality given the
added complexity.
Defining Abstract Class
Inheritance is declared using extends keyword
If Inheritance is not defined, the class extends a class called object.
public abstract class vehicle{
private String make;
private String mode;
private int fivecount;
public class Car extends vehicle{
private int trunkCapacity;
public class Truck extends vehicle{
private int bedCapacity;
}
Abstract Methods
- Methods can also be abstracted, An abstract method is one to which has been
provided, but no implementation for that method is given.
- An abstract method is placeholder, it means that we declare that a method must
exists, but there is no meaningful implementation for that methods within the class.
- Any class which contains an abstract method must also be abstract.
- Any Class which has an incomplete method definition cannot be instatiated.
- Abstract classes can contain both concrete and abstract methods.
If a method can be implemented within an abstract class and implementation
should be provided.
ex:
public abtract class Transacitons{
public abstract int computeValue();
//Note: no implementation.}
public class RetailSale extends Transaction{
public int computeValue(){
//Statements
public class stockTrade extends Transaction{
public int computeValue(){
//Statements
What is Interface?
- An interface is similar to an abstract class with the following exceptions.
- All methods defined in an interface are abstract. Interface can contain no
implementation.
- Interfaces cannot contain instance variable, However, they can contain public
static final variable(i.e. constant class variable).
- Interfaces are declared using the "interface" Keyword.
- If an interface is public, it must be contained in a file which has the same name.
- Interfaces are more abstract than abstract classes.
- Interfaces are implemented by class using "implements" keyword.
Declaring an Interface
public interface Steerable{
public void turnLeft(int degrees);
public void turnRight(int degrees);
public class car extends vehicle implements streerable{
public int turnLeft(int degrees){
//Statements
}
public int turnRight(int degrees){
//Statements
Implementing Interfaces
- A class can only inherit from one superclass. However, a class may implement
several interfaces.
- The interfaces taht class implements are separated by commas(,).
- Any class which implements an interface must provide implementation for all
methods defined within the interface.
NOTE: If an abstract class implements an interface, it need not to implement all
methods defined in the interface. However, each concrete subclass must implement
the methods defined in the interface.
- Interfaces can inherit method signature from others interfaces.
Declaring an Interface
public class car extends vehicle implements Steerable, Drivable{
public int turnLeft(int degrees){
//Statements
public int turnRight(int degrees){
//Statements
//implementing methods definition within the Drivable interface
}
Inheriting Interfaces
- If a superclass implements an interface its subclass also implements the interface.
public abstract class vehicle implements Steerable{
private String mmake;
public class Car extends vehicle{
private int trunkCapacity;
public class truck extends vehicle{
private int bedCapacity;
Interfaces Types
- When a class is defined, the compiler view the class as a new type.
- The same thing is true of interfaces. The compiler regards an interface as a type.
- It can be used to declare variables, methods, functionality.
int i;
car myFleet[];
Steerable anotherFleet[];
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i].turnRight(45);
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java Exception
classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following
table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.
Java Exception Handling Example
S.N. Modifier and Type Method Description
1) void start() It is used t
start th
execution o
the thread.
2) void run() It is used to d
an action for
thread.
3) static void sleep() It sleeps
thread for th
specified
amount o
time.
4) static Thread currentThread() It returns
reference t
the currentl
executing
thread object.
5) void join() It waits for
thread to die.
6) int getPriority() It returns th
priority of th
thread.
7) void setPriority() It changes th
priority of th
thread.
8) String getName() It returns th
name of th
thread.
9) void setName() It changes th
name of th
thread.
10) long getId() It returns th
id of th
thread.
11) boolean isAlive() It tests if th
thread is alive
12) static void yield() It causes th
currently
executing
thread objec
to pause an
allow othe
threads t
execute
temporarily.
13) void suspend() It is used t
suspend th
thread.
14) void resume() It is used t
resume th
suspended
thread.
15) void stop() It is used t
stop th
thread.
16) void destroy() It is used t
destroy th
thread grou
and all of it
subgroups.
17) boolean isDaemon() It tests if th
thread is
daemon
thread.
18) void setDaemon() It marks th
thread a
daemon o
user thread.
19) void interrupt() It interrupt
the thread.
20) boolean isinterrupted() It test
whether th
thread ha
been
interrupted.
21) static boolean interrupted() It test
whether th
current threa
has bee
interrupted.
22) static int activeCount() It returns th
number o
active thread
in the curren
thread's
thread group.
23) void checkAccess() It determine
if the currentl
running threa
has
permission t
modify th
thread.
24) static boolean holdLock() It returns tru
if and only
the curren
thread hold
the monito
lock on th
specified
object.
25) static void dumpStack() It is used t
print a stac
trace of th
current threa
to th
standard erro
stream.
26) StackTraceElement[] getStackTrace() It returns a
array of stac
trace
elements
representing
the stac
dump of th
thread.
27) static int enumerate() It is used t
copy ever
active thread'
thread grou
and it
subgroup int
the specifie
array.
28) Thread.State getState() It is used t
return th
state of th
thread.
29) ThreadGroup getThreadGroup() It is used t
return th
thread grou
to which thi
thread belong
30) String toString() It is used t
return a strin
representation
of this thread
including th
thread's
name, priority
and threa
group.
31) void notify() It is used t
give th
notification fo
only on
thread whic
is waiting for
particular
object.
32) void notifyAll() It is used t
give th
notification t
all waitin
threads of
particular
object.
33) void setContextClassLoader() It sets th
context
ClassLoader
for the Thread
34) ClassLoader getContextClassLoader() It returns th
context
ClassLoader
for the thread
35) static getDefaultUncaughtExceptionHandl It returns th
Thread.UncaughtExceptionHand er() default
ler handler
invoked whe
a threa
abruptly
terminates
due to a
uncaught
exception.
36) static void setDefaultUncaughtExceptionHandl It sets th
er() default
handler
invoked whe
a threa
abruptly
terminates
due to a
uncaught
exception.
Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10.}
printf
%b boolean
%c character
%d integer
%e scientific notation
%f floating point
%s String
%tc complete data and time
%n a new line
%% -%