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

Unit 2 Final Notes

The document provides an overview of Java variables, including their types (local, instance, static) and data types (primitive and non-primitive). It details the characteristics of various primitive data types such as boolean, byte, short, int, long, float, double, and char, along with their default values and sizes. Additionally, it covers Java constants, operators, and keywords, explaining their roles and usage in Java programming.

Uploaded by

vibhutimehta17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 2 Final Notes

The document provides an overview of Java variables, including their types (local, instance, static) and data types (primitive and non-primitive). It details the characteristics of various primitive data types such as boolean, byte, short, int, long, float, double, and char, along with their default values and sizes. Additionally, it covers Java constants, operators, and keywords, explaining their roles and usage in Java programming.

Uploaded by

vibhutimehta17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Unit 2

Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. It is a name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its value can be
changed.
e.g. int a = 15;
a
15

Here, in the above diagram, ‘a’ is the name given to the starting address of the memory where 15
is stored.
Types of Variables
There are three types of variables in Java:
• local variable
• instance variable
• static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example 0-1 types of variables in java
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Types of Data
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. There are 8 types of primitive data types:
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. The Boolean data type specifies one bit of
information, but its "size" can't be defined precisely.
Example: Boolean one = false;
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:
byte a = 10, b = -20 ;
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
Example:
short s = 10000, r = -5000;
int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
int a = 100000, b = -200000;
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
long a = 100000L, b = -200000L;
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0F.
Example:
float f1 = 234.5f;
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double
data type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3 ;
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or
0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A' ;
Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of
Unicode system.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:
A particular code value corresponds to different letters in the various language standards.
The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System. In unicode,
character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
The default values and size of primitive data-types are listed in the Table 2.1
Table 0.1Default values and size of primitive data-types

Data Type Default Value Default size


boolean false 1 bit
Char '\u0000' 2 byte
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d byte

Java Constants
Constants have a name like variables and store a certain type of information but unlike variables
they CANNOT change.
Format:
final <constant type> <CONSTANT NAME> = <value>;
Example:
final int SIZE = 100;
Why use constants ?
They make your program easier to read and understand
populationChange = (0.1758 – 0.1257) * currentPopulation;
Vs.
final float BIRTH_RATE = 17.58;
final float MORTALITY_RATE = 0.1257;
int currentPopulation = 1000000;
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;
It can make your program easier to maintain (update with changes).
If the constant is referred to several times throughout the program, changing the value of the
constant once will change it throughout the program.
Example Java Constants

Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Table 0.2 Types of Operators

Operator Type Category Precedence Associativity


Unary postfix expr++ expr-- Right to left
prefix ++expr --expr +expr - Right to left
expr ~ !
Arithmetic multiplicative */% Left to Right
additive +- Left to Right
Shift shift << >> >>> Left to Right
Relational comparison < > <= >= instanceof Left to Right
equality == != Left to Right
Bitwise bitwise AND & Left to Right
bitwise exclusive OR ^ Left to Right
bitwise inclusive OR | Left to Right
Logical logical AND && Left to Right
logical OR || Left to Right
Ternary ternary ?: Left to Right
Assignment assignment = += -= *= /= %= &= ^= Right to left
|= <<= >>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Example : ++ and –
Example ~ and !
Java Arithmetic Operators
Java arithmatic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Example : Arithmetic Operators

Example 0: Expression
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Example : Left Shift Operator

Java Right Shift Operator


The Java right shift operator >> is used to move left operands value to right by the number of bits
specified by the right operand.
Example : Right Shift Operator

Java Shift Operator


Example : >> vs >>>
Java AND Operator
The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
Example : Logical && and Bitwise &

Example : Logical && vs Bitwise &


Java OR Operator
The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false. The bitwise | operator always checks both conditions whether
first condition is true or false.
Example : Logical || and Bitwise |

Java Ternary Operator


Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in
Java programming. it is the only conditional operator which takes three operands.
Example : Ternary Operator
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the value on its
right to the operand on its left.
Example : Assignment Operator
Example : Adding short

Example : After Type casting

Java Keywords
Java keywords are also known as reserved words. Keywords are particular words which acts as
a key to a code. These are predefined words by Java so it cannot be used as a variable or object
name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
• abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide
the implementation of interface. It can have abstract and non-abstract methods.
• boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
• break: Java break keyword is used to break loop or switch statement. It breaks the current
flow of the program at specified condition.
• byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
• case: Java case keyword is used to with the switch statements to mark blocks of text.
• catch: Java catch keyword is used to catch the exceptions generated by try statements. It
must be used after the try block only.
• char: Java char keyword is used to declare a variable that can hold unsigned 16-bit
Unicode characters
• class: Java class keyword is used to declare a class.
• continue: Java continue keyword is used to continue the loop. It continues the current flow
of the program and skips the remaining code at the specified condition.
• default: Java default keyword is used to specify the default block of code in a switch
statement.
• do: Java do keyword is used in control statement to declare a loop. It can iterate a part of
the program several times.
• double: Java double keyword is used to declare a variable that can hold a 64-bit floating-
point numbers.
• else: Java else keyword is used to indicate the alternative branches in an if statement.
• enum: Java enum keyword is used to define a fixed set of constants. Enum constructors
are always private or default.
• extends: Java extends keyword is used to indicate that a class is derived from another class
or interface.
• final: Java final keyword is used to indicate that a variable holds a constant value. It is
applied with a variable. It is used to restrict the user.
• finally: Java finally keyword indicates a block of code in a try-catch structure. This block
is always executed whether exception is handled or not.
• float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
• for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some conditions become true. If the number of
iteration is fixed, it is recommended to use for loop.
• if: Java if keyword tests the condition. It executes the if block if condition is true.
• implements: Java implements keyword is used to implement an interface.
• import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
• instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
• int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
• interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
• long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
• native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
• new: Java new keyword is used to create new objects.
• null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
• package: Java package keyword is used to declare a Java package that includes the classes.
• private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
• protected: Java protected keyword is an access modifier. It can be accessible within
package and outside the package but through inheritance only. It can't be applied on the
class.
• public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
• return: Java return keyword is used to return from a method when its execution is
complete.
• short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
• static: Java static keyword is used to indicate that a variable or method is a class method.
The static keyword in Java is used for memory management mainly.
• strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
• super: Java super keyword is a reference variable that is used to refer parent class object.
It can be used to invoke immediate parent class method.
• switch: The Java switch keyword contains a switch statement that executes code based on
test value. The switch statement tests the equality of a variable against multiple values.
• synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
• this: Java this keyword can be used to refer the current object in a method or constructor.
• throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exception. It is followed by an instance.
• throws: The Java throws keyword is used to declare an exception. Checked exception can
be propagated with throws.
• transient: Java transient keyword is used in serialization. If you define any data member
as transient, it will not be serialized.
• try: Java try keyword is used to start a block of code that will be tested for exceptions. The
try block must be followed by either catch or finally block.
• void: Java void keyword is used to specify that a method does not have a return value.
• volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
• while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to use
while loop.

