Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Java programming material for beginners by Nithin, VVCE, Mysuru
1. INTRODUCTION ON JAVA
Java is related to C++, which is a direct derivative of C. much of the properties of java
is inherited from these two languages.
From C, java derives its syntax.
From C++, java derives object-oriented features.
Java programming language was introduced by James Gosling, Patrick Naughton,
Chris Warth and Ed Frank at Sun Microsystems in 1991. It took eighteen months to develop
the working version. This language was initially called „OAK‟ but was renamed as „Java‟ in
1995.
Java is a „programming language‟ and a „platform‟. It is a high level, robust, secured
and object-oriented programming language. Any hardware or software environment in which
a program runs is known as a „Platform‟. Since java has its own Runtime environment (JDE)
and Application programming interface (API), it can be called as a platform.
1.1 Types of Java applications.
There are mainly four types of applications that can be created using Java
programming.
1. Standalone applications: It is also known as „Desktop applications‟ or „Window
based applications‟. We need to install these applications on every machine and use
them. Some of these applications are Media player, Antivirus etc. „AWT and Swing‟
are used in java for creating standalone applications.
2. Web applications: An application that runs on the server side and creates a dynamic
page is called web application. Currently servlets, JSP, struts are used for creating
web applications in java.
3. Enterprise applications: An application that is distributed in nature such as banking
application is called enterprise applications. It has the advantage of high level
security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
4. Mobile applications: An application that is created for mobile devices are called as
mobile applications. Currently android and java mobile applications are used for
creating mobile applications.
1.2 Features of Java
There are many important fatures of java, they are also known as „Java buzzwords‟.
1. Simple : According to Sun Microsystems, Java language is simple because syntax is
based on C++ (easier to learn after C++) and removed many confusing features such
2. as explicit pointers, operator overloading etc and no need to remove unreferenced
objects because there is automatic garbage collection in java.
2. Object-oriented : Object-oriented programming (OOPS) is a methodology that
simplify software development and maintaince by providing some basic rules of
OOPS such as
Objects
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
3. Platform independent: A platform is the hardware and software environment in
which a program runs. There are two types of platforms : „Software-based‟ and
„Hardware based‟. Java provides software-based platform.
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.
3. 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.
1.3 Simple java program
To create a java program, we need to create a class that contains main method. For
executing any java program, we need to install JDK. Let‟s see this with an example
Class Simple
{
Public static void main (string args [] )
{
System.out.println (“ Hello Java “);
}
}
Save this file as “Simple.java”
To compile use “javac Simple.java”
To execute use “java Simple”
The meaning of the keywords used in the above example is as follows:
Class: It is a keyword used to declare a class in java.
Public: It is a keyword used as an access modifier which represents visibility.
If its public then it means its visible to all.
Static: It is a keyword which if declared static means that there is no need of
creating objects to invoke the method. In this way it saves memory.
Void: It is the return type of the method. It means that it does not return any
value.
Main: It represents the start of a program.
String [] args: It is used for command line argument.
System.out.println: It is used as a print statement.
4. In how many ways can we write a java program?
There are many ways to write a java program.
By changing the sequence of the modifier.
Static public void main (string agrs [])
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)
Having semicolon at the end of class in java is optional.
Class A
{
Static public void main (string … args)
{
System.out.println (“hello java”);
}
};
What happens at compile time?
At compile time, java file is compiled by java compiler and converts the java code
into byte code.
1.4 Java Environment
Understanding the difference between JDK, JRE and JVM is important in java.
Compiler
Class simple
{
}
Byte code
5. JVM: Java virtual machine is an abstract machine; it is a specification that provides runtime
environment in which java byte code can be executed.
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.
The JVM performs following main tasks
Loads code
Verifies code
Executes code
Provides runtime environment
JRE: Java runtime environment is used to provide runtime environment. It is the
implementation of JVM. It contains set of libraries and other files that JVM uses at runtime.
JDK: JDK is the acronym for java development kit. It contains JRE and other development
tools.
1.5 Variable and Data types in Java
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.
JVM
Set of libraries
Other files
JVM
Set of
libraries
Other files
Development tools
Ex: java, Javac etc
6. Variable
Variable is name of reserved area allocated in memory.
int data=10; //Here data is variable
Types of Variable
There are three types of variables in java
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.
Data Types in Java
7. 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 8byte
1.6 Operators in java
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
Postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
8. logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Chapter 2: Java OOPs Concepts
Object Oriented Programming is a paradigm that provides many concepts such as
inheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language. Smalltalk is considered as the first truly object-oriented
programming language.
2.1 OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects. It simplifies the software development and maintenance by providing
some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
9. 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.
Class: Collection of objects is called class. It is a logical entity.
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.
2.2 Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global
data can be accessed from anywhere.
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.
2.3 Java Naming conventions
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.
Advantage of naming conventions in java
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.
10. Name Convention
class name
should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.
interface
name
should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.
method name
should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
print(), println() etc.
variable
name
should start with lowercase letter e.g. firstName, orderNumber etc.
package
name
should be in lowercase letter e.g. java, lang, sql, util etc.
constants
name
should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
CamelCase in java naming conventions
Java follows camelcase syntax for naming the class, interface, method and variable.If
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
Syntax to declare a class:
class <class_name>{
data member;
method; }
11. 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{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output: 0 null
2.4 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
Example of Object and class that maintains the records of students
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{
12. 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,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output: 111 Karan
222 Aryan
2.5 Method Overloading in Java
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
13. 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.
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
14. 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{
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
Method Overloading and TypePromotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
15. 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.
Example of Method Overloading with TypePromotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b){System.out.println("int arg method invoked");}
void sum(long a,long b){System.out.println("long arg method invoked");}
public static void main(String args[]){
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
} }
Output: int arg method invoked
2.6 Constructor in java
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. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors: There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.
16. Syntax of default constructor:
1. <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.
Java parameterized constructor
A constructor that have 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{
17. 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,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
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.
Example of Constructor Overloading
class Student5{
int id;
18. 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,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
19. 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 can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
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).
Understanding problem without static variable
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.
Java static property is shared to all objects.
Example of static variable
20. //Program of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
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,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
} }
Output:111 Karan ITS
222 Aryan ITS
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.
21. Example of static method
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
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,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
22. }
}
Output: 111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
2.8 ‘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 6 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.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
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.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;
Student10(int id,String name){
id = id;
23. name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
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
class Student11{
int id;
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[]){
24. Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
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:
Program where this keyword is not required
class Student12{
int id;
String name;
Student12(int i,String n){
id = i;
name = n;
25. }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}
Output:111 Karan
222 Aryan
2.9 Inheritance in Java
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.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{ //methods and fields
}
26. 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.
Understanding the simple example of inheritance
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means that
Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
27. In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.
2.10 Aggregation in Java
Aggregation represents HAS-A relationship. Consider a situation, Employee object
contains many informations such as id, name, emailId etc. It contains one more object named
address, which contains its own informations such as city, state, country, zipcode etc. as
given below.
class Employee{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
Why use Aggregation?
For Code Reusability.
Simple Example of Aggregation
In this example, we have created the reference of Operation class in the Circle class.
class Operation{
int square(int n){
return n*n;
}
28. }
class Circle{
Operation op;//aggregation
double pi=3.14;
double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}
public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Output: 78.5
When use Aggregation?
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.
2.11 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.
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.
Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
29. 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).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method
overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
Output: Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
Real example of Java 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.
30. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
31. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
2.12 ‘super’ keyword in java
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.
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.
3. super is used to invoke immediate parent class method.
1) super is used to refer immediate parent class instance variable.
Problem without super keyword
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
32. }
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
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.
Solution by super keyword
//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();
33. } }
Output: 50
2) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor as given below:
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");}
34. }
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
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
Chapter 3: Java String
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:
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";
35. The java.lang.String 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.
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:
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
36. 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
1. 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).
Java String Example
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence
of char values.
No. Method Description
37. 1 char charAt(int index)
returns char value for the particular
index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
4
static String format(Locale l, String format, Object...
args)
returns formatted string with given
locale
5 String substring(int beginIndex)
returns substring for given begin
index
6 String substring(int beginIndex, int endIndex)
returns substring for given begin
index and end index
7 boolean contains(CharSequence s)
returns true or false after matching
the sequence of char value
8
static String join(CharSequence delimiter,
CharSequence... elements)
returns a joined string
9
static String join(CharSequence delimiter, Iterable<?
extends CharSequence> elements)
returns a joined string
10 boolean equals(Object another)
checks the equality of string with
object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
13 String replace(char old, char new)
replaces all occurrences of
specified char value
14
String replace(CharSequence old, CharSequence
new)
replaces all occurrences of
specified CharSequence
15 String trim()
returns trimmed string omitting
leading and trailing spaces
16 String split(String regex)
returns splitted string matching
regex
17 String split(String regex, int limit)
returns splitted string matching
regex and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex)
returns specified char value index
starting with given index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex)
returns specified substring index
starting with given index
23 String toLowerCase() returns string in lowercase.
24 String toLowerCase(Locale l)
returns string in lowercase using
specified locale.
25 String toUpperCase() returns string in uppercase.
26 String toUpperCase(Locale l)
returns string in uppercase using
specified locale.
38. 3.1 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.
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
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"
object.For example:
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
39. 4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose 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.
3.2 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
2. By = = operator
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:
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{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
41. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Output:true
false
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
3.3 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
42. 1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings. For Example:
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar
The Java compiler transforms above code to this:
1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
In java, String concatenation is implemented through the StringBuilder (or StringBuffer)
class and its append method. 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[]){
String s=50+30+"Sachin"+40+40;
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:
1. public String concat(String another)
43. Let's see the example of String concat() method.
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Sachin Tendulkar
3.4 Substring in Java
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.
Note: Index starts from 0.
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. System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).
Example of java substring
public class TestSubstring{
44. public static void main(String args[]){
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Tendulkar
Sachin
3.5 Java String class methods
The java.lang.String 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.
Let's see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
1. String s="Sachin";
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
1. String s=" Sachin ";
2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin
Sachin
Sachin
45. Java String startsWith() and endsWith() method
1. String s="Sachin";
2. System.out.println(s.startsWith("Sa"));//true
3. System.out.println(s.endsWith("n"));//true
true
true
Java String charAt() method
The string charAt() method returns a character at specified index.
1. String s="Sachin";
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h
S
h
Java String length() method
The string length() method returns length of the string.
1. String s="Sachin";
2. System.out.println(s.length());//6
6
Java String intern() method
A pool of strings, initially empty, is maintained privately by the class String.
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.
1. String s=new String("Sachin");
2. String s2=s.intern();
3. System.out.println(s2);//Sachin
Sachin
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.
1. String s1="Java is a programming language. Java is a platform. Java is an Island.";
46. 2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
"Kava"
3. System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Chapter 4: Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching or
manipulating strings.
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.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.
java.util.regex 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
It implements MatchResult interface. It is a regex engine i.e. used to perform match
operations on a character sequence.
No. Method Description
1 boolean matches() test whether the regular expression matches the pattern.
2 boolean find() finds the next expression that matches the pattern.
47. 3
boolean find(int
start)
finds the next expression that matches the pattern from the given
start number.
Pattern class
It is the compiled version of a regular expression. It is used to define a pattern for the regex
engine.
No. Method Description
1
static Pattern compile(String
regex)
compiles the given regex and return the instance of
pattern.
2
Matcher matcher(CharSequence
input)
creates a matcher that matches the given input with
pattern.
3
static boolean matches(String
regex, CharSequence input)
It works as the combination of compile and matcher
methods. It compiles the regular expression and
matches the given input with the pattern.
4 String[] split(CharSequence input)
splits the given input string around matches of given
pattern.
5 String pattern() returns the regex pattern.
Example of Java Regular Expressions
There are three ways to write the regex example in java.
import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();
//2nd way
48. boolean b2=Pattern.compile(".s").matcher("as").matches();
//3rd way
boolean b3 = Pattern.matches(".s", "as");
System.out.println(b+" "+b2+" "+b3);
}}
Output
true true true
Regex Character classes
No. Character Class Description
1 [abc] a, b, or c (simple class)
2 [^abc] Any character except a, b, or c (negation)
3 [a-zA-Z] a through z or A through Z, inclusive (range)
4 [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
5 [a-z&&[def]] d, e, or f (intersection)
6 [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)
Regular Expression Character classes Example
1. import java.util.regex.*;
2. class RegexExample3{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)
5. System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)
6. System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes mor
e than once)
7. }}
Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
49. Regex Description
X? X occurs once or not at all
X+ X occurs once or more times
X* X occurs zero or more times
X{n} X occurs n times only
X{n,} X occurs n or more times
X{y,z} X occurs at least y times but less than z times
Regular Expression Character classes and Quantifiers Example
1. import java.util.regex.*;
2. class RegexExample4{
3. public static void main(String args[]){
4. System.out.println("? quantifier ....");
5. System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time
)
6. System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one t
ime)
7. System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes
more than one time)
8. System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than o
ne time)
9. System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come o
ne time)
10.
11. System.out.println("+ quantifier ....");
12. System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more ti
mes)
13. System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one ti
me)
14. System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes
more than once)
15. System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matchi
ng pattern)
16.
17. System.out.println("* quantifier ....");
18. System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may co
me zero or more times)
50. 19.
20. }}
Regex Metacharacters
The regular expression metacharacters work as a short codes.
Regex Description
. Any character (may or may not match terminator)
d Any digits, short of [0-9]
D Any non-digit, short for [^0-9]
s Any whitespace character, short for [tnx0Bfr]
S Any non-whitespace character, short for [^s]
w Any word character, short for [a-zA-Z_0-9]
W Any non-word character, short for [^w]
b A word boundary
B A non word boundary
Regular Expression Metacharacters Example
import java.util.regex.*;
class RegexExample5{
public static void main(String args[]){
System.out.println("metacharacters d....");d means digit
System.out.println(Pattern.matches("d", "abc"));//false (non-digit)
System.out.println(Pattern.matches("d", "1"));//true (digit and comes once)
System.out.println(Pattern.matches("d", "4443"));//false (digit but comes more than onc
e)
System.out.println(Pattern.matches("d", "323abc"));//false (digit and char)
51. System.out.println("metacharacters D....");D means non-digit
System.out.println(Pattern.matches("D", "abc"));//false (non-
digit but comes more than once)
System.out.println(Pattern.matches("D", "1"));//false (digit)
System.out.println(Pattern.matches("D", "4443"));//false (digit)
System.out.println(Pattern.matches("D", "323abc"));//false (digit and char)
System.out.println(Pattern.matches("D", "m"));//true (non-digit and comes once)
System.out.println("metacharacters D with quantifier....");
System.out.println(Pattern.matches("D*", "mak"));//true (non-
digit and may come 0 or more times)
}}
Chapter 5: Exception Handling in Java
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
5.1 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:
1. statement 1;
2. statement 2;
52. 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
Difference between checked and unchecked exceptions
1) Checked Exception: The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as
unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
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.
1. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
53. If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. 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.
1. String s="abc";
2. 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:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Handling Keywords
There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
5.2 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
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
54. Syntax of try-finally block
1. try{
2. //code that may throw exception
3. }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
Let's try to understand the problem if we don't use try-catch block.
public class Testtrycatch1{
public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}
}
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, 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{
55. int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
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:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Java catch multiple exceptions
Java Multi catch block
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[5]=30/0;
56. }
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
rest of the code...
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 .
5.3 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
57. {
Statement 1;
Statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
58. 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..");
} }
5.4 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.
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
Case 1:
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;
59. System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 2:
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
60. rest of the code...
5.5 Java throw exception
The Java throw keyword is used to explicitly throw an exception. We can throw either
checked or uncheked exception in java by throw keyword. The throw keyword is mainly used
to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
1. throw exception;
Let's see the example of throw IOException.
1. throw new IOException("sorry device error);
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
61. Output:
Exception in thread main java.lang.ArithmeticException:not valid
Chapter 6: Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
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 platforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
Applet class extends Panel. Panel class extends Container which is the subclass of
Component.
6.1 Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet 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.
62. java.awt.Component class
The Component class provides 1 life cycle method of applet.
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.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
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);
}
}
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html
<html>
<body>
63. <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.jav
6.2 Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
64. 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.
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);
65. g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
6.3 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:
1. 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.
Syntax:
1. 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:
66. 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>
6.4 Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.
Example of animation in applet:
import java.awt.*;
import java.applet.*;
67. public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(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.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
6.5 EventHandling in Applet
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.
Example of EventHandling in applet:
68. import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
69. </applet>
</body>
</html>
6.6 JApplet class in Applet
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.
Example of EventHandling in JApplet:
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
70. }
In the above example, we have created all the controls in init() method because it is invoked
only once.
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
6.7 Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
Example of Painting in Applet:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
71. g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
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.
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
Digital clock in Applet
Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the
simple example:
Example of Digital clock in Applet:
1. import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class DigitalClock extends Applet implements Runnable {
Thread t = null;
int hours=0, minutes=0, seconds=0;
72. String timeString = "";
public void init() {
setBackground( Color.green);
}
public void start() {
t = new Thread( this );
t.start();
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = cal.getTime();
timeString = formatter.format( date );
repaint();
t.sleep( 1000 ); // interval given in milliseconds
}
}
catch (Exception e) { }
}
73. public void paint( Graphics g ) {
g.setColor( Color.blue );
g.drawString( timeString, 50, 50 );
}
}
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.
myapplet.html
<html>
<body>
<applet code="DigitalClock.class" width="300" height="300">
</applet>
</body>
</html>
6.8 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(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
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);
74. }
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body> </html>
Chapter 7: Java Swings
7.1 The Origins of Swing
Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present
in Java‟s original GUI subsystem: the Abstract Window Toolkit. The AWT defines a basic
set of controls, windows, and dialog boxes that support a usable, but limited graphical
interface.
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.
Swing Is Built on the AWT
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.
7.2 Two Key Swing Features
As just explained, Swing was created to address the limitations present in the AWT. It does
this through two key features:
Swing Components Are Lightweight: With very few exceptions, Swing components are
lightweight. This means that they are written entirely in Java and do not map directly to
platform-specific peers. Because lightweight components are rendered using graphics
primitives, they can be transparent, which enables nonrectangular shapes. Thus, lightweight
components are more efficient and more flexible.
75. Swing Supports a Pluggable Look and Feel: Swing supports a pluggable look and feel
(PLAF). Because each Swing component is rendered by Java code rather than by native
peers, the look and feel of a component is under the control of Swing. This fact means that it
is possible to separate the look and feel of a component from the logic of the component, and
this is what Swing does.
7.3 Components and Containers
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
7.4 A Simple Swing Application
The following program shows one way to write a Swing application. In the process, it
demonstrates several key features of Swing. It uses two Swing components: JFrame and
JLabel. JFrame is the top-level container that is commonly used for Swing applications.
JLabel is the Swing component that creates a label, which is a component that displays
information. The label is Swing‟s simplest component because it is passive. That is, a label
does not respond to user input. It just displays output. The program uses a JFrame container
to hold an instance of a JLabel. The label displays a short text message.
76. // A simple Swing application.
import javax.swing.*;
class SwingDemo {
SwingDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
Output:-
77. Swing programs are compiled and run in the same way as other Java applications.
7.5 Create a Swing Applet
The second type of program that commonly uses Swing is the applet. Swing-based applets
are similar to AWT-based applets, but with an important difference: A Swing applet extends
JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of
the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing
container, which means that it is not derived from JComponent.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet {
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
// Initialize the applet.
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc) {
System.out.println("Can't create because of "+ exc);
}
}
// Set up and initialize the GUI.
private void makeGUI() {
// Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
78. });
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});
// Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
}
}
Output:-
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.
// Demonstrate JLabel and ImageIcon.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
79. makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("france.gif");
// Create a label.
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add the label to the content pane.
add(jl);
}
}
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 java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
80. private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}
});
}
}.
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 java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JToggleButtonDemo" width=200 height=80>
</applet>
*/
public class JToggleButtonDemo extends JApplet {
JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(
81. new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("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.
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("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 java.awt.*;
82. import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=270 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("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");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Perl");
cb.addItemListener(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)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected");
else
jlab.setText(cb.getText() + " is cleared");
}
83. }
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 java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("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");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
84. b3.addActionListener(this);
add(b3);
// Define a button group.
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(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) {
jlab.setText("You selected " + ae.getActionCommand());
}
}
Output from the radio button example is shown here:
7.12 JTabbedPane: JTabbedPane encapsulates a tabbed pane. It manages a set of
components by linking them with tabs. Selecting a tab causes the component associated with
that tab to come to the forefront. Tabbed panes are very common in the modern GUI, and you
have no doubt used them many times. Given the complex nature of a tabbed pane, they are
surprisingly easy to create and use. JTabbedPane defines three constructors. We will use its
default constructor, which creates an empty control with the tabs positioned across the top of
the pane. The other two constructors let you specify the location of the tabs, which can be
along any of the four sides. Tabs are added by calling addTab( ). Here is one of its forms:
void addTab(String name, Component comp)
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
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads is a
one-dimensional array with the column headings. Here are the steps required to set up a
simple JTable that can be used to display data:
85. 1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
// Demonstrate JTable.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
86. }
}
Output from this example is shown here:
Chapter 8
Multithreading in Java
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. 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 occur in a single
thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved by two ways:
Process-based Multitasking(Multiprocessing)
87. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
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.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Note: At least one process is required for each thread.
What is Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution. Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
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.
8.1:Life cycle of a Thread (Thread States)
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.