Java Programming Material by Nithin, VVCE, Mysuru
Java Programming Material by Nithin, VVCE, Mysuru
Java is related to C++, which is a direct derivative of C. much of the properties of java
is inherited from these two languages.
The java platform differs from most other platforms in the sense that it‟s a software-
based platform that runs on top of other hardware-based platforms and it has two
components.
Runtime environment
Application programming interface (API)
Java code can be run on multiple platforms such as Windows, Solaris, Linux, Mac/OS
etc. Java code is compiled by the compiler and converted into „byte code‟. The byte code is a
platform independent code because it can be run on multiple platform i.e „Write once and run
anywhere (WORA)‟.
4. Secured: Java is secured because „No explicit pointer‟ and „Program run inside
virtual machine sandbox‟. It is composed of the following:
Class loader: Adds security by separating the package for classes of local file
system from those that are imported from network sources.
Byte verifier: Checks the code fragments for illegal code that can violate access
rights to objects.
Security manager: Determines what resources a class can access such as reading
and writing to local disk.
These securities are provided by java language. Some security can also be provided
by application developer through SSL, JAAS, Cryptography etc.
5. Robust: Robust simply means its strong. Java uses strong memory management.
There are „lack of pointers‟ that avoids security problem. There is „Automatic garbage
collection‟ in Java. There is „Exception handling‟ and „Type checking‟ mechanisms in
java.
All these points make java robust.
6. Architectural neutral: There is no implementation dependent features.
7. Portable: We may carry the java byte code to any platforms.
8. High performance: Java is faster than traditional interpretation since byte code is
close to native code.
9. Distributed: We can create distributed applications in java. RMI and EJB are used
for creating distributed applications. We may access files by calling the methods from
any machine on internet.
10. Multi-threaded: A thread is like a separate program executing concurrently. We can
write java programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it shares the same memory. Threads are
important for multimedia, web applications etc.
Class Simple
Subscript notation in java array can be used after type, before variable or after
variable.
Public static void main (string[] args)
Public static void main (string [] args)
Public static void main (string args[])
We can provide var-args support to main method by passing three ellipses (dots)
Public static void main (string … args)
Class A
};
Class simple
{
Compiler Byte code
JVM 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.
Loads code
Verifies code
Executes code
Provides runtime environment
Set of libraries
JVM
Other files
JDK: JDK is the acronym for java development kit. It contains JRE and other development
tools.
Set of
Development tools
libraries
JVM
Ex: java, Javac etc
Other files
Variable is a name of memory location. There are three types of variables: local, instance and
static. There are two types of data types in java, primitive and non-primitive.
Variable
Types of 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. It is not declared as static.
Static variable: A variable that is declared as static is called static variable. It cannot be
local.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.
Operators Precedence
multiplicative */%
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
Object means a real word entity such as pen, chair, table etc.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object: Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.
Inheritance: When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism: When one task is performed by different ways i.e. known as polymorphism.
For example: to convenes the customer differently, to draw something e.g. shape or rectangle
etc. In java, we use method overloading and method overriding to achieve polymorphism.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
Encapsulation: Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.
Java naming convention is a rule to follow as you decide what to name your identifiers
such as class, package, variable, constant, method etc. But, it is not forced to follow. So, it is
known as convention not rule All the classes, interfaces, packages, methods and fields of java
programming language are given according to java naming convention.
By using standard Java naming conventions, you make your code easier to read for yourself
and for other programmers. Readability of Java program is very important. It indicates that
less time is spent to figure out what the code does.
Name Convention
should start with uppercase letter and be a noun e.g. String, Color, Button,
class name
System, Thread etc.
interface should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name ActionListener etc.
should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
method name
print(), println() etc.
variable
should start with lowercase letter e.g. firstName, orderNumber etc.
name
package
should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants
should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
name
Java follows camelcase syntax for naming the class, interface, method and [Link]
name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.
Class in Java
A class is a group of objects that has common properties. 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
class <class_name>{
data member;
method; }
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and
name. We are creating the object of the Student class by new keyword and printing the
objects value.
class Student1{
[Link]([Link]);
[Link]([Link]);
Output: 0 null
Advantage of Method
Code Reusability
Code Optimization
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method on it. Here, we are displaying the state
(data) of the objects by invoking the displayInformation method.
class Student2{
int rollno;
String name;
rollno=r;
name=n;
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
222 Aryan
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So, we
perform method overloading to figure out the program quickly.
In java, Method Overloading is not possible by changing the return type of the method.
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{
[Link](10,10,10);
[Link](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 differs in data type. The first
sum method receives two integer arguments and second sum method receives two double
arguments.
class Calculation2{
[Link](10.5,10.5);
[Link](20,20);
Output: 21.0
40
One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int,long,float or double. The char datatype can
be promoted to int,long,float or double and so on.
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
} }
It is a special type of method that is used to initialize the object. Java constructor is invoked at
the time of object creation. It constructs the values i.e. provides data for the object that is why
it is known as constructor.
Rules for creating java constructor: There are basically two rules defined for the
constructor.
1. <class_name>(){}
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(){[Link]("Bike is created");}
Output:
Bike is created
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;
id = i;
name = n;
[Link]();
[Link]();
Output:
111 Karan
222 Aryan
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.
class Student5{
int id;
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
[Link]();
[Link]();
Output:
111 Karan 0
222 Aryan 25
2.7 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 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.
class Student{
int rollno;
String name;
String college="ITS";
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created. All student have its unique rollno and name so
instance data member is good. Here, college refers to the common property of all objects. If
we make it static, this field will get memory only once.
class Student8{
int rollno;
String name;
rollno = r;
name = n;
[Link]();
[Link]();
} }
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
college = "BBDIT";
rollno = r;
name = n;
[Link]();
[Link]();
[Link]();
[Link]();
}
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
The 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.
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
id = id;
name = name;
[Link]();
[Link]();
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.
class Student11{
int id;
String name;
[Link] = id;
[Link] = name;
[Link]();
[Link]();
Output111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:
class Student12{
int id;
String name;
id = i;
name = n;
}
[Link]();
[Link]();
Output:111 Karan
222 Aryan
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A [Link] means that
Programmer is a type of Employee.
class Employee{
float salary=40000;
int bonus=10000;
class Employee{
int id;
String name;
...
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
op=new Operation();
return pi*rsquare;
double result=[Link](5);
[Link](result);
Output: 78.5
Code reuse is also best achieved by aggregation when there is no is-a relationship.
Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method
overriding.
class Vehicle{
[Link]();
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
Consider a scenario, Bank is a class that provides functionality to get rate of interest.
But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks
could provide 8%, 7% and 9% rate of interest.
class Bank{
class Test2{
Output:
The super keyword in java is a reference variable that is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
class Vehicle{
int speed=50;
int speed=100;
void display(){
[Link]();
Output: 100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.
class Vehicle{
int speed=50;
int speed=100;
void display(){
[Link]();
} }
Output: 50
The super keyword can also be used to invoke the parent class constructor as given below:
class Vehicle{
Vehicle(){[Link]("Vehicle is created");}
Bike5(){
[Link]("Bike is created");
Bike is created
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(){[Link]("welcome");}
}
void display(){
[Link]();
Welcome
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The [Link] class implements Serializable, Comparable and CharSequence
interfaces.
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.
We will discuss about immutable string later. Let's first understand what is string in java and
how to create the string object.
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.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
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:
1. String s1="Welcome";
2. 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.
To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).
2) By new keyword
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).
char ch[]={'s','t','r','i','n','g','s'};
[Link](s1);
[Link](s2);
[Link](s3);
}}
java
strings
example
The [Link] class provides many useful methods to perform operations on sequence
of char values.
Once string object is created its data or state can't be changed but a new string object
is created.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
String s="Sachin";
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed
but a new object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still
refers to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
[Link] example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=[Link](" Tendulkar");
5. [Link](s);
6. }
7. }
output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
Because java uses the concept of string [Link] there are 5 reference variables,all
referes to one object "sachin".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.
1. By equals() method
2. By = = operator
3. By compareTo() method
The String equals() method compares the original content of the string. It compares values of
string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.
class Teststringcomparison1{
String s1="Sachin";
String s2="Sachin";
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
Output:true
true
false
class Teststringcomparison2{
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s3));//true
Output:false
true
class Teststringcomparison3{
String s1="Sachin";
String s2="Sachin";
Output:true
false
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.
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
Output:0
In java, string concatenation forms a new string that is the combination of multiple strings.
There are two ways to concat string in java:
Java string concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1{
[Link](s);//Sachin Tendulkar
Output:Sachin Tendulkar
class TestStringConcatenation2{
String s=50+30+"Sachin"+40+40;
[Link](s);//80Sachin4040
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
The String concat() method concatenates the specified string to the end of current string.
Syntax:
class TestStringConcatenation3{
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
Sachin Tendulkar
A part of string is called substring. In other words, substring is a subset of another string. In
case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. [Link]([Link](0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
[Link]([Link](6));//Tendulkar
[Link]([Link](0,6));//Sachin
Tendulkar
Sachin
The [Link] class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any
form in window based, web based or mobile application.
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
1. String s="Sachin";
2. [Link]([Link]());//SACHIN
3. [Link]([Link]());//sachin
4. [Link](s);//Sachin(no change in original)
SACHIN
sachin
Sachin
The string trim() method eliminates white spaces before and after string.
Sachin
Sachin
Java String startsWith() and endsWith() method
1. String s="Sachin";
2. [Link]([Link]("Sa"));//true
3. [Link]([Link]("n"));//true
true
true
1. String s="Sachin";
2. [Link]([Link](0));//S
3. [Link]([Link](3));//h
S
h
1. String s="Sachin";
2. [Link]([Link]());//6
When the intern method is invoked, if the pool already contains a string equal to this String
object as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.
Sachin
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Output:
It is widely used to define constraint on strings such as password and email validation. After
learning java regex tutorial, you will be able to test your own regular expressions by the Java
Regex Tester Tool.
[Link] package
It provides following classes and interface for regular expressions. The Matcher and Pattern
classes are widely used in java regular expression.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Matcher class
1 boolean matches() test whether the regular expression matches the pattern.
2 boolean find() finds the next expression that matches the pattern.
boolean find(int finds the next expression that matches the pattern from the given
3
start) start number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
static Pattern compile(String compiles the given regex and return the instance of
1
regex) pattern.
Matcher matcher(CharSequence creates a matcher that matches the given input with
2
input) pattern.
import [Link].*;
//1st way
Matcher m = [Link]("as");
boolean b = [Link]();
//2nd way
boolean b2=[Link](".s").matcher("as").matches();
//3rd way
}}
Output
5 [a-z&&[def]] d, e, or f (intersection)
1. import [Link].*;
2. class RegexExample3{
3. public static void main(String args[]){
4. [Link]([Link]("[amn]", "abcd"));//false (not a or m or n)
5. [Link]([Link]("[amn]", "a"));//true (among a or m or n)
6. [Link]([Link]("[amn]", "ammmna"));//false (m and a comes mor
e than once)
7. }}
Regex Quantifiers
1. import [Link].*;
2. class RegexExample4{
3. public static void main(String args[]){
4. [Link]("? quantifier ....");
5. [Link]([Link]("[amn]?", "a"));//true (a or m or n comes one time
)
6. [Link]([Link]("[amn]?", "aaa"));//false (a comes more than one t
ime)
7. [Link]([Link]("[amn]?", "aammmnn"));//false (a m and n comes
more than one time)
8. [Link]([Link]("[amn]?", "aazzta"));//false (a comes more than o
ne time)
9. [Link]([Link]("[amn]?", "am"));//false (a or m or n must come o
ne time)
10.
11. [Link]("+ quantifier ....");
12. [Link]([Link]("[amn]+", "a"));//true (a or m or n once or more ti
mes)
13. [Link]([Link]("[amn]+", "aaa"));//true (a comes more than one ti
me)
14. [Link]([Link]("[amn]+", "aammmnn"));//true (a or m or n comes
more than once)
15. [Link]([Link]("[amn]+", "aazzta"));//false (z and t are not matchi
ng pattern)
16.
17. [Link]("* quantifier ....");
18. [Link]([Link]("[amn]*", "ammmna"));//true (a or m or n may co
me zero or more times)
19.
20. }}
Regex Metacharacters
Regex Description
\b A word boundary
import [Link].*;
class RegexExample5{
}}
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:
1. statement 1;
2. statement 2;
3. statement 3;//exception occurs
4. statement 4;
5. statement 5;
Suppose there is 5 statements in your program and there occurs an exception at statement 3,
rest of the code will not be executed i.e. statement 4 to 5 will not run. If we perform
exception handling, rest of the statement will be executed. That is why we use exception
handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions [Link], SQLException etc. Checked
exceptions are checked at compile-time.
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. [Link]([Link]());//NullPointerException
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.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try
2. catch
3. finally
4. throw
5. throws
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.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block only.
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.
try{
int data=50/0;
}catch(ArithmeticException e){[Link](e);}
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
try{
a[5]=30/0;
}
Output:task1 completed
Rule: At a time only one Exception is occured 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 .
The try block within a try block is known as nested try block in java.
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)
....
class Excep6{
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
} }
Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
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.
Case 1:
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
try{
int data=25/0;
[Link](data);
catch(NullPointerException e){[Link](e);}
Case 2:
Let's see the java finally example where exception occurs and handled.
try{
int data=25/0;
[Link](data);
catch(ArithmeticException e){[Link](e);}
The Java throw keyword is used to explicitly throw an exception. We can throw either
checked or uncheked exception in java by throw keyword. The throw keyword is mainly used
to throw custom exception. We will see custom exceptions later.
1. throw exception;
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.
if(age<18)
else
[Link]("welcome to vote");
validate(13);
}
Output:
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
Applet class extends Panel. Panel class extends Container which is the subclass of
Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
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.
//[Link]
import [Link];
import [Link];
[Link]("welcome",150,150);
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
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 [Link]. Now Html file is not
required but it is for testing purpose only.
//[Link]
import [Link];
import [Link];
[Link]("welcome to applet",150,150);
/*
</applet>
*/
c:\>javac [Link]
c:\>appletviewer [Link]
import [Link];
import [Link].*;
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);
[Link]([Link]);
[Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
[Link]
<html>
<body>
</applet>
</body>
</html>
Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The [Link] class provide a method drawImage() to display the image.
The [Link] class provides getImage() method that returns the object of Image.
Syntax:
import [Link].*;
Image picture;
picture = getImage(getDocumentBase(),"[Link]");
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.
[Link]
<html>
<body>
</applet>
</body> </html>
Applet is mostly used in games and animation. For this purpose image is required to be
moved.
import [Link].*;
import [Link].*;
public class AnimationExample extends Applet {
Image picture;
picture =getImage(getDocumentBase(),"bike_1.gif");
for(int i=0;i<500;i++){
try{[Link](100);}catch(Exception e){}
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.
[Link]
<html>
<body>
</applet>
</body>
</html>
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see
the simple example of event handling in applet that prints a message by click on the button.
import [Link].*;
import [Link].*;
Button b;
TextField tf;
tf=new TextField();
[Link](30,40,150,20);
b=new Button("Click");
[Link](80,150,60,50);
add(b);add(tf);
[Link](this);
setLayout(null);
[Link]("Welcome");
In the above example, we have created all the controls in init() method because it is invoked
only once.
[Link]
<html>
<body>
</body>
</html>
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.
import [Link].*;
import [Link].*;
import [Link].*;
JButton b;
JTextField tf;
tf=new JTextField();
[Link](30,40,150,20);
b=new JButton("Click");
[Link](80,150,70,40);
add(b);add(tf);
[Link](this);
setLayout(null);
[Link]("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked
only once.
[Link]
<html>
<body>
</applet>
</body>
import [Link].*;
import [Link].*;
import [Link].*;
addMouseMotionListener(this);
setBackground([Link]);
Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
In the above example, getX() and getY() method of MouseEvent is used to get the current x-
axis and y-axis. The getGraphics() method of Component class returns the object of
Graphics.
[Link]
<html>
<body>
</applet>
</body>
</html>
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the
simple example:
1. import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
Thread t = null;
setBackground( [Link]);
[Link]();
try {
while (true) {
repaint();
catch (Exception e) { }
}
public void paint( Graphics g ) {
[Link]( [Link] );
In the above example, getX() and getY() method of MouseEvent is used to get the current x-
axis and y-axis. The getGraphics() method of Component class returns the object of
Graphics.
[Link]
<html>
<body>
</applet>
</body>
</html>
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
import [Link];
import [Link];
String str=getParameter("msg");
[Link](str,50, 50);
}
[Link]
<html>
<body>
</applet>
</body> </html>
One reason for the limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents, or peers. This means that
the look and feel of a component is defined by the platform, not by Java. Because the AWT
components use native code resources, they are referred to as heavyweight.
Before moving on, it is necessary to make one important point: although Swing eliminates a
number of the limitations inherent in the AWT, Swing does not replace it. Instead, Swing is
built on the foundation of the AWT. This is why the AWT is still a crucial part of Java.
A Swing GUI consists of two key items: components and containers. However, this
distinction is mostly conceptual because all containers are also components. The difference
between the two is found in their intended purpose: As the term is commonly used, a
component is an independent visual control, such as a push button or slider. A container holds
a group of components. Thus, a container is a special type of component that is designed to
hold other components. Furthermore, in order for a component to be displayed, it must be
held within a container. Thus, all Swing GUIs will have at least one container. Because
containers are components, a container can also hold other containers. This enables Swing to
define what is called a containment hierarchy, at the top of which must be a top-level
container.
Swing defines two types of containers. The first are top-level containers: JFrame, JApplet,
JWindow, and JDialog. These containers do not inherit JComponent. They do, however,
inherit the AWT classes Component and Container. Unlike Swing‟s other components, which
are lightweight, the top-level containers are heavyweight. This makes the top-level containers
a special case in the Swing component library. As the name implies, a top-level container
must be at the top of a containment hierarchy.
A top-level container is not contained within any other container. Furthermore, every
containment hierarchy must begin with a top-level container. The one most commonly used
for applications is JFrame. The one used for applets is JApplet. The second type of containers
supported by Swing are lightweight containers. Lightweight containers do inherit
JComponent. An example of a lightweight container is JPanel, which is a general-purpose
container. Lightweight containers are often used to organize and manage groups of related
components because a lightweight container can be contained within another container. Thus,
you can use lightweight containers such as JPanel
import [Link].*;
class SwingDemo {
SwingDemo() {
[Link](275, 100);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](jlab);
[Link](true);
[Link](new Runnable() {
new SwingDemo();
});
Output:-
Swing programs are compiled and run in the same way as other Java applications.
7.6 JLabel and ImageIcon: JLabel is Swing‟s easiest-to-use component. JLabel can be
used to
display text and/or an icon. It is a passive component in that it does not respond to user input.
JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be one
of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.
7.7 JTextField: JTextField is the simplest Swing text component. It is also probably its
most widely used text component. JTextField allows you to edit one line of text. It is derived
from JTextComponent, which provides the basic functionality common to Swing text
components. JTextField uses the Document interface for its model. Three of JTextField‟s
constructors is as shown here:
JTextField(int cols)
Here cols is the number of columns in the textfield. The text field is initially empty.
// Demonstrate JTextField.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus([Link]());
}
});
}
}.
7.8 JButton: the JButton class provides the functionality of a push button. You have
already seen a simple form of it in the preceding chapter. JButton allows an icon, a string, or
both to be associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button. When the button is pressed, an
ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( )
method of the registered ActionListener, you can obtain the action command string
associated with the button.
7.9 JToggleButton: A useful variation on the push button is called a toggle button. A
toggle button looks just like a push button, but it acts differently because it has two states:
pushed and released. That is, when you press a toggle button, it stays pressed rather than
popping back up as a regular push button does. When you press the toggle button a second
time, it releases (pops up). Therefore, each time a toggle button is pushed, it toggles between
its two states. JToggleButton defines several constructors one among them is
JToggleButton(String str)
// Demonstrate JToggleButton.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if([Link]())
[Link]("Button is on.");
else
[Link]("Button is off.");
}
});
// Add the toggle button and label to the content pane.
add(jtbn);
add(jlab);
}
}
The output from the toggle button example is shown here:
7.10 JCheck Boxes: The JCheckBox class provides the functionality of a check box. Its
immediate superclass is JToggleButton, which provides support for two-state buttons, as just
described. JCheckBox defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label.
// Demonstrate JCheckbox.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add check boxes to the content pane.
JCheckBox cb = new JCheckBox("C");
[Link](this);
add(cb);
cb = new JCheckBox("C++");
[Link](this);
add(cb);
cb = new JCheckBox("Java");
[Link](this);
add(cb);
cb = new JCheckBox("Perl");
[Link](this);
add(cb);
// Create the label and add it to the content pane.
jlab = new JLabel("Select languages");
add(jlab);
}
// Handle item events for the check boxes.
public void itemStateChanged(ItemEvent ie) {
JCheckBox cb = (JCheckBox)[Link]();
if([Link]())
[Link]([Link]() + " is selected");
else
[Link]([Link]() + " is cleared");
}
}
Output from this example is shown here:
7.11 JRadio Buttons: Radio buttons are a group of mutually exclusive buttons, in which
only one button can be selected at any one time. They are supported by the JRadioButton
class, which extends JToggleButton. JRadioButton provides several constructors. The one
used is shown here:
JRadioButton(String str)
Here, str is the label for the button.
// Demonstrate JRadioButton
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Create radio buttons and add them to content pane.
JRadioButton b1 = new JRadioButton("A");
[Link](this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a label and add it to the content pane.
jlab = new JLabel("Select One");
add(jlab);
}
// Handle button selection.
public void actionPerformed(ActionEvent ae) {
[Link]("You selected " + [Link]());
}
}
Output from the radio button example is shown here:
Here, name is the name for the tab, and comp is the component that should be added to
the tab.
7.13 JTable: JTable is a component that displays rows and columns of data. You can drag
the cursor on column boundaries to resize columns. You can also drag a column to a new
position. Depending on its configuration, it is also possible to select a row, column, or cell
within the table, and to change the data within a cell. JTable supplies several constructors.
The one used here is
Chapter 8
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
But we use multithreading than multiprocessing because threads share a common memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Each process have its own address in memory i.e. each process allocates separate
memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
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.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently
not eligible to run.
5) Terminated: A thread is in terminated or dead state when its run() method exits.
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to
be executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
Output:thread is running...
Thread class constructor allocates a new thread [Link] you create object of Multi
class,your class constructor is invoked(provided by Compiler) fromwhere Thread class
constructor is invoked(by super() as first statement).So your Multi class object is thread
object now.
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
[Link] you need to explicitely create Thread class [Link] are passing the object of your
class that implements Runnable so that your class run() method may execute.
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task executes
for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then
determines which task should execute next, based on priority and other factors.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
Syntax:
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
Output:Thread-0
Thread-1
The Thread class provides methods to change and get the name of a thread.
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:Sonoo Jaiswal
running...
The currentThread() method returns a reference to the currently executing thread object.
Output:Thread-0
Thread-1
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
If you have to perform single task by many threads, have only one run() [Link] example:
Program of performing single task by multiple threads
Output:task one
task one
task one
Program of performing single task by multiple threads
Output:task one
task one
If you have to perform multiple tasks by multiple threads,have multiple run() [Link]
example:
Program of performing two tasks by two threads
Output:task one
task two
1. class TestMultitasking4{
2. public static void main(String args[]){
3. Thread t1=new Thread(){
4. public void run(){
5. [Link]("task one");
6. }
7. };
8. Thread t2=new Thread(){
9. public void run(){
10. [Link]("task two");
11. }
12. };
13.
14.
15. [Link]();
16. [Link]();
17. }
18. }
Output:task one
task two
1. class TestMultitasking5{
2. public static void main(String args[]){
3. Runnable r1=new Runnable(){
4. public void run(){
5. [Link]("task one");
6. }
7. };
8.
9. Runnable r2=new Runnable(){
10. public void run(){
11. [Link]("task two");
12. }
13. };
14.
15. Thread t1=new Thread(r1);
16. Thread t2=new Thread(r2);
17.
18. [Link]();
19. [Link]();
20. } }
Output:task one
task two