Control Statements
Java conditional statements allow you to make a decision, based upon the result of a condition.
These statements are called Decision Making Statements or Conditional Statements.
Figure : Control Statements
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false. There
are various types of if statement in Java.
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
• Java if Statement

“If statement” in C is used to control the program flow based on some condition, it's used to execute
some statement code block if the expression is evaluated to true. Otherwise, it will get skipped.
This is the simplest way to modify the control flow of the program.
Example : if statement
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.

Example : If -Else Statement

Example : Leap Year


Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Figure : If –else ladder

Example 0-1 if else ladder


Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.

Example : Nested If

Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-
if ladder statement. The switch statement works with byte, short, int, long, enum types, String and
some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch
statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only. The case value must be literal or constant.
It doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is not
found, it executes the next case.
The case value can have a default label which is optional.
Figure : Switch Statement
Example : Switch Statement
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match
if a break statement is not present.
Example : Break Statement

Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in Java.
• for loop
• while loop
• do-while loop
Figure : Loops in Java
Table 0.3 Comparison between Types of Loops

Comparison for loop while loop do while loop


Introduction The Java for loop is a The Java while loop is a The Java do while
control flow statement that control flow statement loop is a control
iterates a part of that executes a part of the flow statement that
the programs multiple programs repeatedly on executes a part of
times. the basis of given boolean the programs at
condition. least once and the
further execution
depends upon the
given boolean
condition.
When to use If the number of iteration is If the number of iteration If the number of
fixed, it is recommended to is not fixed, it is iteration is not
use for loop. recommended to use fixed and you must
while loop. have to execute the
loop at least once,
it is recommended
to use the do-while
loop.
Syntax for(init;condition;incr/decr while(condition){ do{
){ //code to be executed //code to be
// code to be executed } executed
} }while(condition);
Example //for loop //while loop //do-while loop
for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
} System.out.println(i); System.out.println
i++; (i);
} i++;
}while(i<=10);
Syntax for for(;;){ while(true){ do{
//code to be executed //code to be executed //code to be
infinitive loop
} } executed
}while(true);

Java For Loop


The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop.
There are three types of for loops in java.
• Simple For Loop
• For-each or Enhanced For Loop
• Labeled For Loop

Java Simple For Loop


A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
Condition: It is the second condition which is executed each time to test the condition of the loop.
It continues execution until the condition is false. It must return boolean value either true or false.
It is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Example : For loop

Java Nested For Loop


If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
Example : Nested For loop

Java for-each Loop


The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.

Example : For Each Loop


Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful
if we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.

Example : Labelled For Loop

If you use break bb;, it will break inner loop only which is the default behavior of any loop.
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Example: Infinite For Loop

Now, you need to press ctrl+c to exit from the program.


Java While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop.

Example : While Loop


Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.

Example : Infinite While Loop

Now, you need to press ctrl+c to exit from the program.


Java do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use
do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Example : Do While Loop

Java Infinitive do-while Loop


If you pass true in the do-while loop, it will be infinitive do-while loop.
Example : Infinite Do- While Loop

Now, you need to press ctrl+c to exit from the program.


Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.

Example : Java Break Statement with Loop


Example: Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Java Break Statement with Labeled For Loop
We can use break statement with a label. This feature is introduced since JDK 1.5. So, we can
break any loop in Java now whether it is outer loop or inner.
Example: Java Break Statement with Labeled For Loop

Java Break Statement in while loop


Example: Java Break Statement in while loop
Java Break Statement in do-while loop
Example : Java Break Statement in do-while loop

Java Continue Statement


The continue statement is used in loop control structure when you need to jump to the next iteration
of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while
loop.
Example : Java Continue Statement

As you can see in the above output, 5 is not printed on the console. It is because the loop is
continued when it reaches to 5.
Java Continue Statement with Inner Loop
It continues inner loop only if you use the continue statement inside the inner loop.
Example : Java Continue Statement with Inner Loop
Java Continue Statement with Labeled For Loop
We can use continute statement with a label. This feature is introduced since JDK 1.5. So, we can
continue any loop in Java now whether it is outer loop or inner.
Example: Java Continue Statement with Labeled For Loop

Java Continue Statement in while loop


Example: Java Continue Statement in while loop
Java Continue Statement in do-while loop
Example 0-2 Java Continue Statement in do-while loop

Java Comments
The Java comments are the statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement. It can also be used to hide program code.
Types of Java Comments
There are three types of comments in Java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Figure: Types of Comments
(1) Java Single Line Comment
The single line comment is used to comment only one line.

