Reading Material Of 403- JAVA Programming I N D E X403- JAVA Programming Unit-1 Vidyabharti Trust of...
Transcript of Reading Material Of 403- JAVA Programming I N D E X403- JAVA Programming Unit-1 Vidyabharti Trust of...
Reading Material
Of
403- JAVA Programming
I N D E X
Sr No Description Page No.
Unit- 1 Introduction to Java 1
Unit-2 Basic Concepts 6
Unit-3 Classes and Objects 16
Unit-4 Applet 36
Unit-5 5.1 Multithreading 48
5.2 Exception Handling 58
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
1 | P a g e P r o f . R o n a k P a n c h a l
Unit 1. Introduction to Java
1.1. Properties of Java
1.2. Comparison of java with C++
1.3. Java Compiler
1.4. Java Interpreter
What is Java? Java is a programming language and a platform. Java is a high level, robust, secured and object-oriented
programming language. Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc.
Java latest version is “Java SE 11 (18.9 LTS)” . It released in September 2018
Java Future release version is “Java SE 12 (19.3)” and it will be release at March 2019
History of Java 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Why Java name for java language? The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary",
"Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
Java is an island of Indonesia where first coffee was produced (called java coffee).
Notice that Java is just a name not an acronym.
Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
In 1995, Time magazine called Java one of the Ten Best Products of 1995.
JDK 1.0 released in(January 23, 1996).
Where it is used? According to Sun, 3 billion devices run java. There are many devices where java is currently used. Some
of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
2 | P a g e P r o f . R o n a k P a n c h a l
Types of Java Applications 1) Standalone Application
2) Web Application
3) Enterprise Application
4) Mobile Application
Features of Java There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple Program of Java To create a simple java program, you need to create a class that contains main method. Let's understand
the requirement first.
Requirement for Hello Java Example
For executing any java program, you need to
install the JDK if you don't have installed it, download the JDK and install it.
set path of the jdk/bin directory.
create the java program
compile and run the java program
Eg: class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
} }
save this file as Simple.java
To compile: javac Simple.java
To execute: java Simple
Output: Hello Java
Understanding first java program
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
3 | P a g e P r o f . R o n a k P a n c h a l
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
4 | P a g e P r o f . R o n a k P a n c h a l
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create object to invoke the
main method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
How to set path in Java There are 2 ways to set java path:
1. temporary
2. permanent
How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
Open command prompt
copy the path of jdk/bin directory
write in command prompt: set path=copied_path
For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java byte code can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is the
implementation of JVM.It physically exists. It contains set of libraries + other files that JVM uses at
runtime.
Implementation of JVMs is also actively released by other companies besides Sun Micro Systems.
JDK JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
JDK Includes Javac(Java compiler), Java (Interpreter), JDB(Java Debugger) , and Applet Viewer.
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
5 | P a g e P r o f . R o n a k P a n c h a l
Comparison of java with C++
Java C++
Java is a true and complete object oriented
language.
C++ is an extension of C with object oriented
behavior. C++ is not a complete object oriented
language as that of Java.
Java does not provide template classes. C++ offers Template classes.
Java supports multiple inheritance using
interface.
C++ achieves multiple inheritance by permitting
classes to inherit from multiple classes.
Java does not provide global variables. Global variables can be declared in C++.
Java does not support pointers. C++ supports pointers.
In Java, destruction of objects is performed in
finalize method.
In C++, destruction of objects is performed by
destructor function.
Java doesn’t provide header files. C++ has header files.
Write once, run anywhere / everywhere (WORA / WORE).
Write once, compile anywhere (WOCA).
Java program Structure.
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
Main Method Class
{
Main Method Definition
}
Document Section
The documentation section comprises a set of comment lines giving the name of the program, the
author and other details, Comments must explain why and what of classes and how of algorithms. This
would greatly help in maintaining the program.
We can write comments in java in two ways.
a. Single Line comments: It start with two forward slashes (//) and continue to the end of the current
line. Line comments do not require an ending symbol.
b. Multiple line comments start with a forward slash and an asterisk (/*) and end with an asterisk and a
forward slash (*/).Block comments can also extend across as many lines as needed.
403- JAVA Programming Unit-1 Vidyabharti Trust of BCA College, Umrakh
6 | P a g e P r o f . R o n a k P a n c h a l
Package Statement The first statement allowed in a Java file is a package statement. This statement
declares a package name and informs the compiler that the classes defined here belong to this package.
Example: Package student; The package statement is optional.
Import Statements The next thing after a package statement (but before any class definitions) may be a
number of import statements. This is similar to the #include statement in C. Example: import student.
test; This statement instructs the interpreter to load the test class contained in the package student.
Using import statements, we can have access to classes that are part of other named packages.
Interface Statements An interface is like a class. This is also an optional section and is used only when
we wish to implement the multiple inheritance features in the program.
Class Definitions A Java program may contain multiple class definitions. Classes are the primary and
essential elements of a Java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.
Main Method Class Since every Java stand-alone program requires a main method as its starting point,
this class is the essential part of a Java program. A simple Java program may contain only this part. The
main method creates objects of various classes and establishes communications between them. On
reaching the end of main, the program terminates and the control passes back to the operating system.
Disclaimer: The study material is compiled by Prof. Nainesh J. Gathiyawala. The basic objective of this material is to supplement teaching and discussion in the classroom in the subject. Students are required to go for extra reading in the subject through library work.
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
7 | P a g e P r o f . R o n a k P a n c h a l
Unit 2. Basic Concepts
Identifier, Literals , Operators , Variables
Keywords
Data Types
Branching: If – Else, Switch
Looping : While, Do-while , For
Type Casting.
Strings
Basic String operations
String comparison
String Buffer class.
Variable:
Variable is used to store values. It value may change during program execution.
int data=50;//Here data is variable
Types of Variable
There are three types of variables in java
local variable
instance variable
static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Example to understand the types of variables
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
8 | P a g e P r o f . R o n a k P a n c h a l
}
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
9 | P a g e P r o f . R o n a k P a n c h a l
Data Types in Java
In java, there are two types of data types
primitive data types
non-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 8 byte
Why char uses 2 byte in java and what is \u0000 ? Because java uses Unicode system rather than ASCII code system. \u0000 is the lowest range of
Unicode system.
Operators in java
Operator is a symbol that is used to perform operations. Java provides a rich set of
operators to manipulate variables. We can divide all the Java operators into the following
groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Bitwise operator
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
The following table lists the bitwise operators.
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
10 | P a g e P r o f . R o n a k P a n c h a l
A=60 , B=13
1. & (bitwise and)
Binary AND Operator copies a bit to the result if it exists in both operands.
Example: (A & B) will give 12 which is 0000 1100
2. | (bitwise or)
Binary OR Operator copies a bit if it exists in either operand.
Example: (A | B) will give 61 which is 0011 1101
3. ^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one operand but not both.
Example: (A ^ B) will give 49 which is 0011 0001
4. ~ (bitwise compliment)
Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
Example: (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary
number.
5. << (left shift)
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified
by the right operand
Example: A << 2 will give 240 which is 1111 0000
6. >> (right shift)
Binary Right Shift Operator. The left operands value is moved right by the number of bits
specified by the right operand.
Example: A >> 2 will give 15 which is 1111
7. >>> (zero fill right shift)
Shift right zero fill operators. The left operands value is moved right by the number of bits
specified by the right operand and shifted values are filled up with zeros.
Example: A >>>2 will give 15 which is 0000 1111
Type casting
Assigning a value of one type to a variable of another type is known as Type Casting.
If two types are compatible then java will perform the conversion automatically.
If two types are incompatible then we have to use a cast, which perform an explicit
conversion.
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
11 | P a g e P r o f . R o n a k P a n c h a l
In Java, type casting is classified into two types,
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
12 | P a g e P r o f . R o n a k P a n c h a l
1. Widening Casting (Implicit)
Automatic Type casting take place when,
the two types are compatible
the target type is larger than the source type
Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output :
Int value 100
Long value 100
Float value 100.0
2. Narrowing or Explicit type conversion:
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example : public class Test
{
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
13 | P a g e P r o f . R o n a k P a n c h a l
public static void main(String[] args)
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
14 | P a g e P r o f . R o n a k P a n c h a l
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}Output :
Double value 100.04
Long value 100
Int value 100
Command Line Argument
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used
as an input.
Simple example:
class cmd
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println("Sum = " + c);
}
}
Run program : java cmd 10 20
Output : 30
Example of command-line argument that prints all the values In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
class A
{
public static void main(String args[])
{
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
15 | P a g e P r o f . R o n a k P a n c h a l
for(int i=0;i<args.length;i++)
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
16 | P a g e P r o f . R o n a k P a n c h a l
System.out.println(args[i]);
}
}
compile > javac A.java
run > java A Neha Nainesh Gathiyawala Output: Neha
Nainesh
Gathiyawala
Java String
Basically, String is collection of character.
Java String provides a lot of concepts that can be performed on a string such as compare,
concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example: char[] ch={'j','a','v','a'};
String s=new String(ch);
is same as:
String s="java”;
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
What is String in java Generally, string is a sequence of characters. But in java, string is an object that represents a
sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal Java String literal is created by using double quotes. For Example:
String s="welcome";
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
17 | P a g e P r o f . R o n a k P a n c h a l
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object
with the value "Welcome" in string constant pool, so it will create a new object. After that it will
find the string with the value "Welcome" in the pool, it will not create new object but will
return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of string literal? To make Java more memory efficient (because no new objects are created if it exists already in
string constant pool).
2) By new keyword String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap(non pool).
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
Why string objects are immutable in java?
Because java uses the concept of string literal. Suppose there are 5 reference variables, all
refers to one object "Nainesh". If one reference variable changes the value of the object, it will
be affected to all the reference variables. That is why string objects are immutable in java.
Java String compare
We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare string in java: 1. By equals() method
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
18 | P a g e P r o f . R o n a k P a n c h a l
2. By = = operator
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
19 | P a g e P r o f . R o n a k P a n c h a l
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
} } Output:true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
} } Output:false
Truec
2) String compare by == operator
The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
} } Output:true
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
20 | P a g e P r o f . R o n a k P a n c h a l
false
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
21 | P a g e P r o f . R o n a k P a n c h a l
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
} } Output:0
1
-1
String Concatenation in Java
In java, string concatenation forms a new string that is the combination of multiple strings.
There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method
1) String Concatenation by + (string concatenation) operator
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
} } Output:
Sachin Tendulkar
String concatenation operator produces a new string by appending the second operand onto
the end of the first operand. The string concatenation operator can concat not only string but
primitive values also. For Example:
class TestStringConcatenation2{
public static void main(String args[]){
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
22 | P a g e P r o f . R o n a k P a n c h a l
String s=50+30+"Sachin"+40+40;
403- JAVA Programming Unit-2 Vidyabharti Trust College of BCA, Umrakh
23 | P a g e P r o f . R o n a k P a n c h a l
System.out.println(s);//80Sachin4040
} } 80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
2) String Concatenation by concat() method The String concat() method concatenates the specified string to the end of current string.
Syntax:
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
OP : Sachin Tendulkar
Disclaimer: The study material is compiled by Prof. Nainesh J. Gathiyawala. The basic objective of this material is to supplement teaching and discussion in the classroom in the subject. Students are required to go for extra reading in the subject through library work.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
16 | P a g e P r o f . R o n a k P a n c h a l
3. Classes and Objects
Simple Class, Field Access Controls, Object creation
Construction and Initialization
Methods, this pointer
Overloading Methods & Constructors. Static members, static block, static class
Inheritance, super, abstract class, overriding methods
Interfaces
Introduction to Interfaces.
Interface Declaration.
Inheriting and Hiding Constants.
Inheriting, Overloading and Overriding Methods.
Interfaces Implementations
Class in Java Class is user defined data type. It is a template or blueprint from which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface
Syntax to declare a class:
class <class_name>{
data member;
method;
}
Instance variable in Java
A variable that is created inside the class but outside the method is known as instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when object
(instance) is created. That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
17 | P a g e P r o f . R o n a k P a n c h a l
new keyword
The new keyword is used to allocate memory at runtime.
Example of Object and class that maintains the records of students
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
s1.insertRecord(111," PRINCY ");
s2.insertRecord(222," HARVI ");
s1.displayInformation();
s2.displayInformation();
}
}
OP : 111 PRINCY
222 HARVI
Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Constructor properties:
Constructor name must be same as its class name. Constructor must have no return type.
Constructor always declared as public.
Constructor invoke automatically whenever object is created.
Types of java constructors There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
18 | P a g e P r o f . R o n a k P a n c h a l
Java Default Constructor
A constructor that have no parameter is known as default constructor
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
at the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1(); }
}
Output: Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default
constructor.
Q) What is the purpose of default constructor? Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Example of default constructor that displays the default values class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3(); Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output: 0 null
0 null
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
19 | P a g e P r o f . R o n a k P a n c h a l
Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.
Java parameterized constructor
A constructor that has parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"PRINCY");
Student4 s2 = new Student4(222,"HARVI");
s1.display();
s2.display();
}
}
Output: 111 PRINCY
222 HARVI
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists. The compiler differentiates these
constructors by taking into account the number of parameters in the list and their type.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
20 | P a g e P r o f . R o n a k P a n c h a l
Example of Constructor Overloading class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Nainesh");
Student5 s2 = new Student5(222,"Gathiyawala",25);
s1.display();
s2.display();
} }
Output:
111 Nainesh 0
222 Gathiyawala 25
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
Constructor is used to initialize the state of an
object. Method is used to expose behavior of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default
constructor if you don't have any constructor. Method is not provided by compiler in any case.
Constructor name must be same as the class
name.
Method name may or may not be same as class
name.
Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
21 | P a g e P r o f . R o n a k P a n c h a l
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.
Usage of java this keyword
Here is given the usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
1) this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
Understanding the problem without this keyword
class Student10{
int id;
String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"RAJ");
Student10 s2 = new Student10(321,"World");
s1.display();
s2.display();
}
}
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why
we are using this keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
//example of this keyword
class Student11{
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
22 | P a g e P r o f . R o n a k P a n c h a l
int id;
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
23 | P a g e P r o f . R o n a k P a n c h a l
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"PRINCY");
Student11 s2 = new Student11(222,"HARVI");
s1.display();
s2.display();
} }
Output111 PRINCY
222 HARVI
If local variables (formal arguments) and instance variables are different, there is no need to
use this keyword.
2) this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to reuse
that constructor.
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"Nainesh");
Student13 e2 = new Student13(222,"Gathiyawala");
e1.display();
e2.display();
}
}
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
24 | P a g e P r o f . R o n a k P a n c h a l
Output:
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
25 | P a g e P r o f . R o n a k P a n c h a l
default constructor is invoked
default constructor is invoked
111 Ishaan
222 Tamhankar
Rule: Call to this() must be the first statement in constructor.
Method Overloading in Java
If a class has multiple methods by same name but different parameters, it is known as
Method Overloading.
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing the return type of the method.
1) Example of Method Overloading by changing the no. of arguments In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
} }
Output:30
40
2) Example of Method Overloading by changing data type of argument In this example, we have created two overloaded methods that differ in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
26 | P a g e P r o f . R o n a k P a n c h a l
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output:21.0
40
Q) Why Method Overloading is not possible by changing the return type of
method? In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity.
Q) Can we overload main () method? Yes, by method overloading. You can have any number of main methods in a class by method
overloading.
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
27 | P a g e P r o f . R o n a k P a n c h a l
void run(){System.out.println("Bike is running safely");}
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
28 | P a g e P r o f . R o n a k P a n c h a l
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
Output: Bike is running safely
Can we override static method? No, static method cannot be overridden. It can be proved by runtime polymorphism
Why we cannot override static method? Because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.
Can we override java main method? No, because main is a static method.
Difference between method overloading and method overriding in java
No. Method Overloading Method Overriding
1)
Method overloading is used to increase the
readability of the program.
Method overriding is used to provide the
specific implementation of the method that is
already provided by its super class.
2) Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
3) In case of method overloading, parameter
must be different.
In case of method overriding, parameter must
be same.
4) Method overloading is the example of compile
time polymorphism.
Method overriding is the example of run time
polymorphism.
5)
In java, method overloading can't be
performed by changing return type of the
method only. Return type can be same or
different in method overloading. But you must
have to change the parameter.
Return type must be same or covariant in
method overriding.
super keyword in java
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
29 | P a g e P r o f . R o n a k P a n c h a l
3. super is used to invoke immediate parent class method.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
30 | P a g e P r o f . R o n a k P a n c h a l
1) super is used to refer immediate parent class instance variable.
//example of super keyword
class Vehicle{
int speed=50;
}
class Bike4 extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
} } Output:100
2) super is used to invoke parent class constructor.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
} }
Output:Vehicle is created
Bike is created
3) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
31 | P a g e P r o f . R o n a k P a n c h a l
void message(){System.out.println("welcome to java");}
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
32 | P a g e P r o f . R o n a k P a n c h a l
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:welcome to java
Welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not of
Person class because priority is given to local.
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. Variable (Stop value change)
2. Method (Stop method overriding)
3. Class (Stop inheritance)
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
33 | P a g e P r o f . R o n a k P a n c h a l
Example of final method class Bike{ final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
} }
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class final class Bike{} class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
} }
Output:Compile Time Error
Q) Can we declare a constructor final? No, because constructor is never inherited.
Q) What is final parameter? If you declare any parameter as final, you cannot change the value of it.
Java static keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
34 | P a g e P r o f . R o n a k P a n c h a l
4. nested class
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
35 | P a g e P r o f . R o n a k P a n c h a l
1) Java static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable It makes your program memory efficient (i.e it saves memory).
Example of static variable //Program of static variable
class Student8{
int rollno;
String name;
static String college ="SDJ";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"PRINCY");
Student8 s2 = new Student8(222,"HARVI");
s1.display();
s2.display();
}
}
Output:111 PRINCY SDJ
222 HARVI SDJ
2) Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
//Program of changing the common property of all objects(static field).
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
36 | P a g e P r o f . R o n a k P a n c h a l
class Student9{
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
37 | P a g e P r o f . R o n a k P a n c h a l
int rollno;
String name;
static String college = "SDJ";
static void change(){
college = "SDJ International College ";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Nainesh");
Student9 s2 = new Student9 (222,"Princy");
Student9 s3 = new Student9 (333,"Harvi");
s1.display();
s2.display();
s3.display();
} } Output:111 Nainesh SDJ International College
222 Princy SDJ International College
333 Harvi SDJ International College
Restrictions for static method There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Q) Why java main method is static? Ans) because object is not required to call static method if it were non-static method, jvm create
object first then call main() method that will lead the problem of extra memory allocation.
3) Java static block
Is used to initialize the static data member.
It is executed before main method at the time of class loading.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
38 | P a g e P r o f . R o n a k P a n c h a l
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
} Output:static block is invoked
Hello main
Abstract class in Java
A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Abstraction Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only important things to the user and hides the internal details.
sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class abstract class A{}
abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
Example abstract method
abstract void printStatus();//no body and abstract
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
39 | P a g e P r o f . R o n a k P a n c h a l
Example of abstract class that has abstract method In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
} }
OP : running safely..
Abstract class having constructor, data member, methods etc. An abstract class can have data member, abstract method, method body, constructor and even
main() method.
example of abstract class that have method body abstract class Bike{
Bike(){System.out.println("bike is created");} abstract void run();
void changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");} }
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
} } bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
Interface
An interface is a blueprint of a class. It has abstract methods only. The interface in java is a
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
40 | P a g e P r o f . R o n a k P a n c h a l
mechanism to achieve fully abstraction.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
41 | P a g e P r o f . R o n a k P a n c h a l
Why use Java interface?
There are mainly two reasons to use interface. They are given below.
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritances.
The java compiler adds public and abstract keywords before the interface method
And
Public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and
abstract.
Understanding relationship between classes and interfaces
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the
A6 class.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
} } Output:Hello
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
42 | P a g e P r o f . R o n a k P a n c h a l
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
} }
Output:Hello
Welcome
Q) Multiple inheritances is not supported through class in java but it is
possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritances is not supported in case of
class. But it is supported in case of interface because there is no ambiguity as implementation is
provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestTnterface1 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestTnterface1 obj = new TestTnterface1();
obj.print();
} }
Op : Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
43 | P a g e P r o f . R o n a k P a n c h a l
interface Printable{
403- JAVA Programming Unit-3 Vidyabharti Trust College of BCA, Umrakh
44 | P a g e P r o f . R o n a k P a n c h a l
void print();
}
interface Showable extends Printable{
void show();
}
class Testinterface2 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
} } Hello
Welcome
Difference between abstract class and interface
Abstract class Interface
1) Abstract class can have abstract and non-
abstract methods. Interface can have only abstract methods.
2) Abstract class doesn't support multiple
inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static
and non-static variables. Interface has only static and final variables.
4) Abstract class can have static methods, main
method and constructor.
Interface can't have static methods, main
method or constructor.
5) Abstract class can provide the
implementation of interface.
Interface can't provide the implementation
of abstract class.
6) The abstract keyword is used to declare
abstract class.
The interface keyword is used to declare
interface.
7)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Disclaimer: The study material is compiled by Prof. Nainesh J. Gathiyawala. The basic objective of this material is to supplement teaching and discussion in the classroom in the subject. Students are required to go for extra reading in the subject through library work.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
36 | P a g e P r o f . R o n a k P a n c h a l
Java Applet
Applet is small java program that are primarily used in internet computing.
An applet is a special type of application that's included as a part of an HTML page and can be
stored in a web page and run within a web browser.
They can be run using the appletviewer or any Web browser that supports Java.
It can perform arithmetic operations, display graphics, play sounds, accept user input, create
animation.
Applet code uses the services of two classes namely Applet and Graphics from the Java class
library.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
When an applet is loaded , it undergoes a series of changes in its state. The applet state include
1. Born or initialization state
2. Running state
3. Idle state
4. Dead or destroyed state
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
37 | P a g e P r o f . R o n a k P a n c h a l
Initialization State :
Applet enters the initialization state when it is first loaded. This is achieved by calling
the init() method of Applet Class. The applet is born. At this stage, we may do the
following, if required.
1. Create objects needed by the applet
2. Set up initial values
3. Load images or fonts
4. Set up colors,
The initialization occurs only once in the applet‟s life cycle.
Running State :
Applet enters the running state when the system calls the start() method of Applet Class.
This occurs automatically after the applet is initialized.
Starting can also occur if the applet is already in “stopped” (idle) state.
The start() method may be called more than once.
Idle or Stopped State :
An applet becomes idle when it is stopped from running.
Stopping occurs automatically when we leave the page containing the currently running
applet. We can also do so by calling the stop() method explicitly.
If we use a thread to run the applet, then we must use stop() method to terminate the thread.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
38 | P a g e P r o f . R o n a k P a n c h a l
Dead State :
An applet is said to be dead when it is removed from memory.
This occurs automatically by invoking the destroy() method when we quit the browser.
Like initialization, destroying stage occurs only once in the applet‟s life cycle.
If the applet has created any resources, like threads, we may override the destroy()
method to clean up these resources.
Display State :
Applet moves to the display state whenever it has to perform some output operations
on the screen.
This happens immediately after the applet enters into the running state.
The paint() method is called to accomplish this task.
Almost every applet will have a paint() method.
Display state is not considered as a part of the applet‟s life cycle.
Who is responsible to manage the life cycle of an applet?
Java Plug-in
Applet Architecture:
Applets are event driven. An applet waits until an event occurs. The AWT notifies the applet about
an event by calling an event handler that has been provided by the applet. Once this happens, the
applet must take appropriate action and then quickly return control to the AWT.
The user interacts with the applet as he/she want , when he/she wants. These interactions are sent to
the applet as events to which the applet must respond. For ex. when the user clicks a mouse, a
mouse-clicked event is generated. If the user press a key, a keypress event is generated.
Applets can contain various controls , such as push buttons and check boxes. When the user interacts
with one of these controls, an event is generated.
The Java‟s AWT makes Applet architecture simple.
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
} }
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
39 | P a g e P r o f . R o n a k P a n c h a l
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it
is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
40 | P a g e P r o f . R o n a k P a n c h a l
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font. 12. repaint() method:
whenever your applet needs to update the information displayed in its window, it simply
calls repaint().
Syntax : 1) void repaint()
This version causes the entire window to be repianted.
2) void repiant(int left,int top, int width, int height)
It specifies a region that will be repainted. You save time by specifying a region
to repaint.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
41 | P a g e P r o f . R o n a k P a n c h a l
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.
Syntax of drawImage() method:
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the
specified image.
How to get the object of Image:
The java.applet.Applet class provides getImage() method that returns the object of Image.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
42 | P a g e P r o f . R o n a k P a n c h a l
Syntax:
public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
1. public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
2. public URL getCodeBase(): is used to return the base URL.
Example of displaying image in applet:
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
In the above example, drawImage() method of Graphics class is used to display the image. The
4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
43 | P a g e P r o f . R o n a k P a n c h a l
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter().
HTML allows you to pass parameters to your applet. To retrieve a parameter, use the
getParameter() method. It returns the value of the specified parameter in the form of a String
object. Thus, for numeric and Boolean values, you will need to convert their string
representations into their internal formats.
Syntax:
String getParameter(String parameterName)
Eg:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50); }
}
/*<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet"> </param>
</applet> */
To set background Color
setBackground(Color.red);
To set Foreground Color
setForeground(Color.red);
To change Status message
showStatus("This is a status message of an applet window");
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
44 | P a g e P r o f . R o n a k P a n c h a l
Applet Example :
1. Smileyface
public void paint(Graphics g){
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
2. Set font and style
Font myFont = new Font("Courier", Font.BOLD | Font.ITALIC ,50);
g.setFont(myFont);
g.drawString("Sample", 10, 50);
3. Polygon
public void paint(Graphics g){
g.drawLine(10,20,170,40);
g.drawLine(170,40,80,140);
g.drawLine(80,140,10,20);
}
}
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
45 | P a g e P r o f . R o n a k P a n c h a l
4. Face
public void paint(Graphics g){
g.drawOval(40,40,120,150); //head
g.drawOval(57,75,30,20);//left eye
g.drawOval(110,75,30,20);//right eye
g.fillOval(68,81,10,10);//pupil(left)
g.fillOval(121,81,10,10);//pupil(right)
g.drawOval(85,100,30,30);//nose
g.fillArc(60,125,80,40,180,180);//mouth
g.drawOval(25,92,15,30);//left ear
g.drawOval(160,92,10,30);//right ear
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
46 | P a g e P r o f . R o n a k P a n c h a l
5. Draw Polygon
public void paint(Graphics g)
{
// int x[] = {350,450,570,450};
// int y[] = {220,100,220,320};
int x[] = {100,220,350,300,150};
int y[] = {150,70,150,290,290};
g.drawPolygon(x,y,5);
}
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
47 | P a g e P r o f . R o n a k P a n c h a l
Difference between applet and application.
Applet Application
Small Program Large Program
Used to run a program on client Browser Can be executed on stand alone computer system
Applet is portable and can be executed by any
JAVA supported browser.
Need JDK, JRE, JVM installed on client
machine.
Applet applications are executed in a Restricted
Environment
Application can access all the resources of the
computer
Applets are created by extending the
java.applet.Applet
Applications are created by writing public static
void main(String[] s) method.
Applet application has 5 methods which will be
automatically invoked on occurrence of specific
event
Application has a single start point which is main
method
Main method is not present Main method is present
Does not require any security Requires highest security for the system as they
are untrusted
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
48 | P a g e P r o f . R o n a k P a n c h a l
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than multiprocessing because threads share a common memory area. And
that’s why known as Light Weight Process. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occurs in a single
thread.
As shown in the above figure, thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS and one process can have
multiple threads.
Note: At a time one thread is executed only.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
49 | P a g e P r o f . R o n a k P a n c h a l
Life cycle of a Thread (Thread States) During the life time of a thread, there are many states it can enter. They include:
1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state
A thread is always in one of these five states
Newborn State:
When we create a thread object, the thread is born and is said to be in newborn state.
Runnable state:
The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor. That is, the thread has joined the queue of threads that are waiting for execution.
If all threads have equal priority, then they are given time slots for execution in round robin fashion,
ie. First-come, first-serve manner. The thread that relinquishes control, joins the queue at the end and
again waits for its turn. This process of assigning time to threads is known as time-slicing.
However, it we want a thread to relinquish control to another thread of equal priority before its
turncomes, we can do so by using the yield() method.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
50 | P a g e P r o f . R o n a k P a n c h a l
Running State:
Running means that the processor has given its time to the thread for its execution.
Blocked State:
A thread is said to be blocked when it is prevented from entering into the Runnable state and
subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting.
A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run
again.
Dead State:
Every thread has a life cycle.
A running thread ends its life when it has completed execution its run() method. It is natural death.
However, we can kill it by sending the stop message to it at any state thus causing a premature death
to it. A thread can be killed as soon it is born, or while it is running , or even when it is in “not
Runnable” (blocked) condition.
How to create thread? There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
1) By extending Thread class:
class th1 extends Thread
{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println("Th 1 = " + i);
}
}
}
class th2 extends Thread
{
public void run()
{
for(int i=1;i<10;i++)
{
System.out.println("Th 2 = " + i);
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
51 | P a g e P r o f . R o n a k P a n c h a l
}
}
}
class test
{
public static void main(String args[])
{
th1 a1=new th1();
th2 a2=new th2();
a1.run();
a2.run();
System.out.println("exit main");
}
}
2) By implementing the Runnable interface:
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
} Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
object.So you need to explicitely create Thread class object.We are passing the object of your
class that implements Runnable so that your class run() method may execute.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
A new thread starts.
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
52 | P a g e P r o f . R o n a k P a n c h a l
Can we start a thread twice? No. After starting a thread, it can never be started again.
If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but
for second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
running
Exception in thread "main" java.lang.IllegalThreadStateException
Thread Priorities:
Each thread has a priority. Priorities are represented by a number between 1 and 10.
They are used by the thread scheduler to decide when each thread should be allowed to run. In
theory , higher threads get more CPU time than lower-priority threads.
It's possible to assign a thread priority
3 constants defined in Thread class:
The Thread class contains three integer priority constants.
1) MIN_PRIORITY
2) NORM_PRIORITY
3) MAX_PRIORITY
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
53 | P a g e P r o f . R o n a k P a n c h a l
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1
The value of MAX_PRIORITY is 10.
You can check a threads priority using getPriority()
You can change a threads priority using setPriority()
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
} } Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
Sleep method in java The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int nanos)throws InterruptedException
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
54 | P a g e P r o f . R o n a k P a n c h a l
Example of sleep method in java
class c1 extends Thread
{
public void run()
{
System.out.println("c program");
try{
Thread.sleep(3000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("c++ program");
try{
Thread.sleep(3000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("java program");
}
}
class test
{
public static void main(String args[]) {
c1 obj1 = new c1();
obj1.start();
}
}
Op: C program
C++ program
Java program
Each new line output comes after 3 second of time interval
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time, the thread scheduler picks up another thread and so on.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
55 | P a g e P r o f . R o n a k P a n c h a l
Difference between wait and sleep?
Let's see the important differences between wait and sleep methods.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
It is the method of Object class It is the method of Thread class
It is the non-static method It is the static method
should be notified by notify() or notifyAll()
methods
after the specified amount of time, sleep is
completed.
SYNCHRONIZATION Each object in Java has a lock and a monitor to manage the lock.
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). Only one
thread can own a monitor at a given time.
As long as the thread holds the monitor, no other thread can enter the synchronized section of code. other threads
are said to be waiting for the monitor.
In java „synchronized‟ keyword is used with the method to enter the thread in monitor.
You can synchronize your code two ways.
1) Using Synchronized Methods:
synchronized void method( )
{
………. // code here is synchronized
}
To enter an object‟s monitor, just call a method that has been modified with the synchronized
keyword.
Whenever a thread has completed its work of using synchronized method (or block of code), it
will hand over the monitor to the next thread that is ready to use the same resource.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
56 | P a g e P r o f . R o n a k P a n c h a l
While a thread is inside a synchronized method, all other threads that try to call it on the same
instance have to wait. To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized method.
An interesting situation may occur when two or more threads are waiting to gain control of a
resource of each other. A Java multithreaded program may suffer from the deadlock condition
because the synchronized keyword, when a thread is waiting for an object lock, that is acquired
by another thread and second thread is waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.
If all threads calling the same method on the same object at the same time , then this is called a
race condition because the threads are racing each other to complete the method. In most
situation, a race condition is more subtle and less predictable, because you can‟t be sure when the
context switch will occur. This can cause a program to run right one time and wrong the next.
Inter-Thread Communication
Inter-thread communication can be defined as the exchange of messages between two or more
threads. The transfer of messages takes place before or after the change of state of thread.
Java implements inter-thread communication with the help of following three methods :
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
wait() : Tells the calling thread to give up the monitor and Sends the calling thread into the sleep
mode. This thread can now be activated only by notify or notifyall() methods.
One can also specify the time for which the thread has to wait. The desired waiting time period is
specified as an argument to the wait () method.
notify() : Resumes the first thread that went into the sleep mode.
notifyall() : Resumes all the threads that are in sleep mode. The execution of these threads happens
as per priority.
These methods are declared within Object class. Since the methods are declared as final they
cannot be overridden.
Deadlock in java
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
57 | P a g e P r o f . R o n a k P a n c h a l
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Deadlock describes a situation where two or more threads are blocked forever, waiting for each
other. Deadlock occurs when multiple threads need the same locks but obtain them in different
order. A Java multithreaded program may suffer from the deadlock condition because the
synchronized keyword causes the executing thread to block while waiting for the lock, or
monitor, associated with the specified object. Here is an example:
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
58 | P a g e P r o f . R o n a k P a n c h a l
Exception Handling in Java
The exception handling in java is one of the powerful mechanisms to handle the runtime errors
so that normal flow of the application can be maintained.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, 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 ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs
NullPointerException. String s=null;
System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below: int a[]=new int[5];
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
59 | P a g e P r o f . R o n a k P a n c h a l
a[10]=50; //ArrayIndexOutOfBoundsException
Exception in Java can be categorized into two types:
Unchecked exception: The exceptions that are not checked at compile time are called
unchecked exceptions. These exceptions are not essentially handled in the
Program code, instead the JVM handles such exceptions. Unchecked exceptions are extended
from the java.lang.RuntimeException class.
Checked exception : Exceptions that are checked at compile-time are called checked exceptions.
These exceptions are explicitly handled in the code itself with the help of try-catch blocks.
Checked exceptions are extended from the java.lang.Exception class.
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
Problem without exception handling
public class Testtrycatch1{
public static void main(String args[]){
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
60 | P a g e P r o f . R o n a k P a n c h a l
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, 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
Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
} Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Java catch multiple exceptions
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[50]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}}
Output:task1 completed
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
61 | P a g e P r o f . R o n a k P a n c h a l
rest of the code...
Rule: At a time only one Exception is occurred and at a time only one catch block is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class TestMultipleCatchBlock1{
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...");
}
}
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)
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
62 | P a g e P r o f . R o n a k P a n c h a l
{
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
63 | P a g e P r o f . R o n a k P a n c h a l
}
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 must be followed by try or catch block.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
64 | P a g e P r o f . R o n a k P a n c h a l
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
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
65 | P a g e P r o f . R o n a k P a n c h a l
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 unchecked 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.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
66 | P a g e P r o f . R o n a k P a n c h a l
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...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
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.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
67 | P a g e P r o f . R o n a k P a n c h a l
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:
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. 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...
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
68 | P a g e P r o f . R o n a k P a n c h a l
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.
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:
No. throw throws
1) Java throw keyword is used to explicitly
throw an exception.
Java throws keyword is used to declare an
exception.
2) Checked exception cannot be propagated
using throw only.
Checked exception can be propagated 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.
Difference between final, finally and finalize
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
No. final finally Finalize
1)
Final is used to apply restrictions on
class, method and variable. Final class
can't be inherited, final method can't be
overridden and final variable value can't
be changed.
Finally is used to place
important code, it will be
executed whether
exception is handled or
not.
Finalize is used to
perform clean up
processing just before
object is garbage
collected.
2) Final is a keyword. Finally is a block. Finalize is a method.
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
69 | P a g e P r o f . R o n a k P a n c h a l
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...
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
70 | P a g e P r o f . R o n a k P a n c h a l
Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
71 | P a g e P r o f . R o n a k P a n c h a l
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
} }
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
} }
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
} }
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
403- JAVA Programming Vidyabharti Trust College of BCA, Umrakh
72 | P a g e P r o f . R o n a k P a n c h a l
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 }}
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2)
String is slow and consumes more memory when you
concat too many strings because every time it creates
new instance.
StringBuffer is fast and consumes
less memory when you concate
strings.
3)
String class overrides the equals() method of Object
class. So you can compare the contents of two strings
by equals() method.
StringBuffer class doesn't override
the equals() method of Object class.
.