Example 0-1 Java Single Line Comment

2) Java Multi Line Comment


The multi line comment is used to comment multiple lines of code.
Example 0-2 Java Multi Line Comment
3) Java Documentation Comment
The documentation comment is used to create documentation API. To create documentation API,
you need to use javadoc tool.

Example 0-3 Java Documentation Comment


Now, there will be HTML files created for your Calculator class in the current directory. Open the
HTML files and see the explanation of Calculator class provided through documentation comment.

Objects and classes in Java


Object: A real time entity in world is known as object. Examples are Table, Fan, chair, Car, bag,
board, apple, Book, Bike, Pen, Person, Institute, and Bank etc.
Each object must have the following attributes:
1. State: The state of an object is the data members of that object like name, address , phone
number of a Person Object.
2. Behavior: It represents the methods or member functions which gives the information how that
object performs tasks on the data members. Like getName(), setName(), getDetails(), putDetails()
of the Person object.
3. Identity: Each object has its unique id which is used by the Java Virtual Machine while
processing that object. The Object Id is not visible to the user.

Figure : Object Characteristics


An object could also be defined as an instance of the class.
Class:A class is a user defined data type which consists of two fields: data members and methods
(member functions).
There is small difference in the syntax of class in java and c++. The class definition in java does
not end with semicolon as was the case in c++ and also the main function has also be defined
inside the class due pure object oriented characteristics of java.
General syntax of class in java is as follows:
class Demo
{
// data member section
Int x;
Int y; //data members;
// member functions or methods
void show();
}

Difference between C++ class and Java class


C++ class Java Class
Definition ends with a semicolon Definition of a Java class does not require
semicolon (;) at the end
We call functions of a class as member functions We call member functions as methods
By default class protection mode was private By default Protection mode is default not
private
The protection modes were used as block like Here the protections modes are not specified
Class Demo as block
{ Class Demo
private: {
Int x; private int x;
Void add(); private void add();
public: public int y;
Int y; public void show();
Void show(); }
};
main() function was defined outside the class The main() function also has to be part of any
class i.e. main() will be defined inside the
class.
Creating object in c++ is a one-step only In Java Object creation follows two steps
Demo d1; Demo d1; here d1 is just a reference variable
D1=new Demo(); now the memory is allocated
to the data members of the class.
Types of variables in Class
Example: Types of variables
Class Demo
{
Private int x;
Public int y;
int z;
static int a,b;
private void add();
public int y;
public void show()
{
Int t1, t2;
}
};
Instance Variable:
The non-static data members of the class are known as instance variable. These are associated to
individual instance / object of the class.
In the above example the variables x, y, and z are non-static data members of class Demo and
known as instance variables.
Local Variable:
These are variables which are declared inside methods or member functions of the class are known
as local variable. Variable t1 and t2 which are declared inside the function show are local variables.
Class variable:
The static data members of the class are known as class variables because these are associated with
the class as a whole and independent of a particular object. A single copy of such variables will be
shared among different objects. Variable a and b in the above class are known as class variables
because these are declared as static data members inside the class. The memory to such variables
will be allocated once and that memory will be shared by all the objects of this class.
Instantiation or Object Creation of Class
The process of creating the objects of class is known as class instantiation. Here the word instance
and object are used interchangeable i.e. having similar meaning.
Class Box
{
int width;
int height;
int depth;
voidgetData()
{
}
Void putData()
{
}
}
The object creation is of two steps:
Step-1: Declare a reference variable
Box mybox;
Step-2:
Using new operator and class constructor create the memory for the data members of the class and
assign that memory to the reference variable created in step-1.
mybox=new Box();

Figure : Object Creation in Java


In Java the primitive data types like int , char, float, double etc. are not implemented as Objects so
to create memory for them there is no need to use new operator. This feature of java enhances the
processing speed of primitive data types in java. Also because of this reason the Java language is
not 100% pure object oriented language. Although in 2nd version of Java , wrapper classes were
introduced which enables the programmer to convert primitive data types to objects and vice versa.
So the class is creates the logical framework or blueprint of the structure whereas the Object is the
physical form of the class. This could also be interpreted as class a passive entity and object as
active entity.
Object Reference Assignment
Box b1=new Box();
Box b2;
b2=b1;
Two reference variables have been created in the above statements as b1 and b2.
b1 variable has allocated memory address of the data members of the class Box where as b2 is
referring to null. In third statement we assigned b1 to b2. It means that where reference variable
b1 is referencing now b2 is also referring to the same memory as shown in Figure 4 below

Figure : Reference Variable assignment


If b1 is set to null
b1=null;
then still b2 refers to the object .
Adding Methods or functions to the class
The class has two sections : data members and methods. The user can skip any of these sections.
To add methods in a class is a simple process.
class Demo
{
Int x;
Int y;
Int z;
voidgetData()
{
}
int add(int a, int b, int z)
{
return(a+b+c);
}
voidputData()
{
}
}
The above code consists of three data members as x,y, z and three methods as getData() add(int
x, int y, intz), putData().
The methods could also have parameters like add(int x, int y, int z) or without parameters like
getData() and putData().
To access data members or methods outside the class the user should use object along with dot
operator and data member or method name.
Constructor
A constructor is a special type of method defined inside the class. It has certain features :
1. Name of constructor has to be the same as that of the class.
2. Has no return type not even void
3. Gets called automatically as soon as object is created
4. Can not be static
5. Can not be abstract
6. Can not be final
7. Can not be synchronized
Types of Constructor:
There are two types of constructors as constructor with no parameters (Default) and parameterized
constructor
Example below shows default as well as parametrized constructors.
Class Student
{
String name;
introllno;
Student() // Constructor having no arguments
{
name=null;
rollno=0;
}
// Parameterized Constructor with two parameters
Student(String s1, int r)
{
name=s1;
rollno=r;
}
public static void main(String arg[])
{
Student s1=new Student(); // Calls the default constructor
Student s2=new Student(“Ravi”,150); // calls the parameterized constructor
}
What if you implement only parameterized constructor in class
classDemo
{
privateintvar;
publicDemo(intnum) // Parametrized constructor
{
var=num;
}
publicintgetValue()
{
returnvar;
}
publicstaticvoid main(Stringargs[])
{
Demomyobj = newDemo();
System.out.println("value of var is: "+myobj.getValue());
}
}
It will throw a compilation error. The reason is, the statement Demomyobj = new Demo3() is
invoking a default constructor which we don’t have in our program. when you don’t implement
any constructor in your class, compiler inserts the default constructor into your code, however
when you implement any constructor (in above example I have implemented parameterized
constructor with int parameter), then you don’t receive the default constructor by compiler into
your code.
If we remove the parameterized constructor from the above code then the program would run fine,
because then compiler would insert the default constructor into your code.
Constructor Chaining
The process of calling a constructor from another constructor of the same class is called constructor
chaining.
The real purpose of Constructor Chaining is that you can pass parameters through a bunch of
different constructors, but only have the initialization done in a single place. This allows you to
maintain your initializations from a single location, while providing multiple constructors to the
user. If we don’t chain, and two different constructors require a specific parameter, you will have
to initialize that parameter twice, and when the initialization changes, you’ll have to change it in
every constructor, instead of just the one.

Figure : Constructor chaining


The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-Java resource such as a file handle or window character font, then you
might want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you can define
specific actions that will occur when an object is just about to be reclaimed by the garbage
collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls that
method whenever it is about to recycle an object of that class. Inside the finalize( ) method you
will specify those actions that must be performed before an object is destroyed. The garbage
collector runs periodically, checking for objects that are no longer referenced by any running state
or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls
the finalize( ) method on the object.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside
its class.
It is important to understand that finalize( ) is only called just prior to garbage collection. It is not
called when an object goes out-of-scope, for example. This means that you cannot know when—
or even if—finalize( ) will be executed. Therefore, your program should provide other means of
releasing system resources, etc., used by the object. It must not rely on finalize( ) for normal
program operation
Using the ‘this’ Keyword
Within an instance method or a constructor, this is a reference to the current object — the object
whose method or constructor is being called. You can refer to any member of the current object
from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method
or constructor parameter.
For example, the Point class was written like this
public class Point {
publicint x = 0;
publicint y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Each argument to the constructor shadows one of the object's fields — inside the constructor x is
a local copy of the constructor's first argument. To refer to the Point field x, the constructor must
use this.x.
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the
same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class,
with a different implementation from the one in the Objects section.
public class Rectangle {
privateint x, y;
privateint width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's
member variables. The constructors provide a default value for any member variable whose initial
value is not provided by an argument. For example, the no-argument constructor creates a
1x1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument
constructor, passing in the width and height but always using the 0,0 coordinates. As before, the
compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.
classEmployee
{
publicStringempName;
publicintempSalary;
publicString address;
//default constructor of the class
publicEmployee()
{
//this will call the constructor with String param
this("Chaitanya");
}
publicEmployee(String name)
{
//call the constructor with (String, int) param
this(name,120035);
}
publicEmployee(String name,intsal)
{
//call the constructor with (String, int, String) param
this(name,sal,"Gurgaon");
}
publicEmployee(String name,intsal,Stringaddr)
{
this.empName=name;
this.empSalary=sal;
this.address=addr;
}
voiddisp(){
System.out.println("Employee Name: "+empName);
System.out.println("Employee Salary: "+empSalary);
System.out.println("Employee Address: "+address);
}
Public static void main(String[]args)
{
Employee obj=newEmployee();
obj.disp();
}
}
Output:
EmployeeName:Chaitanya
EmployeeSalary:120035
EmployeeAddress:Gurgaon

Initializing an Object
Here's the code for the Point class:
public class Point {
publicint x = 0;
publicint y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor in the Point class takes
two integer arguments, as declared by the code (int a, int b). The following statement provides 23
and 94 as values for those arguments:
Point originOne = new Point(23, 94);

Figure 0-1 Object initialization


Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a
particular method. There are two levels of access control:
At the top level—public, or package-private (no explicit modifier).
At the member level—public, private, protected, or package-private (no explicit modifier).
A class may be declared with the modifier public, in which case that class is visible to all classes
everywhere. If a class has no modifier (the default, also known as package-private), it is visible
only within its own package (packages are named groups of related classes — you will learn about
them in a later lesson.)
At the member level, you can also use the public modifier or no modifier (package-private) just
as with top-level classes, and with the same meaning. For members, there are two additional access
modifiers: private and protected. The private modifier specifies that the member can only be
accessed in its own class. The protected modifier specifies that the member can only be accessed
within its own package (as with package-private) and, in addition, by a subclass of its class in
another package.
The following table shows the access to members permitted by each modifier.
Table: Access Levels

Access Levels

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

The first data column indicates whether the class itself has access to the member defined by the
access level. As you can see, a class always has access to its own members. The second column
indicates whether classes in the same package as the class (regardless of their parentage) have
access to the member. The third column indicates whether subclasses of the class declared outside
this package have access to the member. The fourth column indicates whether all classes have
access to the member.
Access levels affect you in two ways. First, when you use classes that come from another source,
such as the classes in the Java platform, access levels determine which members of those classes
your own classes can use. Second, when you write a class, you need to decide what access level
every member variable and every method in your class should have.
Let's look at a collection of classes and see how access levels affect visibility. The following
figure shows the four classes in this example and how they are related.

Figure :Multi Package Access control


Figure: Classes and Packages of the Example Used to Illustrate Access Levels
The following table shows where the members of the Alpha class are visible for each of the access
modifiers that can be applied to them.
Table : Visibility

Visibility

Modifier Alpha Beta Alphasub Gamma

Public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

Private Y N N N

Function/ Method Overloading


The process of defining multiple functions having same name but with different arguments and
their types within a single class is known as function overloading. Method overloading is one of
the ways that Java implements polymorphism. If you have never used a language that allows the
overloading of methods, then the concept may seem strange at first. But as you will see, method
overloading is one of Java’s most exciting and useful features. When an overloaded method is
invoked, Java uses the type and/or number of arguments as its guide to determine which version
of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or
number of their parameters. While overloaded methods may have different return types, the return
type alone is insufficient to distinguish two versions of a method. When Java encounters a call to
an overloaded method, it simply executes the version of the method whose parameters match the
arguments used in the call.
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result; // call all versions of test()
ob.test(); ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Inheritance
The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique features and rest of the
common properties and functionalities can be extended from the another class.
Child Class / Derived class / Sub class:
The class that extends the features of another class is known as child class, sub class or derived
class.
Parent Class / Base Class:
The class whose properties and functionalities are used(inherited) by another class is known as
parent class, super class or Base class.
Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class
need not be rewritten in the child class.
How to do inheritance in Java
For inheriting one class from another the keyword extends is used. The general syntax for
inheritance is as follows:
Class Derived_class extends base_class
{
}
Example :
class Animal {
// methods and fields
}
// use of extends keyword
// to perform inheritance
class Dog extends Animal {
// methods and fields of Animal
// methods and fields of Dog
}
Example :
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle {
// the MountainBike subclass adds one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass adds one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a
method to set it. Except for the constructor, it is as if you had written a new MountainBike class
entirely from scratch, with four fields and five methods. However, you didn't have to do all the
work. This would be especially valuable if the methods in the Bicycle class were complex and had
taken substantial time to debug.
A subclass inherits all of the public and protected members of its parent, no matter what package
the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-
private members of the parent. You can use the inherited members as is, replace them, hide them,
or supplement them with new members:
The inherited fields can be used directly, just like any other fields.
You can declare a field in the subclass with the same name as the one in the superclass,
thus hiding it (not recommended).
You can declare new fields in the subclass that are not in the superclass.
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the one in the
superclass, thus overriding it.
You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
You can declare new methods in the subclass that are not in the superclass.
You can write a subclass constructor that invokes the constructor of the superclass, either implicitly
or by using the keyword super.
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another
class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the
child class.For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which
means a child class has two parent classes. For example class C extends both classes A and B. Java
doesn’t support multiple inheritance.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For
example class A & B extends class C and another class D extends class A then this is a hybrid
inheritance example because it is a combination of single and hierarchical inheritance.
Note : java does not support multiple inheritance which means in java inheriting more than one
base class into a single child class at once is not allowed.
class child extends Base1, Base2 // this is not allowed in java
{
}
To perform multiple inheritance in java, a new concept has been added known as Interface.
Interface
In the Java programming language, an interface is a reference type, similar to a class, that can
contain only constants, method signatures, default methods, static methods, and nested types.
Method bodies exist only for default methods and static methods. Interfaces cannot be
instantiated—they can only be implemented by classes or extended by other interfaces. Extension
is discussed later in this lesson. Defining an interface is similar to creating a new class:
public interface OperateCar {
// constant declarations, if any
// method signatures
// An enum with values RIGHT, LEFT
int turn(Direction direction,
double radius,
double startSpeed,
double endSpeed);
int changeLanes(Direction direction,
double startSpeed,
double endSpeed);
int signalTurn(Direction direction,
boolean signalOn);
int getRadarFront(double distanceToCar,
double speedOfCar);
int getRadarRear(double distanceToCar,
double speedOfCar);
......
// more method signatures
}
Note that the method signatures have no braces and are terminated with a semicolon.
It means an interface can have constant data members which are final and static in nature along
with method declarations only. The definition of such methods will be given by the class inheriting
the interface. All methods and data mebers in an interface are by default public in nature, that is
why when such methods are to be defined in the class they have to use public modifier.
How class inherits an interface
The keyword used to inherit the interface in the class is implements.
Example
interface A
{
int x=20; // this variable is static and final similar to final int x=20; its value can not be changed
void show(); // this method is abstract
}
class Demo implements A
{
int a=30;
public void show()
{
System.out.println(“the value of x and a are …..”+x+a);
}
public static void main(String arg[])
{
Demo d1=new Demo();
d1.show();
}
}
Any class implementing the interface has to provide the body to all the methods declared in the
interface. Even if a single method (declared in interface) is not defined in the class inheriting the
interface, then the class becomes abstract and can not be instantiated. So it is mandatory to define
all the methods declared in the interface by the class inheriting it .
In JDK8 a new type of method is allowed to be defined in interface known as default methods.
Such methods are preceded by default keyword as follows:
interface Test
{
void show();
default void display()
{
}
}
Partial implementation
The process in which a class implements only specific methods of an interface and leaves other
methods as abstract is called partial implementation.
interface Test {
int a=20, b=30;
void add();
voiod sub();
void divide();
}
class Demo
{
public void add()
{
int sum=a+b;
System.out.println(“sum is….”+sum);
}
public void sub()
{
int sub=a-b;
System.out.println(“Subtraction is….”+sub);
}
}
In the above example the interface Test have three methods and the class Demo have implemented
only two methods. So the class demo becomes abstract. This situation is known as partial
implementation as one method of the interface still left undefined by the class.
Inheritance among interfaces
One interface can also inherit another interfaces. The keyword extends will be used when one
interface inherits another interface. In interfaces the multiple inheritance is also possible which
means one interface can inherit more than one interfaces at onec.
interface A
{
int x=10;
void add();
}
interface B
{
int y=20;
void sub();
}
interface C extends A, B // multiple inheritance in interfaces is allowed
{
int z=30;
}

Figure 0-1 Use of extends and implements keyword


Figure 2.17 shows how the inheritance occurs among classes and interfaces.
Inheritance of class and interface( Multiple inheritance)
In Java a class can at most extends one base class and more than one interfaces at once.
interface A
{
int x=10;
void add();
}
interface B
{
int y=20;
void sub();
}
class Base
{
int a=30;
void show()
{
System.out.println(“Base class method…..”);
}
}
class Derived extends Base implements A, B
{
public void add()
{
int sum =x+a+y;
System.out.println(“sum is….”+sum);
}
public void sub()
{
int sub =x-(a+y);
System.out.println(“sub is….”+sub);
}
Void show()
{
add();
sub();
}
public static void main(String arg[])
{
Child c1=new Child();
c1.show();
}
}
The above program shows how a single class inherits another class along with interfaces. This is
an example of multiple inheritance in java.
Using Super
The keyword super has two main applications in Java.
Calling super class constructors
The first calls the superclass constructor.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob)
{
// pass object to constructor
width = ob.width; height = ob.height; depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1;
// use -1 to indicate
height = -1;
// an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return
volume double volume()
{
return width * height * depth;
}
} // BoxWeight now fully implements all constructors.
class BoxWeight extends Box
{
double weight;
// weight of box // construct clone of an object
BoxWeight(BoxWeight ob)
{
// pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight()
{
super(); // call to base class default constructor
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m)
{
super(len); // call to parameterized constructor
weight = m;
}
}
class DemoSuper
{
public static void main(String args[])
{
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight();// default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol; vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol =
mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); vol =
mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println(); vol =
myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight); System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight); System.out.println();
}
}
Another Use of Super Keyword
// Using super to overcome name hiding.
The second form of super acts somewhat like this, except that it always refers to the superclass of
the subclass in which it is used.
class A
{
int i;
}
// Create a subclass by extending class A.
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
Constructors calling sequence
In case of multilevel inheritance in Java the calling sequence of constructors will be from super
Base class, Base Class, Child class, sub Child class and so on.
class A
{
A()
{
System.out.println("Inside A's constructor.");
}
}
class Ba extends A
{
B()
{
System.out.println("Inside B's constructor.");
}
}
class c extends B
{
C()
{
System.out.println("Inside C's constructor.");
}
}
class Test
{
Public static void main(String arg[])
{
C c1=new C();
}
}
The output will be :
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
Dynamic Method Dispatch / Dynamic Polymorphism
Java does not consists of pointers and so there is no concept of virtual function in java.
Java has reference variables. A reference variable of a Base class can refer to its sub class objects
which helps Java to resolve the calls to the overridden methods at run time. Resolving the calls to
overridden methods at run time is known as run time polymorphism. . When an overridden method
is called through a superclass reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. When different types of objects are referred to, different
versions of an overridden method will be called.
// Dynamic Method Dispatch
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{ // override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type
A r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Abstract Class
Any class that contains one or more abstract methods must also be declared abstract. To declare a
class abstract, you simply use the abstract keyword in front of the class keyword at the beginning
of the class declaration. There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Such objects would be useless, because an
abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static
methods. Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be itself declared abstract.
class A
{
abstract void callme(); //
concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B(); b.callme(); b.callmetoo();
}
}
Final Keyword
The final keyword can be used with a variable, method and class.
Variable as final
In Java instead of const keyword, final is used to make the variable as constant.
final int x=20; // once value initialized can not be modified.
Method as final
If the keyword final is used with the method then that method can not be overridden in sub class.

class Demo
{
final void add(int x, int y)
{
int sum =x+y;
}
}
class child extends Demo
{
Void add(int a, int b)// error because the method was final in the base class
{
}
}
Class as Final
If the user add final keyword with the class definition then that class can never be inherited. It is
opposite of abstract class. The abstract class has to be extended so instantiate where as a final class
can never be extended.
Exception Handling in Java
The 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.
What is Exception in Java
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the
rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.
Hierarchy of Java Exception classes:
The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by
two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

Figure : A hierarchy of Java Exception classes


Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as
the unchecked exception. According to Oracle, there are three types of exceptions:
• Checked Exception
• Unchecked Exception
• Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known
as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Table: Keywords in Exception Handling

Keyword Description
Try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
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 important 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 doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling where we using a try-catch statement to handle
the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Problem without exception handling
Let's try to understand the problem if we don't use a try-catch block.
Example 1
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is not executed (in such case, the rest of
the code statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Example 2
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Now, as displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3
In this example, we also kept the code in a try block that will not throw an exception.
public class TryCatchExample3 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not
execute.
Example 4
Here, we handle the exception using the parent class exception.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
catch(Exception e)
{
System.out.println("Can't divided by zero");
}
}
}
Output:
Can't divided by zero
Example 6
Let's see an example to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in a catch block.
public class TryCatchExample7 {
public static void main(String[] args) {
try
{
int data1=50/0; //may throw exception
}
catch(Exception e)
{
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose exception code
within a try block and use catch block only to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic Exception) with a different type
of exception class (ArrayIndexOutOfBoundsException).
public class TryCatchExample8 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 9
Let's see an example to handle another unchecked exception.
public class TryCatchExample9 {
public static void main(String[] args) {
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked exception.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class TryCatchExample10 {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {

System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Output:
File saved successfully
Internal working of java try-catch block

Figure : Working of Try Catch Block


The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Java catch multiple exceptions
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different
exceptions, use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for Arithmetic
Exception must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Example 2
public class MultipleCatchBlock2 {
public static void main(String[] args) {
try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
Example 3
In this example, try block contains two exceptions. But at a time only one exception occurs and its
corresponding catch block is invoked.
public class MultipleCatchBlock3 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding exception
type. In such case, the catch block containing the parent exception class Exception will invoked.
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Parent Exception occurs
rest of the code
Example 5
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e.
from most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block
itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.

Figure : Java Finally Block Flow Chart


Note: If you don't handle exception, before terminating the program, JVM executes finally block(if
any).
Why use java finally
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection
etc.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).
Java throw exception
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword
is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If the
age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java Exception propagation
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call
stack to the previous method,If not caught there, the exception again drops down to the previous
method, and so on until they are caught or until they reach the very bottom of the call stack.This
is called exception propagation
Rule: By default Unchecked Exceptions are forwarded in calling chain (propagated).
Program of Exception Propagation
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
In the above example exception occurs in m() method where it is not handled,so it is propagated
to previous n() method where it is not handled, again it is propagated to p() method where
exception is handled.
Exception can be handled in any method in call stack either in main() method,p() method,n()
method or m() method.
Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Program which describes that checked exceptions are not propagated
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
}

Output:Compile Time Error

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared
Ans) checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
Java throws example
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or declare the
exception.
There are two cases:
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether exception occurs during
the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur, the code will be executed fine.
B)In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.
A)Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:device operation performed
normal flow...

B)Program if exception occurs


import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:Runtime Exception
Difference between throw and throws in Java
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
Table 0.4 Difference between throw and throws

No. Throw throws


1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
2) Checked exception cannot be propagated Checked exception can be propagated
using throw only. with throws.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.

Java throw example


void m(){
throw new ArithmeticException("sorry");
}
Java throws example
void m()throws ArithmeticException{
//method code
}
Java throw and throws example
void m()throws ArithmeticException{
throw new ArithmeticException("sorry");
}

ExceptionHandling with MethodOverriding in Java


There are many rules if we talk about methodoverriding with exception handling. The Rules are
as follows:
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method cannot declare
the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
If the superclass method does not declare an exception
1) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
p.msg();
}
}
Output:Compile Time Error
2) Rule: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}

Output:child
If the superclass method declares an exception
1) Rule: If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method declares parent exception
import java.io.*;
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class TestExceptionChild2 extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild2();
try{
p.msg();
}catch(Exception e){}
}
}
Output:Compile Time Error

Example in case subclass overridden method declares same exception


import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild3 extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild3();
try{
p.msg();
}catch(Exception e){}
}
}
Ou tput:child
Example in case subclass overridden method declares subclass exception
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild4 extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild4();
try{
p.msg();
}catch(Exception e){}
}
}
Output:child
Example in case subclass overridden method declares no exception
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild5 extends Parent{
void msg(){System.out.println("child");}

public static void main(String args[]){


Parent p=new TestExceptionChild5();
try{
p.msg();
}catch(Exception e){}
}
}
Output:child
Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Output:Exception occured: InvalidAgeException:not valid
rest of the code...
Java Applets
Applets in Java are small and dynamic internet-based programs. A Java Applet can be only
executed within the applet framework of Java. For an easy execution of applets, a restricted
‘sandbox’ is provided by the applet framework. Generally, the applet code is embedded within
an HTML page. The applet codes are executed when the HTML pages get loaded into the Java-
compatible web browsers. Applets are mainly downloaded on remote machines and used on the
client side.
A Java applet can be a fully functional Java application as well since it can utilize a complete Java
API at its own accord. But still, there is a thin line between an applet and an application in Java.
In the next section of this article on Applets in Java, I will be listing down the differences between
a Java Applet and a Java application.
Java Applet vs Java Application
Table 0.5 Difference between Java Application and Java Applets

Java Application Java Applet


Java Applications are the stand-alone Java Applets are small Java programs which are
programs which can be executed designed to exist within HTML web document
independently
Java Applications must have main() method Java Applets do not need main() for execution
for them to execute
Java Applications just needs the JRE Java Applets cannot run independently and
require API’s
Java Applications do not need to extend any Java Applets must extend java.applet.Applet class
class unless required
Java Applications can execute codes from the Java Applets Applications cannot do so
local system
Java Applications has access to all the Java Applets has access only to the browser-
resources available in your system specific services
Java Applets:
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal. There are some important differences
between an applet and a standalone Java application, including the following:
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is downloaded
to the user's machine.
A JVM is required to view an applet.
The JVM can be either a plug-in of the Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various methods
during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser.
The security of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Life Cycle of an Applet:
Every Java Applet needs to go through a series of phases from initialization to destruction in order
to complete its execution. For that, the very first step is to inherit the java.applet.Applet class. This
class aids with various methods which help in holding up a basic framework for the Java Applets.
The various methods involved in the life cycle of Java Applet has been depicted by the below

Figure 1.Life Cycle of Applet.


As you can see, there are 4 main methods which are mandatory for any Java Applet to override.
Let me brief you about each of these methods one by one.
public void init(): This is the very first method to be invoked during the life cycle of an applet. In
this method, the variable that will be used further in the applet is initialized. One thing you must
note here is that this method can be invoked only once per applet life cycle.
public void start(): This is the second method that is invoked just after the init() method is called
by the browser. Each time a user revisits the web page containing the applet, start() method is
invoked and the applet is started.
public void stop(): This method is invoked whenever a user leaves the web page containing applet.
In other words, the stop() method is used to suspend the threads which are not required when the
applet is in the background or is not visible on the screen. These can be easily resumed using the
start() method.
public void destroy(): Finally, we have the destroy() method which is invoked in order to
completely remove an applet from the memory. This method is invoked only once per applet life
cycle and all the engaged resources must be freed up before this method is called.
One more method that is mostly used along with the above four is paint().
public void paint(Graphics g): This method is invoked whenever an applet needs to be redrawn or
repainted in the browser, irrespective of the cause. The paint() method takes one Graphic object as
a parameter that contains the graphics context in which the applet is being executed. Also, this
method is invoked each time output is expected from the applet.
Program to create an applet to display "Hello World".
Applets are small java programs that are run on a web page or java compatible web browser.
Java application programs that run on command prompt using java interpreter are called as Java
console-based applications. Whereas the java applets can be transported over internet from one
computer to another and run using appletviewer or any web browser that supports java. They are
included in an HTML page which tells the browser which applets to load.
An applet can perform arithmetic operations, display graphics, play sounds, accept user input,
create animation and play interactive games.
Every applet is created by creating sub class of Applet class. An applet is simply a Java class that
extends the java.applet.Applet class. There are following steps to create an applet program by first
mechanism:
First of all add the following import statements:
import java.applet.Applet;
import java.awt.Graphics;
Define an applet subclass. Every applet must define a subclass of the Applet class.
The Applet class have life cycle methods: init( ), start( ), stop( ), destroy( ), paint( ).
public class HelloWorld extends Applet
Every Applet must implement one of the following methods : init( ), start( ) or paint( ). The paint(
) method requires Graphics object as an argument, defined as follows. The Graphics class is present
in java.awt package.
public void paint (Graphics g) { ... }
Now use the Graphics class methods like drawString( ), drawLine( ) to draw on Applet window.
The complete program is shown below.
Compile the above program using java compiler. Remember that you have to define the subclass
with public access specifier.
javac HelloWorld.java
After that it will create a .class file by name "HelloWorld.class".
Next create a HTML file and put the <APPLET> tag in it by specifying the class file name in
CODE attribute as shown below.
<APPLET CODE="HelloWorld.class" WIDTH="100" HEIGHT="100">
</APPLET>
Save the HTML file as "HelloWorldApplet.html" and use appletviewer command to load the
applet viewer window.
appletviewer HelloWorldApplet.html
In this program, we have created two seperate file, in first file we have created applet class and in
second file we have embed the <APPLET> tag in it by specifying class name. In next program we
will put the applet tag in same .java file. The output of this program is, it will just display "Hello
World !" on applet window. The drawString(String msg, int x, int y) is a method of Graphics class
which draws the string in an applet.
JAVA PROGRAM CODE
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World !", 10, 30);
}
}
HTML CODE
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="HelloWorld.class" width="200" height="200">
</applet>
</body>
</html>
Commands to Compile & Run Applet programs
C:\>javac HelloWorld.java
C:\>appletviewer HelloWorldApplet.html
OUTPUT

Features of Applets over HTML


Displaying dynamic web pages of a web application.
• Playing sound files.
• Displaying documents
• Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
An applet cannot load libraries or define native methods.
An applet cannot ordinarily read or write files on the execution host.
An applet cannot read certain system properties.
An applet cannot make network connections except to the host that it came from.
An applet cannot start any program on the host that’s executing it.
Security restrictions and capabilities of applets
Sandbox Applets
Sandbox applets are restricted to the security sandbox and can perform the following operations:
They can make network connections to the host and port they came from. Protocols must match,
and if a domain name is used to load the applet, the domain name must be used to connect back to
the host, not the IP address.
They can easily display HTML documents using the show Document method of
the java.applet.AppletContext class.
They can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the user's CLASSPATH)
have none of the restrictions that applets loaded over the network do.
They can read secure system properties. When launched by using JNLP, sandbox applets can also
perform the following operations:
They can open, read, and save files on the client.
They can access the shared system-wide clipboard.
They can access printing functions.
They can store data on the client, decide how applets should be downloaded and cached, and much
more. Sandbox applets cannot perform the following operations:
They cannot access client resources such as the local filesystem, executable files, system clipboard,
and printers.
They cannot connect to or retrieve resources from any third party server (any server other than the
server it originated from).
They cannot load native libraries.
They cannot change the SecurityManager.
They cannot create a ClassLoader.
They cannot read certain system properties.
Setting the security level within the Java Control Panel
Java 7.0 /8.0 introduced the ability to manage when and how untrusted Java applications (i.e. an
application that is digitally signed by an unknown publisher, or a certificate that has not been
issued by a trusted Certificate Authority) will run if they are included on a web page. Setting the
security level within the Java Control Panel will determine whether
You are prompted before an untrusted java application is run (MEDIUM or HIGH) or
Untrusted Java applications will be blocked so they cannot run (VERY HIGH).
Setting the Security levels through the Java Control Panel
In the Java Control Panel, click on the Security tab.
Select the desired Security level.
Click Apply.
Click OK to save changes made to the Java Control Panel.
Java Control Panel - Java 8 and later versions
Java Control Panel - Java 7

Security levels in the Java Control Panel


Very High
This is the most restrictive security level setting. All the applications that are signed with a valid
certificate and include the Permissions attribute in the manifest for the main JAR file are allowed
to run with security prompts. All other applications are blocked.
High
This is the minimum recommended (and default) security level setting. Applications that are
signed with a valid or expired certificate and include the Permissions attribute in the manifest for
the main JAR file are allowed to run with security prompts. Applications are also allowed to run
with security prompts when the revocation status of the certificate cannot be checked. All other
applications are blocked.
Medium (removed from Java 8 Update 20 and later versions)
Only unsigned applications that request all permissions are blocked. All other applications are
allowed to run with security prompts. Selecting the Medium security level is not recommended
and will make your computer more vulnerable should you run a malicious application.

You might also like