Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Java PDF Merge

Uploaded by

Dhananjay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Java PDF Merge

Uploaded by

Dhananjay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 199

How Java differs from C and C++

Few major differences between C/C++ and Java programming language.


---------------------------------------------------------------------------------------------------

Java and C

1. Java does not include the C unique statement keywords sizeof and typedef.
2. Java does not contain the data types struct and union.
3. Java does not define the type modifiers keywords auto, extern, register, extern.
4. Java does not support explicit pointer.
5. Java does not have a preprocessor and therefore we cannot use #define, #include statement.
6. Java adds many features required for Object oriented programming.

Java and C++

1. Java does not support Operator overloading.


2. Java does not have template class.
3. Java does not support multiple inheritances of classes. This is accomplished using a new feature
called “interface”.
4. Java does not support global variables. Every variable and method is declared within a class.
5. Java does not use pointers.
6. Java has replaced the destructor function with a finalize() function.
7. There is no header file in Java.
Implementing A JAVA Program
Implementation of a Java application program involves a following step. They include:

1. Creating the program


2. Compiling the program
3. Running the program

Remember that, before we begin creating the program, the Java Development Kit (JDK) must be
properly installed on our system and also path will be set.

• Creating Program
We can create a program using Text Editor (Notepad) or IDE (NetBeans)
class Test
{
public static void main(String []args)
{
System.out.println("My First Java Program.");
}
};

File Save : d:\Test.java


• Compiling the program
To compile the program, we must run the Java compiler (javac), with the name of the
source file on “command prompt” like as follows

D:\javac Test.java

If everything is OK, the “javac” compiler creates a file called “Test.class” containing
byte code of the program.

• Running the program


We need to use the Java Interpreter to run a program.

d:\java Test
Now the interpreter looks for the main method in the program and begins execution from
there. After execution program successfully the output will be as follows,

Output:
My First Java Program.

Lets understand what above program : ---

class : class keyword is used to declare classes in Java

public : It is an access specifier. Public means this function is visible to all.

static : static is again a keyword used to make a function static. To execute a static function you do not
have to create an Object of the class. The main() method here is called by JVM, without creating any object
for class.

void : It is the return type, meaning this function will not return anything.

main : main() method is the most important method in a Java program. This is the method which is
executed, hence all the logic must be inside the main() method. If a java class is not having a main() method,
it causes compilation error.

String[] args : This is used to signify that the user may opt to enter parameters to the Java Program at
command line. We can use both String[] args or String args[]. Java compiler would accept both forms.

System.out.println : This is used to print anything on the console like “printf” in C language.
CLASSPATH

1. CLASSPATH describes a location where all required files are available which is used in our
application.

2. Java compiler and JVM will use CLASSPATH to locate required files.

3. If we do not set CLASSPATH then Java compiler will not able to find required files hence you
will get error.

PATH

1. PATH variable is set to provide path for all java tools like javac, java, appletviewer.

2. PATH describes a location where binary executables are available.

3. If we do not set PATH then our system will not be able to find where javac is; hence it will not
work. It is mandatory to set path.

How to set path in Java

If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all
the tools will be available in the current directory.

But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

1. Temporary
2. Permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

• Open command prompt


• copy the path of jdk/bin directory
• write in command prompt: set path=copied_path

For Example:

set path=C:\Program Files\Java\jdk1.7.0_15\bin


2) How to set Permanent Path of JDK in Windows 7

For setting the permanent path of JDK, you need to follow these steps:

Go to MyComputer properties ->Click on Advanced system settings -> select Advance Tab
->click on environment variables -> click on new button of user variable

write

Variable name: path

Variable Value: path of bin folder ( eg: c:\Program Files\Java\jdk1.8_51\bin;.;)

-> write path of bin folder in variable value -> ok -> ok -> ok
Variable Name: path

Under Variable value: c:\Program Files\Java\jdk1.8_51\bin; . ;


Q: Write a Java program to calculate the sum and product of two given number.

class Sample {
public static void main(String args[])
{
int a,b,sum=0,product=0;
a=10;
b=20;
sum=a+b;
product=a*b;
System.out.println("Sum="+sum);
System.out.println("Product="+product);
}
};

Q: Write a Java program to accept two numbers from the user and calculate sum and
product.

import java.util.*;
class Sample {
public static void main(String args[])
{
int a,b,sum=0,product=0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the First No:");
a=scan.nextInt();
System.out.println("Enter the Second No:");
b=scan.nextInt();
sum=a+b;
product=a*b;
System.out.println("Sum="+sum);
System.out.println("Product="+product);
}
}

Q: Write a Java program to accept two number from the user and calculate the average.

import java.util.*;
public class Sample {
public static void main(String args[])
{
double a,b,sum=0,avg=0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter the First No:");
a=scan.nextDouble();
System.out.println("Enter the Second No:")
b=scan.nextDouble();
sum=a+b;
avg=sum/2;
System.out.println("Average="+avg);
}
}

Q: Write a java program to convert fahrenheit to celsius and celsius to Fahrenheit using
formula c = (5.0/9.0)*(f-32).

import java.util.Scanner;
public class Fahrenheit_Celsius
{
public static void main(String[] args)
{
double c, f;
Scanner s = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit:");
f = s.nextDouble();
c = (5.0/9.0)*(f-32);
System.out.println("Temperature in Celsius:"+c);
}
}

Output:
Enter temperature in Fahrenheit:15
Temperature in Celsius:-9.444444444444445
Q: Write a Java program to calculate the area of triangle using three sides.

import java.lang.*;
import java.util.Scanner;
public class Area
{
public static void main(String[] args)
{

int a,b,c;
double s,area;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the three sides:");
a=scan.nextInt();
b=scan.nextInt();
c=scan.nextInt();
s=(a+b+c)/2;
area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.err.println("Area of Triangle:"+area);
}
}

Q: Write a Java program to calculate the given mathematical equation.


• b2 – 4ac
// Restrict the number of digits after decimal point in Java.
// formation the decimal values using the DecimalFormat class.

import java.util.Scanner;
import java.text.DecimalFormat;
public class Sample
{
public static void main(String[] args)
{
int a,b,c;
double s,area;
Scanner scan = new Scanner(System.in);

System.out.print("Enter the three sides:");


a=scan.nextInt();
b=scan.nextInt();
c=scan.nextInt();
s=(a+b+c)/2;
area=Math.sqrt(s*(s-a)*(s-b)*(s-c));

DecimalFormat fmt=new DecimalFormat("0.00");


System.err.println("Area of Triangle:"+fmt.format(area));
}
}
Can you save a java source file by other name than the class name?

Yes, if the class is not public

Can you have multiple classes in a java source file?

Yes.
What is Java?
Java is a general purpose; object oriented programming language developed by Sun Microsystems of USA
in 1995 later acquired by Oracle Corporation. Originally called Oak by James Gosling, one of the inventers
of the language. Java was designed for the development of software for consumer electronic devices like
TVs, VCRs, Toasters, set-top boxes and such other electronic machines. This goal had a strong impact on
the development team which included James Gosling, Mike Sheridan, and Patrick Naughton discovered
that the existing language like C and C++ had limitations in terms of both reliability and portability.
However they modeled their new language Java on C and C++ but removed a numbers of features of C and
C++ that were considered as source of problems and thus made Java a really simple, reliable, portable and
powerful language.

Platform: Any hardware or software environment in which a program runs is known as a platform. Since
Java has its own runtime environment (JRE) and API, it is called platform.

Where it is used?
There are many devices where java is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus etc.


2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

1
Types of Java Applications

There are mainly 4 types of applications that can be created using java programming:

1) Standalone Application

It is also known as desktop application or window-based application. An application that we need


to install on every machine such as media player, antivirus etc AWT and Swing are used in java
for creating standalone applications.
Example: Library Management System, Payroll System, Media player, antivirus, Paint etc.

2) Web Application

Web Applications are the client-server software application which is run by the client. . Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
Example: e-commerce website, bank website, Hotel Management System etc.

3) Enterprise Application

An application that is distributed in nature, such as banking applications Enterprise resource


planning (ERP) ,customer relationship management systems (CRM), supplier relationship
management systems (SRM). etc. etc. It has the advantage of high level security, load balancing
and clustering. In java, Enterprise Java Bean (EJB) is used for creating enterprise applications.
Example: Tally , SAP , HubSpot.

4) Mobile Application

An application that is created for mobile devices. Currently Android and Java ME (Micro edition)
are used for creating mobile applications.
Example: WhatsApp, Xender etc.

2
History of Java
The history of java starts from Green Team. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top boxes, televisions, VCRs,
Toasters etc.

For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc.

There are given the major point that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991
but Java was first released in 1995.The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Oak name for java language?

Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany,
Romania etc.

In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java name for java language?

➢ The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary",
"Silk", "jolt", "DNA" etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.

➢ According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.

➢ Java is an island of Indonesia where first coffee was produced (called java coffee).

➢ Notice that Java is just a name not an acronym.

3
➢ Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

Java Version History

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
11. Java SE 9 (2017)
12. Java SE 10 (2018)
13. Java SE 11 (2019)
14. Java SE 12 (2019)
15. Java SE 13 (2019)
16. Java SE 14 (2020)

4
Features of Java Programming Language
Java is Simple, Object oriented, Distributed, Robust, Platform independent, Secure, Architecture neutral,
Portable, High performance, Multithreaded, Dynamic language.

1. Simple

i. Java is developed from C and C++ language.

ii. Java is easy to learn and its syntax is quite simple, clean and easy to understand. The
syntax is similar to C language.

iii. The confusing and ambiguous concepts of C and C++ programming language are either
left out in Java or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in Java but were an important part
of C++.
iv. There is no structure, union keyword in java

v. Java does not support multiple inheritance.

2. Object Oriented Programming

Java supports class, object, data encapsulation, data abstraction, inheritance, polymorphism that’s
why java is called OOP language.

3. Distributed

Java is also a distributed language. Programs can be designed to run on computer networks. Java
has a special class library for communicating using TCP/IP protocols.

You can create such types of application in java that you can run on two or more than two machine.
Some part of that program is running on one machine and some part of program running on other
machine.

Creating network connections is very much easy in Java as compared to C/C++.

Network programming (Socket Programming), Remote Method Invocation (RMI) and Enterprise
Java Bean (EJB) are used for creating distributed application.

4. Robust

Robustness is the capacity of a computer system to handle the errors during execution and manage
the incorrect input of data. Java is robust because it utilizes strong memory management. There is
an absence of pointers that avoids/bypasses security problem. There is automatic garbage collection
in Java which runs on the Java Virtual Machine to eliminate objects which are not being accepted
by a Java application anymore. There are type-checking mechanisms and exception-handling in
Java. All these features make Java robust.

5
5. Secured

Java is best known for its security. With java, we can develop virus free system. Java is secure
because

• No explicit pointer

• Java programs runs inside a virtual machine.

• Java language provides security by default.

• Some security can also be provided by an application developer explicitly through SSL,
Cryptography etc.

6. Platform Independent

Unlike other programming languages such as C, C++ etc which are compiled into platform specific
machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any machine with
Java Runtime Environment can run Java Programs.

7. Architecture Neutral

Because of Byte code you can run java code on any hardware configuration.

8. Portable

We may carry the java byte code to any platform.

9. High Performance

Java is an interpreted language, so it will never be as fast as a compiled language like C or C++.
But, Java enables high performance with the use of just-in-time compiler.

“java has so many feature which is help to high performace. like oop, multhreading, Exception
handling etc.”

6
10. Multithreading

Thread means it’s a part of process which handles one particular job at a time. If more than one
thread in the program i.e known as multithreaded application. Multitasking is possible because of
multithreading. Threads are important for many application such as gaming, multi-media, web
applications etc.

11. Dynamic

In java, memory allocation is takes place always dynamically.

7
CLASSPATH

1. CLASSPATH describes a location where all required files are available which is used in our
application.

2. Java compiler and JVM will use CLASSPATH to locate required files.

3. If we do not set CLASSPATH then Java compiler will not able to find required files hence you
will get error.

PATH

1. PATH variable is set to provide path for all java tools like javac, java, appletviewer.

2. PATH describes a location where binary executables are available.

3. If we do not set PATH then our system will not be able to find where javac is; hence it will not
work. It is mandatory to set path.

How to set path in Java

If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all
the tools will be available in the current directory.

But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

1. Temporary
2. Permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

• Open command prompt


• copy the path of jdk/bin directory
• write in command prompt: set path=copied_path

For Example:

set path=C:\Program Files\Java\jdk1.7.0_15\bin

8
2) How to set Permanent Path of JDK in Windows 7

For setting the permanent path of JDK, you need to follow these steps:

Go to MyComputer properties ->Click on Advanced system settings -> select Advance Tab
->click on environment variables -> click on new button of user variable

write

Variable name: path

Variable Value: path of bin folder ( eg: c:\Program Files\Java\jdk1.8_51\bin;.;)

-> write path of bin folder in variable value -> ok -> ok -> ok

9
10
Variable in Java

When we want to store any information, we store it in an address of the computer.


Instead of remembering the complex address where we have stored our information,
we name that address. The naming of an address is known as variable. Variable is
the name of memory location.

In other words, variable is a name which is used to store a value of any type during
program execution.

Syntax

data-type variable-name;

Here, datatype refers to type of variable which can any like: int, float etc.
and variableName can be any like: empId, amount, price etc.

Java Programming language defines mainly three kinds of variables.

1. Instance Variables (Object Variable)


2. Static Variables (Class Variables)
3. Local Variables

1. Instance variables

Instance variables are variables that are declare inside a class but outside any
method, constructor or block. Instance variable are also variable of object
commonly known as field or property. They are referred as object variable.
Each object has its own copy of each variable and thus, it doesn't affect the
instance variable if one object changes the value of the variable.
class student
{
int rollno;
String name;
}

Here, rollno and name are instance variable of Student class.

2. Static Variables
Static are class variables declared with static keyword. Static variables are
initialized only once.
class student
{
int rollno;
String name;
Static int collegCode=1001;
}

Here collegeCode is a static variable. Each object of Student class will share
collegeCode property.
3. Local Variables

Local variables are declared in method, constructor or block. Local variables


are initialized when method, constructor or block start and will be destroyed
once its end. Local variable reside in stack. Access modifiers are not used for
local variable.

double getDiscount(int price)


{
double discount;
discount=price*(20/100);
return discount;
}

Here discount is a local variable.


Java Tokens
Tokens are smallest individual units in a program that has some meaning to the
compiler. Java Language includes 5 types of tokens:-

1. Keywords
2. Identifiers
3. Literals or Constants
4. Operator
5. Separator

1. Keywords :

• Keywords are pre-defined or reserved words in a java programming


language.

• Keywords are special words that are significant to the java compiler.

• We cannot use keywords as variable names, class names, method names


and interface names because by doing so, we are trying to assign a new
meaning to the keyword which is not allowed.

class interface abstract switch case break default

continue for while do if else open

byte short int long float double char

boolean import extends implements final return void

super new static native package public private

protected synchronized transient thread this volatile

try catch finally throw throws


2. Identifier:

Identifiers are used as the general terminology for naming of variables,


functions, arrays, classes, packages and interface in a program.

Java identifiers follow the following rules

i. It must begin with alphabets, underscore and dollar sign characters.

ii. It must not begin with digit but can contain digits within.

iii. Identifiers in Java are case sensitive. (i.e. Uppercase and Lowercase
letters are distinct.)

iv. Identifier name cannot contain white spaces.

v. It can be of any length

vi. You cannot use keywords as identifiers.

3. Literals or Constant:

• Literals in Java are a sequence of characters i.e. digits, letters & other
characters that represent constant values to be stored in variable.

• Literals are also like normal variables. But, the only difference is, their
values cannot be modified or changed by the program once they are
defined.

• Literals refer to fixed values.

• Literals may belong to any of the data type.

Syntax:

<final> <data_type> <variable_name>;

eg: final int tax_rate=5;


• Java specifies 5 major types of literals:

1. Integer literals

2. Floating point literals

3. Character literals

4. String literals

5. Boolean literals

4. Operator:

• Java supports a rich set of operators such as =, +, -, * etc that can be


used according to the need of the application.

• An operator is a symbol that tells the computer to perform certain


mathematical or logical manipulations.

• Operators are used in programs to manipulate data and variables.

• Operators are usually parts of mathematical or logical expression.

Types of Operators:
I. Arithmetic Operators

II. Relational Operators or Comparison Operators

III. Logical Operators

IV. Assignment Operators

V. Increment and Decrement Operators

VI. Conditional Operators

VII. Bitwise Operators


I. Arithmetic Operators:

Arithmetic operators are used to performing addition, subtraction, multiplication,


division, and modulus. It acts as a mathematical operation.

Operator Description

+ ( Addition ) This operator is used to add the value of the operands.

– ( Subtraction ) This operator and is used to subtract two operands.


* ( This operator is used to multiply the value of the operands.
Multiplication )
/ ( Division ) This operator is used to divide the left hand operator with
right hand operator.
% ( Modulus ) This operator is used to divide the left hand operator with
right hand operator and returns remainder.

Example:

public class Test {

public static void main ( String[] args ) {

int a = 10;

int b = 20;

System.out.println ( a + b );

System.out.println ( a – b );

System.out.println ( a * b );

System.out.println ( a / b );

System.out.println ( a % b );

}
Output:

30

-10

200

10

II. Relational Operator:

• Relational operator compares two numbers and returns a boolean value.


• This operator is used to define a relation or test between two operands.
• All the relational operators are binary operator.
Example: we may compare the age of two persons, compare the price of two items
etc.
Operator Description

< (Less than) This operator returns True, if the value of the left operand
is less than the value of the right operand, else it returns
False.

> (Greater than) This operator returns True, if the value of the left operand
is greater than the value of the right operand, else it returns
False.

<= (Less than or This operator returns True, if the value of the left operand
equal to) is less than or equal to the value of the right operand, else it
returns False.

>= (Greater This operator returns True, if the value of the left operand
than or equal is greater than or equal to the value of the right operand,
to) else it returns False.

== (Equal to) This operator returns True, if two operands are equal, else
it returns False.
!= (Not equal to) This operator returns True, if two operands are not equal,
else it returns False.

Example:
public class Sample {
public static void main ( String[] args ) {
int a = 10;
int b = 20;
System.out.println ( a < b );
System.out.println( a > b );
System.out.println ( a <= b );
System.out.println (a >= b );
System.out.println ( a == b );
System.out.println ( a != b );
}
}
Output :

true

false

true

false

false

true
III. Logical Operator

Logical operators are used to combining two or more conditions or relational expression.

Operator Description

&& (Logical AND) This operator returns True if both the operands are true,
otherwise, it returns False.

|| (Logical OR) This operator returns True if either the operands are true,
otherwise it returns False.

! (Logical AND) This operator returns True if an operand is False. It


reverses the logical state of an operand.

Example:

public class Test {

public static void main ( String args[] ) {

int a = 5;

System.out.println ( a<5 && a<20 );

System.out.println ( a<5 || a<20 );

System.out.println ( ! ( a<5 && a<20 ));

Output:

false

true

true
IV. Assignment Operator

• Assignment operators are used to assign new value to a variable.


• The left side operand of the assignment operator is called variable and the right side
operand of the assignment operator is called value.
Syntax:
var = expression ;
Here, the data type of “var” must be compatible with the type of expression.
• It allows to create a chain of assignment
Eg:
int a,b,c;
a=b=c=100;

Operator Description

= This operator is used to assign the value on the right to the


operand on the left.

+= This operator is used to add right operand to the left


operand and assigns the result to the left operand.

-= This operator subtracts right operand from the left operand


and assigns the result to the left operand.

*=
This operator multiplies right operand with the left operand
and assigns the result to the left operand.

/= This operator divides left operand with the right operand


and assigns the result to the left operand.

^= This operator performs exponential calculation on operators


and assigns value to the left operand

%= This operator is used to divide the left-hand operator with


right hand operator and assigns the result to left operand.
Example:

public class Test {

public static void main ( String[] args ) {

int a = 10;

int b = 20;

int c;

System.out.println ( c = a );

System.out.println ( b += a );

System.out.println ( b -= a);

System.out.println ( b *= a );

System.out.println ( b /= a );

Output:

10

30

10

200

2
V. Increment and Decrement

The increment (++) operator (also known as increment unary operator) in Java is used to
increase the value of a variable by 1. Since it is a type of a unary operator, it can be used with
a single operand.

Syntax
The syntax for increment operator is a pair of addition signs ie;

++x;

x++;

The operator can be applied either before or after the variable. Both will have the same
increment of 1. However, they both have separate uses and can be categorized as the
following types.

• Pre-Increment Operator
• Post-Increment Operator

Example:
public class IncrementOperator {

public static void main(String[] args) {

int variable = 15;


System.out.println("Original value of the variable = " + variable);

// after using increment operator


variable++; // increments 1, variable = 16
System.out.println("variable++ = " + variable);

++variable; // increments 1, variable = 17


System.out.println("++variable = " + variable);
}
}

Output
Original value of the variable = 15

variable++ = 16

++variable = 17
Pre-Increment Operator (++x;)

If the increment operator (++) is specified before the variable like a prefix (++x), then it is
called pre-increment operator. In this case, the value of the variable is first incremented by
1, and then further computations are performed.

Example:

public class PreIncrementOperator {

public static void main(String[] args) {

int variable = 5;
System.out.println("Original value of the variable = " + variable);

// using pre-increment operator


int preIncrement = ++variable;

System.out.println("variable = " + variable);


System.out.println("preIncrement = " + preIncrement);
System.out.println("++preIncrement = " + ++preIncrement);
}
}

Output
Original value of the variable = 5

variable = 6

preIncrement = 6

++preIncrement = 7

Post-Increment Operator (x++;)

If the increment operator (++) is specified after the variable like a postfix (x++), then it is
called post-increment operator. In this case, the original value of the variable (without
increment) is used for computations and then it is incremented by 1.

public class PostIncrementOperator {

public static void main(String[] args) {


int variable = 100;
System.out.println("Original value of the variable = " + variable);

// using post-increment operator


int postIncrement = variable++; // postIncrement = 100, variable = 101

System.out.println("postIncrement = " + postIncrement);


System.out.println("variable = " + variable + "\n");

// postIncrement = 101
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 102
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 103
System.out.println("postIncrement++ = " + postIncrement++);

System.out.println("\npostIncrement = " + postIncrement);


}
}

Output
Original variable = 100
postIncrement = 100
variable = 101
postIncrement++ = 100
postIncrement++ = 101
postIncrement++ = 102
postIncrement = 103

Decrement Operator (--)

Decrement as the name implies is used to reduce the value of a variable by 1. It is also one
of the unary operator types, so it can be used with a single operand.

Syntax
The syntax for decrement operator is a pair of negative signs ie;

--x; x--;
Just like the increment operator, the decrement (--) operator can also be applied before and
after the variable. Both will result in the same decrement of 1. They both have distinct uses
and can be diverged in the further types.

• Pre-Decrement Operator
• Post-Decrement Operator

Pre-Decrement Operator (--x;)

If the decrement operator (--) is mentioned before the variable like a prefix (--x), then it is
called a pre-decrement operator. For this case, the value of the variable is first decremented
by 1, and then other computations are performed.

Example:

public class PreDecrementOperator {

public static void main(String[] args) {

int variable = 11;


System.out.println("Original value of the variable = " + variable);

// using preDecrement operator


int preDecrement = --variable;

// variable = 10
System.out.println("variable = " + variable);
// preDecrement = 10
System.out.println("preDecrement = " + preDecrement);
// preDecrement = 9
System.out.println("--preDecrement = " + --preDecrement);
}
}

Output
Original value of the variable = 11
variable = 10
preDecrement = 10
--preDecrement = 9
Post-Decrement Operator (x--;)

If the decrement operator (--) is mentioned after the variable like a postfix (x--), then it is
called a post-decrement operator. For this case, the original value of the variable (without
decrement) is used for computations and then it is decremented by 1.

Example:

public class PostDecrementOperator {

public static void main(String[] args) {

int variable = 75;


System.out.println("Original value of the variable = " + variable);

// using postDecrement operator


// postDecrement = 75, variable = 74
int postDecrement = variable--;
System.out.println("postDecrement = " + postDecrement);
System.out.println("variable = " + variable + "\n");
// postDecrement = 74
System.out.println("postDecrement-- = " + postDecrement--);
// postDecrement = 73
System.out.println("postDecrement-- = " + postDecrement--);
// postDecrement = 72
System.out.println("postDecrement-- = " + postDecrement--);

System.out.println("\npostDecrement = " + postDecrement);


}
}

Output

Original value of the variable = 75


postDecrement = 75
variable = 74
postDecrement-- = 75
postDecrement-- = 74
postDecrement-- = 73
postDecrement = 72
VI. Conditional Operator
Ternary operator is a conditional operator; it reduces the line of code while performing the
conditional or comparisons. It is the replacement of if-else or nested if-else statements.
Syntax :

( Condition ) ? ( Statement1 ) : ( Statement2 );

Here Condition is the expression to be evaluated which will return the boolean value. If the
Condition result is True then Statement1 will be executed. If the Condition result is false
then Statement2 will be executed.

Example:

public class Test {


public static void main ( String args[] ) {
int a = 4;
int b = 9;
int min = ( a<b ) ? a : b;
System.out.println ( min );
}
}

Output :

Q: Write a Java program to accept two numbers from the user and print the maximum
number by using conditional operator.

Q: Write a Java program to accept one number from the user and check whether the given
number is ODD number or EVEN number by using conditional operator.

Q: Write a Java program to accept three numbers from the user and print the maximum
number by using conditional operator.
VII. Bitwise Operators

• Java support special operators known as bitwise operators for manipulating of data
at values of bit level.
• These operators are used for testing the bits, or shifting them to right or left.
• The basic bitwise operators are:

Operator Description

& (Bitwise AND) This operator takes two numbers as operands and does
AND on every bit of two numbers.

| (Bitwise OR) This operator takes two numbers as operands and does
OR on every bit of two numbers.

^ (Bitwise XOR) This operator takes two numbers as operands and does
XOR on every bit of two numbers.

~( Bitwise unary NOT) This operator takes one number as an operand and
does invert all bits of that number.

<<( Shift left) The left shift operator moves all bits by a given
number of bits to the left.

>>( Shift right) The right shift operator moves all bits by a given
number of bits to the right.
Example:

public class Test {


public static void main( String[] args ) {
int a = 58;
int b = 13;
System.out.println ( a&b );
System.out.println ( a|b );
System.out.println ( a^b );
}
}

Output :

63

55

Example:

class Test {

public static void main(String[] args)


{
int number = 2;

// 2 bit left shift operation


int Ans = number << 2;

System.out.println(Ans);
}
}
Output :

Example:

class Test

public static void main (String[] args) {

int number = 8;

// 2 bit signed right shift

int Ans = number >> 2;

System.out.println(Ans);

Output :

5. Separators:

Separators are symbols used to indicate where groups of code are divided and arranged.
Separator basically defines the shape and function of our code.

Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Comma ( , ): It is used to separate consecutive identifiers in a variable declaration also used
inside “for loop” statements.
Semi colon ( ; ) : It is used to separate statement.
Period ( . ): It is used to separate package names from sub-packages; also used to separate a
variable or method from a reference variable.
Data Types in Java
Every variable in java has a data type. Data types specify the size and type of values that can be
stored in an identifier. Java language is rich in its data types. The variety of data types available
allow the programmer to select the type appropriate to the need of application.

In java, data types are classified into two categories:

1. Primitive Data type or Intrinsic or built in data type


2. Non-Primitive Data type or derived or reference data type

Data Type

Primitive Non- primitive

Numeric Non-Numeric class Interface Array

Integer Floating point Character Boolean

Integer
This group includes byte, short, int, long
byte : It is 1 byte(8-bits) integer data type. Value range from -128 to 127. Default value zero.
example: byte b=10;

short : It is 2 bytes(16-bits) integer data type. Value range from -32768 to 32767. Default value
zero. example: short s=11;

int : It is 4 bytes(32-bits) integer data type. Value range from -2147483648 to 2147483647.
Default value zero. example: int i=10;

long : It is 8 bytes(64-bits) integer data type. Value range from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. Default value zero. example: long l=100012;
Example:

public class Demo{

public static void main(String[] args) {


// byte type
byte b = 20;
System.out.println("b= "+b);

// short type
short s = 20;
System.out.println("s= "+s);

// int type
int i = 20;
System.out.println("i= "+i);

// long type
long l = 20;
System.out.println("l= "+l);

}
}

Floating-Point Number

This group includes float, double

float : It is 4 bytes(32-bits) float data type. Default value 0.0f. example: float ff=10.3f;

double : It is 8 bytes(64-bits) float data type. Default value 0.0d. example: double db=11.123;

public class Demo{

public static void main(String[] args) {


// float type
float f = 20.25f;
System.out.println("f= "+f);

// double type
double d = 20.25;
System.out.println("d= "+d);

} }
Characters
This group represent char, which represent symbols in a character set, like letters and numbers.

char : It is 2 bytes(16-bits) unsigned unicode character. Range 0 to 65,535.

example: char c='a';

public class Demo {

public static void main(String[] args) {

char ch = 'S';
System.out.println(ch);

char ch2 = '&';


System.out.println(ch2);

char ch3 = '$';


System.out.println(ch3);

Boolean
Boolean type is used when we want to test a particular condition during the execution of the
program. There are only two values that a Boolean type can take: ture or false.

Remember, both these words have been declared as keyword. Boolean type is denoted by the
keyword boolean and uses only 1 bit of storage.

public class Demo {

public static void main(String[] args) {

boolean t = true;
System.out.println(t);

boolean f = false;
System.out.println(f); }}
Type Casting in Java
Casting is a process of changing one type value to another type. In Java, we can cast one type of
value to another type. It is known as type casting.

In Java, type casting is classified into two types,

1. Automatic type conversion or Implicit

2. Explicitly

1. Automatic type conversion or Implicit

Automatic Type casting take place when,

• the two types are compatible


• the target type is larger than the source type

class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

2. Explicitly
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting. If we don't perform casting then compiler reports compile
time error.

class Test

public static void main(String[] args)

double d = 100.04;

long l = (long)d; //explicit type casting required

int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);

System.out.println("Long value "+l);

System.out.println("Int value "+i);

}
}
Variable in Java
When we want to store any information, we store it in an address of the computer. Instead of
remembering the complex address where we have stored our information, we name that address.
The naming of an address is known as variable. Variable is the name of memory location.
In other words, variable is a name which is used to store a value of any type during program
execution.
Syntax
data-type variable-name;
eg:
int a;
String sname,addr,city;

Here, datatype refers to type of variable which can any like: int, float etc. and variableName can
be any like: empId, amount, price etc.
Java Programming language defines mainly three kinds of variables.
Rno=1001 Rno=1002
1. Instance Variables Name=”XYZ Name=”B”
2. Static Variables (Class Variables) ”
3. Local Variables

1. Instance variables
Instance variables are variables that are declare inside a class but outside any
method,constructor or block. Instance variable are also variable of object commonly
known as field or property. They are referred as object variable. Each object has its own
copy of each variable and thus, it doesn't affect the instance variable if one object changes
the value of the variable.

class student
{
int rollno;
String name;
}

Here, rollno and name are instance variable of Student class.


2. Static Variables

Static are class variables declared with static keyword. Static variables are initialized only
once.
class student
{
int rollno;
String name;
static int collegCode=1001;
}

Here collegeCode is a static variable. Each object of Student class will share
collegeCode property.

3. Local Variables

Local variables are declared in method, constructor or block. Local variables are initialized
when method, constructor or block start and will be destroyed once its end. Local variable
reside in stack. Access modifiers are not used for local variable.

double getDiscount(int price)


{
double discount;
discount=price*(20/100);
return discount;
}

Here discount is a local variable.


Wrapper class in Java

• Wrapper class provides the mechanism to convert primitive data type into
object is called boxing and object into primitive data type is called
unboxing.

• Since J2SE 5.0, auto boxing and unboxing feature converts primitive data type
into object and object into primitive data type automatically.

• The automatic conversion of primitive data type into object is known as auto-
boxing and vice-versa auto-unboxing.

One of the eight classes of java.lang package is known as wrapper class in Java.

The list of eight wrapper classes is given below:

Primitive Type Wrapper class


boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

1
Wrapper class Example:

Primitive to Object

public class WrapperExample1{

public static void main(String args[]){

//Converting int into Integer

int a=20;

Integer i=Integer.valueOf(a);//converting int data type into Integer

Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally

System.out.println(a+" "+i+" "+j);

Output: 20 20 20

2
Wrapper class Example:

Object to Primitive Data Type

public class WrapperExample2{

public static void main(String args[]){

//Converting Integer to int

Integer a=new Integer(3);

int i=a.intValue(); //unboxing i.e converting Integer to int

int j=a; //auto unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);

Output: 333

Q: WA Java program to accept one character from the command line /


user. Check whether the given character in Upper case, Lower case, digit
or special character. Solve this problem by using the concept of Wrapper
class.

3
String in java

Generally, String is a sequence of characters. But in Java, String 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. By string literal

Java String literal is created by using double quotes.

Example:

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 object or instance is returned. If string doesn't exist in the pool,
a new string object or instance is created and placed in the String constant pool.

For example:

String s1="Welcome";

String s2="Welcome";//will not create new instance

1
In the given example only one object will be created. Firstly JVM will not find any string object with the
value "Welcome" in string constant pool, so it will create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create new object but will return the reference to the
same instance.

Note: String objects are stored in a special memory area known as string constant pool.

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).

2. By new keyword

String s=new String("Welcome"); or String name=new String(br.readLine());

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).

Example:

public class StringExample{

public static void main(String args[]){

String s1=new String("example");//creating java string by new keyword

//this statement create two object i.e first object is created in heap
//memory area and second object is create in String constant pool.

System.out.println(s1);

}}

2
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.

class Demo{

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

o/p: Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is
created with “Sachin Tendulkar”. That is why string is known as immutable.

3
As you can see in the given figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
For example:

class Demo{

public static void main(String args[]){

String s="Sachin";

s=s.concat(" Tendulkar");

System.out.println(s);

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.

String class Methods/ Functions

1. char charAt(int index) – return the character value at the given index number.

The index number starts from 0 and goes to n-1, where n is length of the string. It
returns StringIndexOutOfBoundsException if given index number is greater than or equal
to this string length or a negative number.

Eg:

class Demo{

public static void main(String args[]){

String str="Ram";

System.out.println(str.charAt(0)); // R }}

2. int length() – returns the total number of character in the string.

4
Eg:

class Demo{

public static void main(String args[]){

String str="Ram Singh";

System.out.println(str.length()); // 9

3. String concat(String str) – combines specified string at the end of this string. It returns combined
string. It is like appending another string.

Eg:

class Demo{

public static void main(String args[]){

String str="Manjeet";

System.out.println(""+str.concat(" Kumar"));}

4. boolean equals(String str) – return true if this String contains the same character as str(including
case) and false otherwise.

Eg:

class Demo{

public static void main(String args[]){

String str="Manjeet";

System.out.println(""+str.equals("Manjeet"));

}} output: true

5
5. int compareTo(String str) – return an integer indication if this string is lexically before( a negative
return value), equal to(a zero return value) or lexically after( a positive return value).

class Demo{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}

6. String replace(char oldchar, char newchar) – return a new String that is identical with this String
except that every occurrence of old-char is replaced by new-char.

class Demo{

public static void main(String args[]){

String str="Manjeet";

System.out.println(""+str.replace('M','R'));}} o/p: Ranjeet

7. String toLowerCase() – return a new string identical to this string. All uppercase letters are
converted to their lowercase equivalent.

class Demo{

public static void main(String args[]){

String str="MANJEET";

System.out.println(""+str.toLowerCase());}

o/p: manjeet

6
8. String toUpperCase() – return a new string identical to this string. All lowercase letters are
converted to their uppercase equivalent.

class Demo{

public static void main(String args[]){

String str="manjeet";

System.out.println(""+str.toUpperCase());

o/p: MANJEET

9. substring

A part of string is called substring. There are two signature of substring() method in Java.

I. public String substring(int startIndex) –

This method returns new String object containing the substring of the
given string from specified startIndex.

class Demo{

public static void main(String args[]){

String str="manjeet";

System.out.println(""+str.substring(3));

o/p: jeet

II. 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 – 1.

class Demo{

public static void main(String args[]){

String str="manjeet";

7
System.out.println(""+str.substring(3,6));

o/p: jee

10. String trim() – This method omitted/eliminates leading and trailing space of the given string.

11. split()

The split() method splits the string against given regular expression and returns a array of Sting.

There are two signature of substring() method in Java.

A. public String[] split(String regex);

B. public String[] split(String regex, int limit);

Parameter

regex: regular expression to be applied on String.

limit: limit for the number of strings in array. If it is zero, it will returns all the Strings
matching in regex.

1 .Eg: split the string on the basis of single while space character (\\s) or for multiple
while space (\\s+)

class Demo{

public static void main(String args[]){

String str="I am 5th semester B.Tech student";

String s[]=str.split("\\s");

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

8
Output:

am

5th

semester

B.Tech

student

2.Eg: split the string on the basis of “/” character

class Demo{

public static void main(String args[]){

String str="10/01/2020";

String s[]=str.split("/");

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

Output:

10

01

2020

3.Eg: split the string on the basis of “,” and “?” character.( i.e for multiple regex)

class Demo{

public static void main(String args[]){

String str="java . string , split method ? by Manjeet kumar";

9
String s[]=str.split("[\\,\\?]");

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

Output:

java . string

split method

by Manjeet kumar

4. eg

class Demo{

public static void main(String args[]){

String str="10/01/2020";

String s[]=str.split("/", 1 );

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

Output:

10/01/2020

5.eg

class Demo{

public static void main(String args[]){

String str="10/01/2020";

10
String s[]=str.split("/", 2 );

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

Output:

10

01/2020

6.eg

class Demo{

public static void main(String args[]){

String str="10/01/2020";

String s[]=str.split("/", 3);

int i;

for( i=0;i<s.length;i++ )

System.out.println(""+s[i]);

Output:

10

01

2020

11
12. public char[] toCharArray()

this method converts the String into character array, its length is similar to the string.

Eg:

class Demo{

public static void main(String args[]){

String str="Manjeet";

char ch[]=str.toCharArray();

int i;

for( i=0;i<ch.length;i++ )

System.out.print(""+ch[i]); }

Output:

Manjeet

Q:. Write a program to reverse String in java using toCharArray() method.

import java.io.*;
import java.util.*;

public class reverseString {


public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
12
Note: length() is a method of a String class; which returns the number of characters in the String whereas
.length is a property of an array; will give the number of elements stored in the array (length of an array).

13
StringBuffer class
StringBuffer class is used to created mutable (modifiable) string. The StringBuffer
class in Java is same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer class

StringBuffer(): creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the specified capacity
as length.

What is mutable string?

A string that can be modified or changed is known as mutable string. StringBuffer


and StringBuilder classes are used for creating mutable string.

1) append() method

The append() method concatenates the given argument with this string.
e.g:
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);
}
}

Output: Hello Java

1|Page
import java.util.*;
public class Employee {

int eid;
Scanner sc=new Scanner(System.in);
StringBuffer name=new StringBuffer();
StringBuffer desgn=new StringBuffer();
int sal;
void readData()
{
System.out.println("Enter the Employee ID:");
eid=Integer.parseInt(sc.nextLine());
System.out.println("Enter the Name:");
name.append(sc.nextLine());
System.out.println("Enter the Designation:");
desgn.append(sc.nextLine());
System.out.println("Enter the Salary:");
sal=Integer.parseInt(sc.nextLine());
}

void display()
{

System.out.println(eid+"\t"+name+"\t"+desgn+"\t"+sal)
;
}

public static void main(String args[])


{
Employee e=new Employee();
e.readData();
e.display();
}
}

2) insert() method

The insert() method inserts the given string with this string at the given position.
e.g:
class A{
public static void main(String args[]){

2|Page
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb);

}
}
Output: HJavaello
3) replace() method

The replace() method replaces the given string from the specified beginIndex and
endIndex-1.

e.g:

class A{
public static void main(String args[]){

StringBuffer sb=new StringBuffer("Hello");


sb.replace(1,3,"Java");
System.out.println(sb);

}
}

Output: HJavalo

4) delete() method
The delete() method of StringBuffer class deletes the string from the specified
beginIndex to endIndex-1.

e.g:

class A{

3|Page
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);
}
}
Output: Hlo

5) reverse() method

The reverse() method of StringBuilder class reverses the current string.


e.g:
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);
}
}

Output: olleH

4|Page
6) capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer.
The default capacity of the buffer is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2.

For example if your current capacity is 16, it will be (16*2)+2=34.


e.g:
class A{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Difference between StringBuffer and StringBuilde

StringBuffer Example

5|Page
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
StringBuilder Example

public class BuilderTest{


public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}

Performance Test of StringBuffer and StringBuilder

public class PTest{


public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() -
startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() -
startTime) + "ms");
}
}

o/p:

Time taken by StringBuffer: 16ms


Time taken by StringBuilder: 0ms

6|Page
Access Specifiers in Java

→ Java Access Specifiers (also known as Visibility Specifiers ) regulate access to


classes, fields and methods in Java.

→ Java Access Specifiers determine whether a field or method in a class, can be used
or invoked by another method in another class or sub-class.

→ Java Access Specifiers can be used to restrict access.

→ Access Specifiers are an integral part of object-oriented programming.

Types Of Access Specifiers :

In java we have four Access Specifiers and they are listed below.

1. Public
2. Private
3. Protected
4. Default(no specifier)

Public specifiers :

→ Public specifiers achieve the highest level of accessibility.


→ Classes, methods, and fields declared as public can be accessed from any class in
the Java program, whether these classes are in the same package or in another
package.
Example:

public class Demo { // public class


public x, y, size; // public instance variables
public void find_fact(){}// public method

Private specifiers :

→ Private specifiers achieve the lowest level of accessibility.


→ Private methods and fields can only be accessed within the same class to which the
methods and fields belong.
→ Private methods and fields are not visible within subclasses and are not inherited
by subclasses. So, the private access specifier is opposite to the public access
specifier.
→ Using private specifier we can achieve encapsulation and hide data from the outside
world.

Example:

class Demo {

private double x, y; // private (encapsulated) instance variables


private void find_fact(){}// private method
}

class Test
{

private int age=18;


private void Msg()
{
System.out.println("Age="+age);
}

public static void main(String args[])


{
Test d=new Test();
System.out.println("Age="+d.age);
d.Msg();
}

class Demo
{
private int age=18;
private void Msg()
{
System.out.println("Age="+age);
}
}

class Test
{

public static void main(String args[])


{
Demo d=new Demo();
System.out.println("Age="+d.age);
d.Msg();
}

}
Protected specifiers :

→ Methods and fields declared as protected can be accessed by the subclasses in the
same package or can be accessed by the subclasses in the other package.

→ The protected access specifier cannot be applied to class and interfaces.

Example:

class Demo {

protected double x, y; // protected instance variables


protected void find_fact(){} //protected method

default (no specifier):

→ When you don't set access specifier for the element, it will follow the default
accessibility level.
→ There is no default specifier keyword.
→ Classes, variables, and methods can be default accessed.
→ Using default specifier we can access class, method, or field which belongs to same
package, but not from outside this package.

Eg.

class Demo
{

int i; //Default access specifier instance variable

void display(){} // method uses Default access specifier


}
//Accessible within the subclass outside the package

package mypack;

import java.util.Scanner;
public class Person
{
int id;
String name;
protected void set_data()
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the Id:");
id=scan.nextInt();
System.out.println("Enter the Name:");
name=scan.next();
}
protected void display()
{
System.out.print(id+"\t"+name+"\t");
}

};

import mypack.Person;
import java.util.Scanner;
class Test extends Person
{

intsal;
public void set_data()
{
super.set_data();
Scanner scan=new Scanner(System.in);
System.out.println("Enter the sal:");
sal=scan.nextInt();
}

public void display()


{
super.display();
System.out.print(sal);
}

public static void main(String args[])


{
Test p=new Test ();
p.set_data();
p.display();
}
}
Tight Coupling
When two classes are highly dependent on each other, it is called tight coupling. It occurs
when a class takes too many responsibilities or where a change in one class requires changes
in the other class. In tight coupling, an object (parent object) creates another object (child
object) for its usage. If the parent object knows more about how the child object was
implemented, we can say that the parent and child object are tightly coupled.
Example: Imagine you have created two classes A and B, in your program. Class A is called
volume, and class B evaluates the volume of a cylinder. If you make any changes in the
volume, then the same changes will reflect in class B. Hence, we can say both the classes are
highly dependent on each other and are tightly coupled.
Code

class Volume {
public static void main(String args[]) {
Cylinder b = new Cylinder(15, 15, 15);
System.out.println(b.volume);
}
}

class Cylinder {
public int volume;
Cylinder(int length, int width, int height) {
this.volume = length * width * height; }
}

Explanation: In the above example, class Volume and class Cylinder are bound
together and work with each other as a team.
Method Overriding in Java
• If subclass (child class) has the same method prototype as declared in the
parent class, it is known as method overriding in Java.
• When a method in a subclass has the same name, same parameters or
signature and same return type as a method in its super-class, then the
method in the subclass is said to override the method in the super-class.
• Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism.
• It must be an IS-A relationship (inheritance).

Eg:
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run() // overridden method
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
//defining the same method prototype as in the parent class
void run() //overriding method
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike obj = new Bike();//creating object
obj.run();//calling method
}
}

Eg:
class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

class Test {

public static void main(String args[]) {


Animal a; // Animal reference
a = new Animal(); // Animal object
a.move(); // runs the method in Animal class
a = new Dog(); // Dog object

a.move(); // runs the method in Dog class


}
}

Output:
Animals can move
Dogs can walk and run
Interface
Interface just defines what a class must do without saying anything about its
implementation.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface without going into its implementation details,
which are left for the person implementing the interface.

Interface is used to support the functionality of multiple inheritances.


In other words, you can say that interfaces can have abstract methods and variables.
It cannot have a method body.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.

• By interface, we can support the functionality of multiple inheritance.

• It can be used to achieve loose coupling.


• Loose coupling is a design goal that seeks to reduce the inter-dependencies between
components of the system/class with the goal of reducing the risk that the changes in one
component will require changes in any other component. Loose coupling is much more
generic concept intended to increase the flexibility of system, make it more maintainable
and makes the entire framework more stable.

• One interface reference variable can hold different types of implementing class memory.

Example:

GSM Mobile (can capabilty to hold different types of Network)

Vodafone
Airtel
Idea
TataDoccomo

Declare interface

An interface is declared by using the interface keyword.


A class that implements an interface must implement all the methods declared in the
interface.

Syntax:

interface <interface_name>

// declare constant fields

// declare methods that abstract

// by default.

}
✓ Interface fields are public, static and final by default, and
✓ Interface methods are public and abstract by default.

Example:

Printable interface has only one method, and its implementation is provided in the Test class.

interface Printable{

void display();

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, means
agreeing to perform the behaviors of the interface. If a class does not perform all the behaviors
of the interface, the class must declare itself as abstract.

A class uses the “implements” keyword to implement an interface.


class Test implements Printable{

public void display(){System.out.println("Hello");}

public static void main(String args[]){

Test obj = new Test ();

obj.display();

Example:

Example:

interface Drawable{

void draw();

class Rectangle implements Drawable{

public void draw(){System.out.println("drawing rectangle");}

class Circle implements Drawable{

public void draw(){System.out.println("drawing circle");}

class TestInterface{

public static void main(String args[]){

Drawable d=new Circle();

d.draw(); }}
Q: We have to calculate the area of a rectangle, a square and a circle. Create an
interface 'Shape' with three methods namely 'RectangleArea' 'SquareArea' and
'CircleArea'. Now create another class 'Area' inheriting the class “Shape”. class 'Area'
containing all the three methods 'RectangleArea', 'SquareArea' and 'CircleArea' for
printing the area of rectangle, square and circle respectively. Create an object of class
'Area' and call all the three methods.

import java.io.*;

public interface Shape {

void rectangleArea();

void squareArea() throws IOException;

void circleArea()throws IOException;;

import java.io.*;

public class Area implements Shape {

int l,b,s,r;

double a;

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

public void rectangleArea()

try{

System.out.println("Enter the length:");

l=Integer.parseInt(br.readLine());

System.out.println("Enter the width:");


b=Integer.parseInt(br.readLine());

a=l*b;

System.out.println("Area of Rectangle:"+a);

}catch(Exception ex){ex.printStackTrace();}

public void squareArea() throws IOException

System.out.println("Enter the side:");

s=Integer.parseInt(br.readLine());

a=s*s;

System.out.println("Area of SquareArea:"+a);

public void circleArea() throws IOException

System.out.println("Enter the radius:");

r=Integer.parseInt(br.readLine());

a=Math.PI*Math.pow(r,2);

System.out.println("Area of CircleArea:"+a);

public static void main(String args[]) throws IOException

Area a=new Area();


a.rectangleArea();

a.squareArea();

a.circleArea();

Example:

import java.util.*;

interface Tax
{
final int trate=5;
void calculateTax();
}

class Book implements Tax


{
int bid, bprice; String bname;
int priceAfterTax;
public void set_data()
{
Scanner scan=new Scanner(System.in);
System.out.println(“Enter Book ID:”);
bid=scan.nextInt();
System.out.println(“Enter Book Name:”);
bname=scan.next();
System.out.println(“Enter Book Price:”);
bprice=scan.nextInt();
}
public void calculateTax()
{
priceAfterTax =bprice+(bprice*trate)/100;
}
void display()
{
System.out.println(“Book ID:”+ bid);
System.out.println(“Book Name:”+ bname);
System.out.println(“Book Price:”+ bprice);
System.out.println(“Price after Tax:”+ priceAfterTax);
}

public static void main(String args[])


{
Book b=new Book();
b.set_data();
b.calculateTax();
b.display();
}

}
Multiple inheritance in Java by interface

If a class implements multiple interfaces, ( or ) one class and one interface, ( or ) an


interface extends multiple interfaces, it is known as multiple inheritance.
Eg_1:

interface A{

void m1();

interface B{

void m2();

class TestMultipleInheritance implements A , B{

public void m1(){System.out.println("Hello");}

public void m2(){System.out.println("Welcome");}

public static void main(String args[]){

TestMultipleInheritance obj = new TestMultipleInheritance();

obj.m1();

obj.m2();

} }

Eg_2. Develop a Java program to demonstrate the use of multiple inheritance.


import java.util.*;

interface Tax

final int trate=5;

void calculateTax();

class Publication{

String pname;

public Publication(String n)

pname=n;

class Book extends Publication implements Tax{

int bid, bprice; String bname;

int priceAfterTax;

public Book(int id,String bn,String pn,int bp){

super(pn);

this.bname=bn;

this.bid=id;

this.bprice=bp;

public void calculateTax(){


priceAfterTax =bprice+(bprice*trate)/100;

void display(){

System.out.println("Book Id \t Name \t PublicationName \t Price \t Price_After_Tax" );

S.o.println(bid+ "\t" +bname+"\t"+pname+ "\t" + "\t\t"+ bprice+ "\t\t"+ priceAfterTax);

public static void main(String args[]){

Book b=new Book(1001, "Java","BPB Publication",100);

b.calculateTax();

b.display();

Extending an Interface

An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.

When a class implements an interface that inherits another interface, it must provide
implementations for all the methods defined within the interface inheritance chain.

Eg:

interface A
{
void m1();
void m2();
}
interface B extends A
{
void m1();

class Test implements B


{

public void m1() {


System.out.println(“m1”);
}

public void m2() {


System.out.println(“m2”);
}

public void m3() {


System.out.println(“m3”);
}

public static void main(String args[]) {


Test obj=new Test();
obj.m1();
obj.m2();
obj.m3();

}}
Q: Create two interfaces in java, first interface contain trate1 as
attribute and calculateFirstTax as method and second interface
contain trate2 as attribute and calculateSecondTax as method.
Create Food class with proper attribute (i.e foodId, foodName and
foodPrice) and method which implements above interface.

Q. Write a JAVA program which has

i. An Interface class for Stack Operations


ii. A Class that implements the Stack Interface and creates a fixed length Stack.

Characteristics of Interface
1. Interface can be declared as abstract but it is seldom done.
2. Since interfaces are meant to be implemented by classes, interface members implicitly
have public accessibility and the public modifier is omitted.
3. The methods are interface are all implicitly abstract and public. A method prototype
has the same syntax as an abstract method.
4. Regardless of how many interfaces a class implements directly or indirectly, it only
provides single implementations of a method that might have multiple declarations
in the interface.
5. Method prototype declarations can also be overloaded as in the case of classes.

Question: Create interface class Staff with members’ names and addresses and
abstract method i.e. accept and display. Define two sub-classes of this class –
“FullTimeStaff” (department, salary) and “PartTimeStaff” (number-of-hours, rate-
per hour). Create “N” objects which could be of either FullTimeStaff or PartTimeStaff
class by asking the user’s choice. Display details of all “FullTimeStaff” or all
“PartTimeStaff”.

import java.io.*;

interface Staff{

String name,address;

public abstract void accept();

public abstract void display();

class FullTimeStaff implements Staff{

String department;

double salary;
public void accept() throws IOException{

System.out.println("Enter the name, address, department and salary: ");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

name=br.readLine();

address=br.readLine();

department=br.readLine();

salary=Double.parseDouble(br.readLine());

public void display(){

System.out.println("Name: "+name);

System.out.println("Address: "+address);

System.out.println("Department: "+department);

System.out.println("Salary: "+salary);

System.out.println("----------------------");

class PartTimeStaff implements Staff{

int hours, rate;


public void accept() throws IOException{

System.out.println("Enter the name, address, No of working hours and rate per


hour: ");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

name=br.readLine();

address=br.readLine();

hours=Integer.parseInt(br.readLine());

rate=Integer.parseInt(br.readLine());

public void display(){

System.out.println("Name: "+name);

System.out.println("Address: "+address);

System.out.println("No of Working Hours: "+hours);

System.out.println("Rate per hour: "+rate);

System.out.println("----------------------");

}
public class Menu {

public static void main(String [] args) throws IOException{

int i;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("1.Full Time Staff");

System.out.println("2.Part Time Satff");

System.out.println("Select Any One: ");

int ch=Integer.parseInt(br.readLine());

switch(ch){

case 1:

System.out.println("Enter the number of Full Time Staff: ");

int n=Integer.parseInt(br.readLine());

FullTimeStaff [] l=new FullTimeStaff[n];

for(i=0;i<n;i++){

l[i]=new FullTimeStaff();

l[i].accept();

for(i=0;i<n;i++){
l[i].display();

break;

case 2:

System.out.println("Enter the number of Part Time Staff: ");

int m=Integer.parseInt(br.readLine());

PartTimeStaff [] h=new PartTimeStaff[m];

for(i=0;i<m;i++){

h[i]=new PartTimeStaff();

h[i].accept();

for(i=0;i<m;i++){

h[i].display();

break;

}
Java Networking
Java Networking is a concept of connecting two or more computing devices together
so that we can share resources.

Java socket programming provides facility to share data between different computing
devices.

Advantage of Java Networking

1. sharing resources
2. centralize software management

Java Networking Terminology

The widely used java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address

IP address is a unique number assigned to a node/computer of a network e.g.


192.168.0.1. It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol

A protocol is a set of rules basically that is followed for communication.

For example:

• TCP
• FTP
• Telnet
• SMTP
• POP etc.

3) Port Number

The port number is used to uniquely identify different applications. It acts as a


communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.

1
4) MAC Address

MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable


but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not


reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.

(An endpoint is a remote computing device that communicates back and forth with a network to which
it is connected. meaning they pass information back and forth)

Java Socket Programming

Java Socket programming is used for communication between the applications


running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:

• IP Address of Server, and


• Port number.

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.

2
ServerSocket

The ServerSocket class can be used to create a server socket.


ServerSocket object is used to establish communication with the clients.

Example: socket programming in which client sends a text and server receives it.

File: MyServer.java

import java.io.*;

import java.net.*;

public class MyServer {

public static void main(String[] args){

try{

ServerSocket ss=new ServerSocket(6666);

Socket s=ss.accept(); //establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream());

String str=(String)dis.readUTF();

System.out.println("message= "+str);

ss.close();

}catch(Exception e){System.out.println(e);}

3
File: MyClient.java

import java.io.*;

import java.net.*;

public class MyClient {

public static void main(String[] args) {

try{

Socket s=new Socket("localhost",6666);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

dout.writeUTF("Hello Server");

dout.close();

s.close();

}catch(Exception e){System.out.println(e);}

Process: To execute this program open two command prompts and execute each program at
each command prompt.

After running the client application, a message will be displayed on the server console.

4
Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes
on.

File: MyServer.java

import java.net.*;

import java.io.*;

class MyServer{

public static void main(String args[])throws Exception{

ServerSocket ss=new ServerSocket(3333);

Socket s=ss.accept();

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){

str=din.readUTF();

System.out.println("client says: "+str);

str2=br.readLine();

dout.writeUTF(str2);

dout.flush();

din.close();

s.close();

ss.close();

}}

5
File: MyClient.java

import java.net.*;

import java.io.*;

class MyClient{

public static void main(String args[])throws Exception{

Socket s=new Socket("localhost",3333);

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){

str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

}}

6
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

DatagramSocket class

Java DatagramSocket class represents a connection-less socket for sending and


receiving datagram packets.

A datagram is basically information but there is no guarantee of its content, arrival


or arrival time.

Commonly used Constructors of DatagramSocket class

• DatagramSocket() throws SocketException:


It creates a datagram socket and binds it with the available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketException:
It creates a datagram socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketException:
It creates a datagram socket and binds it with the specified port number and host address.

DatagramPacket class

Java DatagramPacket is a message that can be sent or received. If you send multiple packets,
it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

• DatagramPacket(byte[] barr, int length): it creates a datagram packet.


This constructor is used to receive the packets of length length. The length must be
less than or equal to the barr.length.

• DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a


datagram packet.
This constructor is used to send the packets of the length to the specified port on the
specified host.
The length must be less than or equal to the barr.length.

barr – the Packet data


length- the packet length
address- destination address
port- destination port number

Example: //DSender.java

7
import java.net.*;

public class DSender{

public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket();

String str = "Welcome java";

InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);

ds.send(dp);

ds.close(); encoding this string into a sequence of bytes

//DReceiver.java

import java.net.*;

public class DReceiver{

public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket(3000);

byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);

ds.receive(dp);

String str = new String(dp.getData(), 0, dp.getLength());

System.out.println(str);
public String(byte[] bytes, int offset, int length)
ds.close();
bytes – the bytes to decoded into characters
}

} offset – the index of the first byte to decode

length – The number of bytes to decode.

8
Java Inner Class
Java inner class or nested class is a class i.e. declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more readable
and maintainable.

Additionally, it can access all the members of outer class including private data members and methods.

Syntax

class Java_Outer_class{

//code

class Java_Inner_class{

//code

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members (data members
and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it logically group
classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java


Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes


There are two types of nested classes; non-static and static nested classes. The non-static nested classes are
also known as inner classes.

1. Non-static nested class (inner class)

a) Member inner class

b) Anonymous inner class

c) Local inner class

2. Static nested class

1
Java Member inner class
A non-static class that is created inside a class but outside a method is called member inner class.

Syntax:

class Outer{

//code

class Inner{

//code

} }

Example:

class TestMemberOuter{

private int data=30;

class Inner{

void msg(){System.out.println("data is "+data);}

public static void main(String args[])

TestMemberOuter obj=new TestMemberOuter();

TestMemberOuter.Inner in=obj.new Inner();

in.msg();

}
2
Note: The java compiler creates two class files in case of inner class. The class file name of inner
class is "TestMemberOuter$Inner".

Java Anonymous inner class


A class that has no name is known as anonymous inner class in java. It should be used if you have to
override method of class or interface.

Java Anonymous inner class can be created by two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


abstract class Person{

abstract void eat();

classTestAnonymousInner{ 1. A class is created but its name is decided


by the compiler which extends the Person
public static void main(String args[]){
class and provides the implementation of
Person p=new Person(){
the eat() method.
void eat() 2. An object of Anonymous class is created
{ that is referred by p reference variable of
System.out.println("nice fruits"); Person type.

};

p.eat();

3
Java anonymous inner class example using interface
interface Eatable{

void eat();

class TestAnnonymousInner1{

public static void main(String args[]){

Eatable e=new Eatable(){

public void eat(){System.out.println("nice fruits");}

};

e.eat();

Java Local inner class


A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate this class inside the
method.

Example

public class TestLocalInner{

private int data=30; //instance variable

void display(){

class Local{

void msg(){System.out.println(data);}

Local l=new Local();

l.msg();

public static void main(String args[]){

TestLocalInner obj=new TestLocalInner();

obj.display();

} }
4
Note: Local inner class cannot be invoked from outside the method.

Java static nested class


A static class i.e. created inside a class is called static nested class in java.
It cannot access non-static data members and methods.
It can be accessed by outer class name.
• It can access static data members of outer class including private.
• Static nested class cannot access non-static (instance) data member or method.

Example

classTestOuter{

static int data=30;

static class Inner{

void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestOuter.Inner obj=new TestOuter1.Inner();

obj.msg();

Java static nested class example with static method


If you have the static member inside static nested class, you don't need to create instance of static nested
class.

class TestOuter{

static int data=30;

static class Inner{

static void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestOuter.Inner.msg();//no need to create the instance of static nested class

}
5
Calendar
Calendar class in Java is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH, YEAR,
HOUR, etc.

As it is an Abstract class, so we cannot use a constructor to create an instance.


Instead, we will have to use the static method Calendar.getInstance() to instantiate
and implement a sub-class.

• Calendar.getInstance(): return a Calendar instance based on the current time in


the default time zone with the default locale.

Java program to demonstrate getInstance() method:

// Date getTime(): It is used to return a Date object representing this


// Calendar's time value.

import java.util.*;
public class DemoCalendar {
public static void main(String args[])
{
Calendar c = Calendar.getInstance();
System.out.println("The Current Date is:" + c.getTime());
}
}

METHOD DESCRIPTION

It is used to add or subtract the specified amount


abstract void add(int
of time to the given calendar field, based on the
field, int amount)
calendar’s rules.

It is used to return the value of the given calendar


int get(int field)
field.

abstract int It is used to return the maximum value for the


getMaximum(int field) given calendar field of this Calendar instance.

abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.

It is used to return a Date object representing this


Date getTime()
Calendar’s time value.
Program 1: Java program to demonstrate get() method.

// Program to demonstrate get() method


// of Calendar class

import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating Calendar object
Calendar calendar = Calendar.getInstance();

// Demonstrate Calendar's get()method


System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
}
}

Program 2: Java program to demonstrate getMaximum() method.

// Program to demonstrate getMaximum() method


// of Calendar class

import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();

int max = calendar.getMaximum(Calendar.DAY_OF_WEEK);


System.out.println("Maximum number of days in a week: " + max);

max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in a year: " + max);
}
}

Program 3: Java program to demonstrate the getMinimum() method.

// Program to demonstrate getMinimum() method


// of Calendar class

import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();

int min = calendar.getMinimum(Calendar.DAY_OF_WEEK);


System.out.println("Minimum number of days in week: " + min);

min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + min);
}
}

Program 4: Java program to demonstrate add() method.

// Program to demonstrate add() method of Calendar class

import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 4);
System.out.println("After 4 days : " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}

GregorianCalendar is a concrete subclass(one which has implementation of all of its


inherited members either from interface or abstract class) of a Calendar that
implements the most widely used Gregorian Calendar with which we are familiar.

java.util.GregorianCalendar vs java.util.Calendar

The major difference between GregorianCalendar and Calendar classes are that
the Calendar Class being an abstract class cannot be instantiated. So an object of
the Calendar Class is initialized as:

Calendar cal = Calendar.getInstance();

Here, an object named cal of Calendar Class is initialized with the current date and
time in the default locale and timezone. Whereas, GregorianCalendar Class being a
concrete class, can be instantiated. So an object of the GregorianCalendar Class is
initialized as:

GregorianCalendar gcal = new GregorianCalendar();


Note: The major difference between GregorianCalendar and Calendar (Julian calendar)
classes are that the Calendar Class being an abstract class cannot be instantiated. So an
object of the Calendar Class is initialized as:

Calendar cal = Calendar. getInstance();

import java.util.*;
class demo{
public static void main(String args[])
{
Date dt=new Date();
System.out.println("System Date:"+dt);

Calendar c=Calendar.getInstance();

System.out.println("Tody's Date :"+c.get(Calendar.DATE));


System.out.println("Tody's Month :"+c.get(Calendar.MONTH));
System.out.println("Tody's Year :"+c.get(Calendar.YEAR));
System.out.println("System Date:");
System.out.println(c.get(Calendar.MONTH)+"/"+c.get(Calendar.DATE)+"/"+c.get(Calendar.YEAR));

System.out.println(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));

GregorianCalendar gc=new GregorianCalendar();

System.out.println(gc.get(Calendar.MONTH)+"/"+gc.get(Calendar.DATE)+"/"+gc.get(Calendar.YEAR));

int x=gc.get(Calendar.YEAR);

if(gc.isLeapYear(x))
System.out.println("Leap Year");
else
System.out.println("Not a Leap Year");
}
}

public void add()


{
try{

String cby="Manjeet";
java.util.Date dt=new java.util.Date();

java.sql.Date sqlDate=new java.sql.Date(dt.getTime());


java.sql.Timestamp sqlTime=new java.sql.Timestamp(dt.getTime());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter the ID:");
int id=Integer.parseInt(br.readLine());
System.out.println("Enter the Name:");
String name=br.readLine();
System.out.println("Enter the Email ID:");
String email=br.readLine();
System.out.println("Enter the Password:");
String pwd=br.readLine();
String query="insert into emp values
("+id+",'"+name+"','"+email+"','"+pwd+"','"+cby+"','"+sqlDate+"')";
int x=DatabaseConnection.insertUpdateFromSqlQuery(query);
if(x>0)
System.out.println("Record Inserted Successfully.");
else
System.out.println("Error in inserting Record.");

}catch(Exception ex){ex.printStackTrace();}
}

public void viewDerbyDatabase()


{
try{

String query="select * from tblemp ";


SimpleDateFormat fmt=new SimpleDateFormat("dd-MM-YYYY");
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection
conn=DriverManager.getConnection("jdbc:derby://localhost:1527/bns","bns","bns");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(query);

while(rs.next())

System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getS
tring(4)+"\t"+rs.getString(5)+"\t"+fmt.format(rs.getDate(6)));

}catch(Exception ex){ex.printStackTrace();}
}
A Definition of Java Garbage Collection

Java garbage collection is the process by which Java programs perform automatic

memory management. Java programs compile to bytecode that can be run on a Java

Virtual Machine or JVM for short. When Java programs run on the JVM, objects are

created on the heap, which is a portion of memory dedicated to the program. Eventually,

some objects will no longer be needed. The garbage collector finds these unused objects

and deletes them to free up memory.

OR

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.

o It is automatically done by the garbage collector (a part of JVM) so we


don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:

o By nulling the reference

o By assigning a reference to another

o By annonymous object etc.

1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:
new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:

protected void finalize(){}

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.

public static void gc(){}

eg:

public class TestGarbage{

public void finalize(){System.out.println("object is garbage collected");}


public static void main(String args[]){
TestGarbage s1=new TestGarbage();
TestGarbage s2=new TestGarbage();
s1=null;
s2=null;
System.gc();
}
}
Output: object is garbage collected
object is garbage collected
Java Thread Priority in Multithreading
→ In a Multi threading environment, thread scheduler assigns processor to a thread
based on priority of thread.

→ Whenever we create a thread in Java, it always has some priority assigned to it.
Priority can either be given by JVM while creating the thread or it can be given by
programmer explicitly.

→ Accepted value of priority for a thread is in range of 1 to 10.

There are 3 static variables defined in Thread class for priority.

public static int MIN_PRIORITY: This is minimum priority that a thread can
have. Value for MIN_PRIORITY is 1.

public static int NORM_PRIORITY: This is default priority of a thread if do not


explicitly define it. Value for NORM_PRIORITY is 5.

public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
MAX_PRIORITY is 10.

Get and Set Thread Priority:

1. public final int getPriority(): java.lang.Thread.getPriority() method returns


priority of given thread.

2. public final void setPriority(int newPriority): java.lang.Thread.setPriority()


method changes the priority of thread to the value newPriority. This method
throws IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.
Examples of getPriority() and setPriority()
import java.lang.*;

class ThreadDemo extends Thread


{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : " +


t1.getPriority()); // Default 5
System.out.println("t2 thread priority : " +
t2.getPriority()); // Default 5
System.out.println("t3 thread priority : " +
t3.getPriority()); // Default 5

t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw IllegalArgumentException


System.out.println("t1 thread priority : " +
t1.getPriority()); //2
System.out.println("t2 thread priority : " +
t2.getPriority()); //5
System.out.println("t3 thread priority : " +
t3.getPriority());//8

// Main thread
System.out.print(Thread.currentThread().getName());
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "
+ Thread.currentThread().getPriority());
}
}

Output:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Main thread priority : 5
Main thread priority : 10

Note:

• Thread with highest priority will get execution chance prior to other threads. Suppose
there are 3 threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first
based on maximum priority 6 after that t1 will execute and then t3.

• Default priority for main thread is always 5, but it can be changed later. Default priority

for all other threads depends on the priority of parent thread.

Example:

// Java program to demonstrat ethat a child thread


// gets same priority as parent
import java.lang.*;

class ThreadDemo extends Thread


{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
// main thread priority is 6 now
Thread.currentThread().setPriority(6);

System.out.println("main thread priority : " +


Thread.currentThread().getPriority());

ThreadDemo t1 = new ThreadDemo();

// t1 thread is child of main thread


// so t1 thread will also have priority 6.

System.out.println("t1 thread priority : "


+ t1.getPriority());
}
}
Output:
Main thread priority : 6
t1 thread priority : 6

• If two threads have same priority then we can’t expect which thread will execute first. It
depends on thread scheduler’s algorithm(Round-Robin, First Come First Serve, etc)

• If we are using thread priority for thread scheduling then we should always keep in mind
that underlying platform should provide support for scheduling based on thread priority.

• Some OS won’t provide proper support for thread priority.


Multithreading in Java
1] Multithreading in Java is a process of executing multiple threads simultaneously.

2] Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

3] 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.

4] 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 exceptions 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:

1] Process-based Multitasking (Multiprocessing): It is used in OS level

2] Thread-based Multitasking (Multithreading): It is used in programmed level

1] Process-based Multitasking (Multiprocessing)

• Each process has its own address in memory i.e. each process allocates separate memory
area.

• Process is heavyweight.

• Cost of communication between the processes is high.

• Switching from one process to another require some time for saving and loading registers,
memory maps, updating lists etc.

1
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.

Eg:

In MS-Word (i.e Process) there is auto-spelling checking; line count, auto-saving etc are threads
running in one process.

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.

2
Figure shows, 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.

Life cycle of a Thread (Thread States)


A thread can be in one of the five states. According to sun, there are only 4 states in thread life
cycle in java newborn, runnable, blocked and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM.

The java thread states are as follows:

1] Newborn state

2] Runnable state

3] Running state

4] Non-Runnable (Blocked state)

5] Dead state / terminated

New Thread Newborn state

start stop

Active stop Dead state


thread Running Runnable

suspended, sleep resume stop


wait notify

Blocked state
Idle thread

Idle thread
Fig: State transition diagram of a thread

3
1) Newborn state

When we create a thread object, the thread is born and is said to be in newborn state. The thread
is not yet scheduled for running. At this state, we can do only one of the following things with it:

i. Scheduled it for running using start() method.

ii. Kill it using stop() method.

Newborn
state
start stop

Runnable Dead state


state

2) Runnable

It means that the thread is ready for execution and is waiting for the availability of the processor.
That is the thread has joined the queue of threads that are waiting for execution. If all the threads
have equals priority, then they are given time slots for execution in round robin fashion i.e first
come first serve manner. The thread that relinquishes control and join the queue at the end and
again waits for its turn. This process of assigning time to threads is known as time-slicing.

However, if we want a thread to relinquish control to another thread to equal priority before its
turn comes, we can do so by using the yield() method.

yield()

. . …….
. …….
. ……..
.
Running Runnable Thread’s
Thread

Fig: Relinquishing control using yield() method.

4
3) Running

Running means that the processor has given its time to the thread for its execution. The thread runs
until it relinquishes control on its own. A running thread may relinquish its control in one of the
following situation:

i. It has been suspended using suspend() method. A suspended thread can be revived by using
the resume() method. This approach is useful when we want to suspend a thread for some
time due to certain reason, but do not want to kill it.

suspend()

. . Resume()
.
Running Runnable Suspended

Fig: Relinquishing control using suspend() method.

ii. It has been made to sleep. We can put a thread to sleep for a specified time period using
the method sleep(time) where time is in milliseconds. This means that the thread is out
queue during this time period. The thread re-enters the runnable state as soon as this time
period is finished.

sleep(t)

after(t)
. . .
Running Runnable Suspended

Fig: Relinquishing control using sleep() method.

5
iii. It has been told to wait until some event occurs. This is done using the wait() method. The
thread can be scheduled to run again using the notify() method.

wait()

. .
notify()
.
Running Runnable Waiting

Fig: Relinquishing control using wait() method.

4) Blocked

A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping or waiting in
order to satisfy certain requirements. A blocked thread is considered “not runnable” but not dead
and therefore fully qualified to run again.

5) Dead state / Terminated

A running thread ends its life when it has completed executing its run() method. It is a natural
death.

However we can kill it by sending stop message using stop() method to it at any state thus causing
a premature death.

A thread can be killed as soon as it born or while it is running or even when it is in blocked state.

6
How to create thread

Creating threads in java is simple. Threads are implemented in the form of Objects that contain a method
called “run()” method. The run() method is the heart and soul of any thread. It makes up the entire body
of a thread in which thread’s behavior can be implemented.

A run() method would appear as follows:

Syntax:

public void run()


{
}

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating
the thread and initiating it with the help of another thread method called “start()” method.

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

By extending Thread class:


1. Declaring the class as extending the “Thread” class.
2. Implementing the “run()” method.
3. Creating a thread object and call the start() method to initiate the thread execution.

Example:

class DemoThread extends Thread


{

public void run()


{
int i;
for(i=1;i<=5;i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}catch(Exception ex){ex.printStackTrace();}
}
7
}

public static void main(String args[])


{
DemoThread d1=new DemoThread();
DemoThread d2=new DemoThread();

d1.start();
d2.start();
}

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.

2. public void start(): starts the execution of the thread. JVM calls the run() method on the thread.

3. public static void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

4. public void join(): waits for a thread to die.

5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6. public int getPriority(): returns the priority of the thread.

7. public int setPriority(int priority): changes the priority of the thread.

8. public String getName(): returns the name of the thread.

9. public void setName(String name): changes the name of the thread.

10. public static Thread currentThread(): returns the reference of currently executing thread.

11. public int getId(): returns the id of the thread.

12. public Thread.State getState(): returns the state of the thread.

13. public boolean isAlive(): tests if the thread is alive.

14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.

15. public void suspend(): is used to suspend the thread(depricated).

16. public void resume(): is used to resume the suspended thread(depricated).

8
17. public void stop(): is used to stop the thread(depricated).

18. public boolean isDaemon(): tests if the thread is a daemon thread.

19. public void setDaemon(boolean b): marks the thread as daemon or user thread.

20. public void interrupt(): interrupts the thread.

21. public boolean isInterrupted(): tests if the thread has been interrupted.

22. public static boolean interrupted(): tests if the current thread has been interrupted.

Starting a thread:

A start() method of Thread class is used to start a newly created thread.

It performs following tasks:

• A new thread starts(with new callstack).

• The thread moves from Newborn state to the Runnable state.

• When the thread gets a chance to execute, its target run() method will run.

Sleep method in java


The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax

The Thread class provides two methods for sleeping a thread:

• public static void sleep(long miliseconds)throws InterruptedException

• public static void sleep(long miliseconds, int nanos)throws InterruptedException

class DemoSleep extends Thread{

public void run(){

for(int i=1;i<5;i++){

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}

System.out.println(i);

} }

public static void main(String args[]){

DemoSleep t1=new DemoSleep ();


9
DemoSleep t2=new DemoSleep ();

t1.start(); t2.start(); } }

Note: As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time, the thread scheduler picks up another thread and so on.

Can we start a thread twice?


No. After starting a thread, it can never be started again. If you do so, an IllegalThreadStateException is
thrown. In such case, thread will run once but for second time, it will throw exception.

Example

public class TestThreadTwice extends Thread{

public void run(){

System.out.println("running...");

public static void main(String args[]){

TestThreadTwice t1=new TestThreadTwice();

t1.start();

t1.start();

Output: running

Exception in thread "main" java.lang.IllegalThreadStateException

What if we call run() method directly instead start() method?


• Each thread starts in a separate call stack.

• Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.

class TestCallRun extends Thread{

public void run(){

System.out.println("running...");

10
public static void main(String args[]){

TestCallRun t1=new TestCallRun();

t1.run();//fine, but does not start a separate call stack

} }

class TestCallRun extends Thread{

public void run(){

for(int i=1;i<5;i++){

try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}

System.out.println(i);

public static void main(String args[]){

TestCallRun t1=new TestCallRun();

TestCallRun t2=new TestCallRun();

t1.run();

11
t2.run();

Output:1

As you can see in the above program that there is no context-switching because here t1 and t2 will be treated
as normal object not thread object.

12
13
The join() method

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.

Syntax:

• public void join()throws InterruptedException

• public void join(long milliseconds)throws InterruptedException

Example of join()

class TestJoinMethod extends Thread{

public void run(){

for(int i=1;i<=5;i++){

try{

Thread.sleep(500);

}catch(Exception e){System.out.println(e);}

System.out.println(i);

public static void main(String args[]){

TestJoinMethod t1=new TestJoinMethod();

TestJoinMethod t2=new TestJoinMethod();

TestJoinMethod t3=new TestJoinMethod();

t1.start();

try{

t1.join();

}catch(Exception e){System.out.println(e);}

t2.start();

t3.start();

In this example, when t1 completes its task then t2 and t3 starts executing.

14
Example of join(long miliseconds) method

class TestJoinMethod extends Thread{

public void run(){

for(int i=1;i<=5;i++){

try{

Thread.sleep(500);

}catch(Exception e){System.out.println(e);}

System.out.println(i);

public static void main(String args[]){

TestJoinMethod t1=new TestJoinMethod();

TestJoinMethod t2=new TestJoinMethod();

TestJoinMethod t3=new TestJoinMethod();

t1.start();

try{

t1.join(1500);

}catch(Exception e){System.out.println(e);}

t2.start();

t3.start();

In this example, when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts
executing.

15
getName(),setName(String) and getId() method:
class demo extends Thread{

public void run(){

System.out.println("running...");

public static void main(String args[]){

demo t1=new demo ();

demo t2=new demo ();

System.out.println("Name of t1:"+t1.getName());

System.out.println("Name of t2:"+t2.getName());

System.out.println("id of t1:"+t1.getId());

t1.start();

t2.start();

t1.setName("Pradeep");

System.out.println("After changing name of t1:"+t1.getName());

} }

16
The public static Thread currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.

Example

class Demo extends Thread{

public void run(){

System.out.println(Thread.currentThread().getName());

public static void main(String args[]){

Demo t1=new Demo();

Demo t2=new Demo();

t1.start();

t2.start();

Q: Write a Java program to use yield(), sleep() and stop() methods.

import static java.lang.Thread.yield;

class A extends Thread

{ int i;

public void run()

for(i=1;i<=5;i++){

if(i==1)

yield();

System.out.println("\tFrom thread A: i = "+i);

System.out.println("Exit from thread A");

17
}

class B extends Thread

{ int j;

public void run()

for(j=1;j<=5;j++)

System.out.println("\tFrom thread B: j = "+j);

if(j==3)

stop();

System.out.println("Exit from thread B");

class C extends Thread

{ int k;

public void run()

for(k=1;k<=5;k++) {

System.out.println("\tFrom thread C: k = "+k);

if(k==1) {

try{Thread.sleep(1000);}

catch(Exception ex){ex.printStackTrace();}

System.out.println("Exit from thread C");

18
}

public class TestThreadMethod_Yield_Stop {

public static void main(String[] args) {

A threadA=new A();

B threadB=new B();

C threadC=new C();

System.out.println("Start Thread A");

threadA.start();

System.out.println("Start Thread B");

threadB.start();

System.out.println("Start Thread C");

threadC.start();

Output:

Start Thread A

Start Thread B

Start Thread C

From thread A: i = 1

From thread B: j = 1

From thread B: j = 2

From thread B: j = 3

From thread C: k = 1

From thread A: i = 2

From thread A: i = 3

From thread A: i = 4

From thread A: i = 5

19
Exit from thread A

From thread C: k = 2

From thread C: k = 3

From thread C: k = 4

From thread C: k = 5

Exit from thread C

20
Java JDBC
• JDBC stands for Java Database connectivity.

• It is a standard application programming interface (API) provided by oracle for


Java application to connect / interact and execute query with different set
of database i.e. Oracle, Microsoft Access, MySQL, SQL Server etc.

• JDBC is an API to connect and execute query with the database. JDBC API
uses JDBC database drivers to connect with the database.
• It acts as a middle layer interface between java applications and database.

• The JDBC classes are contained in the Java Package java.sql and javax.sql.

JDBC helps you to write Java applications that manage these three programming
activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in
answer to your query

Why JDBC?
Class Test

public static void main(String[] args) {

int eid=1001;

String ename="Manjeet";

double salary=20000;

System.out.println(eid+"\t"+ename+"\t"+salary);

JDBC is used to store data permanently into the database.


1
How JDBC Work (Architecture of JDBC)

JDBC Database Database


Drivers

Oracle Driver Oracle

Java JDBC
Application API
SQL Driver SQL

Access Driver
Acces
s

JDBC Application Layer JDBC Driver Layer

JDBC Drivers
• JDBC Driver is a software component that enables Java application to interact with the
database.

• It acts as a middle layer interface between Java applications and database.

JDBC API
• java.sql.DriverManager

• java.sql.Connection

• java.sql.Statement

• java.sql.ResultSet

• java.sql.PreparedStatment

• java.sql.SQLException
2
Steps to :

Set JDBC Driver class-path for Notepad

1. Download the driver for database

Eg: for MySQL

Mysql-connector.jar

2. Set the MySQL connector jar file to the classpath:

Computer -> Advanced System Settings -> Environment Variable

Click on New button

3
Steps to :

Set JDBC Driver for NetBeans IDE/Add jar file to the application

1. Right click on Project Name i.e JavaApplication1 and select properties

➔ Libraries

➔ Click on Add Jar/Folder then a dialog box applear

➔ Then go to c:\program files\java\jdk\db\lib and then select

➔ derby and derbyclient JAR file from lib folder

➔ And clikc on OK button.

4
Five Steps to connect to the database in java
There are 5 steps to connect any java application with the database in java using JDBC. They are
as follows:

• Register the driver class

• Creating connection

• Creating statement

• Executing queries

• Closing connection

5
1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Driver for Oracle

Class.forName("oracle.jdbc.driver.OracleDriver");

Driver for MS-ACCESS

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Driver for MySQL

Class.forName("com.mysql.jdbc.Driver");

Driver for derby Database

Class.forName("org.apache.derby.jdbc.ClientDriver");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException

2) public static Connection getConnection(String url,String name,String password)

throws SQLException

Example to establish connection with the Oracle database

Connection conn=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","password");

Example to establish connection with the MS-ACCESS database

Connection conn=DriverManager.getConnection("jdbc:odbc:mydsn");

6
Example to establish connection with the MySQL database

Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");

Example to establish connection with the deyby database Database UserId

Connection

conn=DriverManager.getConnection("jdbc:derby://localhost:1527/bns","bns","bns");

Password

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery(), executeUpdata() method of Statement interface is used to execute


queries to the database.

executeQuery() method is used to execute SELECT query. It returns the object of ResultSet
that can be used to get all the records of a table.

executeUpdate() is used to execute specified query, it may be create table, drop table, insert
record, update record, delete recrod etc.

7
Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2)); }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Example to connect to the MySQL database

import java.sql.*;

import java.util.*;

class query{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver"); //driver for MySQL

Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");

Statement stat=conn.createStatement();

8
ResultSet rs=stat.executeQuery("select * from stud");

while(rs.next()){

//System.out.print(rs.getInt(1));

System.out.println(rs.getInt(1)+" "+rs.getString(2));

conn.close(); }//try close

catch(Exception e){

System.out.println(e);}

}}

9
DriverManager class:

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers
that are available and handles establishing a connection between a database and the appropriate
driver. The DriverManager class maintains a list of Driver classes that have registered themselves
by calling the method DriverManager.registerDriver().

Commonly used methods of DriverManager class:

• public static Connection getConnection(String url):- is used to establish the connection


with the specified url.

• public static Connection getConnection(String url,String userName,String


password):- userName,String password): is used to establish the connection with the
specified url, username and password.

Connection interface:

A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement. The Connection interface provide many methods for
transaction management like commit(),rollback() etc.

• public Statement createStatement(): creates a statement object that can be used to


execute SQL queries.
• public Statement createStatement(int resultSetType,int resultSetConcurrency):
Creates a Statement object that will generate ResultSet objects with the given type and
concurrency.
• public void commit(): saves the changes made since the previous commit/rollback
permanent.

• public void rollback(): Drops all changes made since the previous commit/rollback.

• public void close(): closes the connection and Releases a JDBC resources
immediately.

10
Statement interface

The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

Commonly used methods of Statement interface:

• public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns


the object of ResultSet.

• public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.

• public boolean execute(String sql): is used to execute queries that may return multiple
results.

Example

import java.sql.*;

import java.util.*;

class query{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver"); //driver for MySQL

Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");

Statement stat=conn.createStatement();

int x=stat.executeUpdate("delete from stud where rno="+args[0]+"");

if(x>0)

System.out.println(“Record deleted successfully.”);

}//try close

catch(Exception e){

System.out.println(e);}}}

11
ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.

By default, ResultSet object can be moved forward only and it is not updatable.

But we can make this object to move forward and backward direction.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

12
import java.sql.*;

class FetchRecord{

public static void main(String args[])throws Exception{

Class.forName("com.mysql.jdbc.Driver"); //driver for MySQL

Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet rs=stmt.executeQuery("select * from stud");

//getting the record of 3rd row

rs.absolute(3);

System.out.println(rs.getInt(1)+" "+rs.getString(2));

conn.close();

}}

13
PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized


query. The performance of the application will be faster if you use PreparedStatement interface
because query is compiled only once.

example of parameterized query

String query="insert into emp values(?,?,?)";

Note: we are passing parameter (?) for the values. Its value will be set by calling the setter methods
of PreparedStatement.

Methods of PreparedStatement interface

import java.sql.*;

import java.util.*;

class query{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver"); //driver for MySQL

Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");

Scanner scan=new Scanner(System.in);


14
System.out.println("Enter the first name to be deleted:");

String n=scan.next();

PreparedStatement stat=conn.prepareStatement("delete from stud where rno=? ");

stat.setString(1,n);

int x=stat.executeUpdate();

if(x>0)

System.out.println("Record Deleted Successfully...");

conn.close();

stat.close();

else

System.out.println("Record Not found..");

catch(Exception e){System.out.println(e);}

15
Java AWT
Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based
application in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components uses the resources of system.

The java.awt package provides classes for AWT such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

1
2
Container
The Container is a component in AWT that can contain another component like Buttons,
TextField, Label etc.

Panel
By using “Panel” class we can organize the component like Button, TextField etc in
the container i.e Frame or Applet .

The Panel is the container that doesn't contain title bar and menu bars. “FlowLayout”
is the default layout for Panel.

Frame
The Frame class is the container that contain title bar and menu bars. It can have other
components like Button, TextField etc. “BorderLayout” is the default layout for Frame.

3
Create AWT application
To create AWT application, you need a Frame.
There are two ways to create a Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class

Example: By extending Frame class


import java.awt.*;
class DemoFrame extends Frame{
DemoFrame() //Constructor
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position

add(b); //adding button into frame


setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true); //now frame will be visible, by default not visible
}

public static void main(String args[]){


new DemoFrame();
}
}

Note: The setBounds(int xaxis, int yaxis, int width, int height) method is used to

sets the position of the AWT button.

4
import java.awt.*;
class DemoFrame extends Frame{
DemoFrame() //Constructor
{
Button b1=new Button("click me1");
Button b2=new Button("click me2");
Button b3=new Button("click me3");
Button b4=new Button("click me4");

add("East",b1); //adding button into frame


add("West",b2);
add("North",b3);
add("South",b4);

setSize(300,300); //frame size 300 width and 300 height

setVisible(true); //now frame will be visible, by default not visible


}

public static void main(String args[]){


new DemoFrame();
}
}

5
Example : By creating the object of Frame class
import java.awt.*;
class DemoFrame{
DemoFrame(){ //constructor
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new DemoFrame();
}
}

TextField

TextField class is a text component that allows the editing of a single line text.

Eg:

Constructor
TextField(int columns)
Constructs a new empty text field with the specified number of columns.

TextField t1;
t1=new TextField(20);

p1.add(t1); //add TextField to the panel

*To accept password character in TextField

t1.setEchoChar(‘*’);

6
*To retrieve the data from the TextField

t1.getText();

*To set the data in the TextField

t1.setText();

Panel

The Panel class is a simplest container class. It provides space in which an application can
attach any other component. Or you can say that the Panel class is used to organize the
controls in the Frame.

Constructor

Panel()
Creates a new panel using the default layout manager.

Panel p1;
p1=new Panel(); or p1=new Panel(null);

*To add panel to the Frame

add(p1);

*To add other component in the Panel

p1.add(t1);

7
Label

Label class is a component for placing text in a container. It is used to display a single line of
read only text. The text can be changed by an application but a user cannot edit it directly.

Constructor

Label(String text)
Constructs a new label with the specified string of text, left justified.

Eg:

Label lblrno;
lblrno=new Label(“Enter the Roll Number:”);

p1.add(lblrno);

Label()
Constructs an empty label.

Eg:
Label lblrno=new Label();

*To set the caption to Label


lblrno.setText(“Enter the Roll Number”);

eg:
Label lblrno=new Label();
lblrno.setText(“Enter the Roll Number”);

Button

The button class is used to create a labeled button. The application result in some action
when the button is pushed.

Button(String text)
Constructs a new button with specified label.
Eg:

Button btn;

8
btn=new Button(“OK”);

p1.add(btn);

Button()
Constructs a button with an empty string for its label.
Eg:
Button btn=new Button();

*To set the caption to Button

btn.setLabel(“OK”);

eg:
Button btn=new Button();
btn.setLabel(“OK”);

TextArea

TextArea class is a multi line region that displays text.

TextArea(int rows, int columns)


Constructs a new text area with the specified number of rows and columns and the empty
string as text.
Eg:

TextArea ta;
ta=new TextArea(4,4);

9
Q: Demonstrate the AWT program for the following Student Entry Form using Frame

import java.awt.*;

public class StudentForm extends Frame {

Label lblRno,lblName,lblAddr;

TextField txtRno,txtName;

TextArea txtAddr;

Button btnOk,btnCancel;

Panel p1;

public StudentForm()

super("Student Entry Form");

lblRno=new Label("Enter the Roll Number:");

lblRno.setBounds(10,50,150,20);

lblName=new Label("Enter the Name:");

lblName.setBounds(10,70,150,20);

10
lblAddr=new Label("Enter the Address:");

lblAddr.setBounds(10,90,150,20);

txtRno=new TextField(20);

txtRno.setBounds(175,50,150,20);

txtName=new TextField(20);

txtName.setBounds(175,70,150,20);

txtAddr=new TextArea(5,4);

txtAddr.setBounds(175,90,400,100);

btnOk=new Button("OK");

btnOk.setBounds(175,250,150,20);

btnCancel=new Button("Cancel");

btnCancel.setBounds(350,250,150,20);

p1=new Panel(null);

add(p1);

p1.add(lblRno); p1.add(txtRno);

p1.add(lblName); p1.add(txtName);

p1.add(lblAddr); p1.add(txtAddr);

p1.add(btnOk);p1.add(btnCancel);

setSize(400, 400);

setVisible(true);

public static void main(String[] args) {

StudentForm sf=new StudentForm();

11
Q. Q: Demonstrate the AWT program for the following Entry Form using Frame

import java.awt.*;
class Calculator extends Frame
{
Label lblfno,lblsno,lblrs;
TextField txtfno,txtsno,txtrs;
Button btnAdd;
Panel p1;
public Calculator()
{
lblfno=new Label("Enter the First No:");
lblfno.setBounds( 10, 50, 150, 20 );

lblsno=new Label("Enter the Second No:");


lblsno.setBounds( 10, 70, 150, 20 );

lblrs=new Label("Result:");
lblrs.setBounds( 10, 90, 150, 20 );

txtfno=new TextField(20);
txtfno.setBounds(175, 50, 150, 20);

txtsno=new TextField(20);
txtsno.setBounds(175, 70, 150, 20);

txtrs=new TextField(20);
txtrs.setBounds(175, 90, 150, 20);

btnAdd=new Button("ADD");

12
btnAdd.setBounds(10,150,100,20);

p1=new Panel(null);

add(p1);
p1.add(lblfno); p1.add(txtfno);
p1.add(lblsno); p1.add(txtsno);
p1.add(lblrs); p1.add(txtrs);
p1.add(btnAdd);
}

public static void main(String args[])


{
Calculator c=new Calculator();

c.setSize(400, 400);
c.setLocation(100,200);
c.setVisible(true);
c.setLocation(300,100);
}

Choice

Choice control is used to show pop up menu of choices.

Constructor

Choice()
Creates a new choice menu.
Eg:

Choice c1;
c1=new Choice();

void add(String item)


Adds an item to this Choice menu.

c1.add(“MCA”);
c1.add(“MBA”);
c1.add(“ME”);
c1.add(“MTech”);

p1.add(c1);

13
void insert(String item, int index)
Inserts the item into this choice at the specified position.

int getSelectedIndex()
Returns the index of the currently selected item.

String getSelectedItem()
Retrieve the selected Item.

void remove(int position)


Removes an item from the choice menu at the specified position.

void remove(String item)


Removes the first occurrence of item from the Choice menu.

List

The List represents a list of text items. The list can be configured that user can choose either one item or multiple
items.

Constructor

List(int rows, boolean multipleMode)


Creates a new scrolling list initialized to display the specified number of rows.

Eg:
List l1;
l1=new List(5,true); // 5 is number of visible items, and true for multi-selection and & false for
single.

void add(String item)


Adds the specified item to the end of scrolling list.

l1.add(“MCA”);
l1.add(“M.Tech”);
l1.add(“MBA”);
l1.add(“MCS”);

p1.add(l1);

void remove(int position)

14
Removes the item at the specified position from this scrolling list.

void remove(String item)


Removes the first occurrence of an item from the list.
String getSelectedItem()
Gets the selected item on this scrolling list.

String[] getSelectedItems()
Gets the selected items on this scrolling list.

Checkbox

Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox
representing what the checkbox does. The state of a checkbox can be changed by clicking on it.

Constructor

Checkbox(String label)
Creates a check box with the specified label.
Eg:
Checkbox c1,c2;

c1=new Checkbox(“JAVA”);
c2=new Checkbox(“C++”);

p1.add(c1);
p1.add(c2);

String getLabel()
Gets the label of this check box.

boolean getState()
Determines whether this check box is in the on or off state.

void setLabel(String label)


Sets this check box's label to be the string argument.

void setState(boolean state)


Sets the state of this check box to the specified state.

15
RadioButton

The CheckboxGroup class is used to group the set of checkbox.

CheckboxGroup cg;
Checkbox c1,c2;

cg=new CheckboxGroup();
c1=new Checkbox(“Male”,cg,true);
c2=new Checkbox(“Female”,cg,false);

p1.add(c1);
p1.add(c2);

Checkbox getSelectedCheckbox()
To get the value of selected radio button we use getSelectedCheckbox() method of CheckboxGroup class.

Eg:

Checkbox chk_value=cg.getSelectedCheckbox();
String str=chk_value.getLabel();

Example:

16
import java.awt.*;

import java.awt.event.*;

public class StudentForm1 extends Frame{

Label lblRno,lblName,lblAddr,lblQ,lblSubject;

TextField txtRno,txtName;

TextArea txtAddr;

Button btnOk,btnCancel;

Choice c1;

Checkbox chk1,chk2;

Panel p1;

public StudentForm1()

super("Student Entry Form");

lblRno=new Label("Enter the Roll Number:");

lblRno.setBounds(10,50,150,20);

lblName=new Label("Enter the Name:");

lblName.setBounds(10,70,150,20);

lblAddr=new Label("Enter the Address:");

lblAddr.setBounds(10,90,150,20);

lblQ=new Label("Qualification:");

lblQ.setBounds(10,200,150,20);

lblSubject=new Label("Subjects:");

lblSubject.setBounds(10,230,150,20);

txtRno=new TextField(20);

txtRno.setBounds(175,50,150,20);

txtName=new TextField(20);

17
txtName.setBounds(175,70,150,20);

txtAddr=new TextArea(5,4);

txtAddr.setBounds(175,90,400,100);

c1=new Choice();

c1.add("MCA");

c1.add("MCS");

c1.add("MTech");

c1.add("MBA");

c1.add("BBA");

c1.add("B.Tech");

c1.setBounds(175,200,150,20);

chk1=new Checkbox("C++");

chk1.setBounds(175,230,150,20);

chk2=new Checkbox("JAVA");

chk2.setBounds(175,260,150,20);

btnOk=new Button("OK");

btnOk.setBounds(175,300,150,20);

btnCancel=new Button("Cancel");

btnCancel.setBounds(350,300,150,20);

p1=new Panel(null);

add(p1);

p1.add(lblRno); p1.add(txtRno);

p1.add(lblName); p1.add(txtName);

p1.add(lblAddr); p1.add(txtAddr);

p1.add(lblSubject); p1.add(lblQ); p1.add(c1);

18
p1.add(chk1); p1.add(chk2);

p1.add(btnOk);p1.add(btnCancel);

setSize(800, 600);

setVisible(true);

p1.setBackground(Color.yellow);

public static void main(String[] args) {

StudentForm1 st=new StudentForm1();

19
What is an Event?

Changing the state of an object is known as event.

Eg: click on button, dragging mouse, entering a character through keyboard, selecting an item from list
etc.

Types of Event

The events can be broadly classified into two categories:


• Foreground Events - Those events which require the direct interaction of user i.e user interacting
with the Graphical User Interface (GUI). For example, clicking on a button, moving the mouse,
entering a character through keyboard, selecting an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.

What is Event Handling?

• Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs.
• These mechanisms have the code which is known as event handler that is executed when an event
occurs.
• Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
• Source –
The source is an object on which event occurs. This occurs when the internal state of that object
changes in some way. Source is responsible for providing information of the occurred event to it's
handler i.e type of event, source of event etc.
• Listener –
A listener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with one or more sources to receive notifications about specific types
of events. Second, it must implement methods to receive and process these notifications.
It is also known as event handler. Listener is responsible for generating response to an event. From
java implementation point of view the listener is also an object. Listener waits until it receives an
event. Once the event is received, the listener processes the event.

Types of Event Classes

1
Event Classes Description
ActionEvent This event gets generated when you activate any control i.e click on
Button, MenuItem etc
ItemEvent This event gets generated when you change the state of Checkbox,
Choice, List etc.
KeyEvent This event gets generated when you press any key on keyboard.
MoueseEvent This event gets generated when you press the mouse, release the
mouse, drag the mouse, move the mouse etc.
WindowEvent This event gets generated when you click on close, maximize or
minimize button on Frame.
AdjustmentEvent This event gets generated when you change the value of scrollbar.

To handle these events, predefined methods are available in particular interfaces. For each event
class one particular interface is there which contains method to handle the event.

Event Listener Interfaces


• Class hierarchy and methods
– java.util.EventListener
• java.awt.event.ActionListener
– actionPerformed
• java.awt.event.AdjustmentListener
– adjustmentValueChanged
• java.awt.event.ComponentListener
– componentHidden, componentMoved,
componentResized, componentShown
• java.awt.event.FocusListener
– focusGained, focusLost
• java.awt.event.ItemListener
– itemStateChanged
• java.awt.event.KeyListener
– keyPressed, keyReleased, keyTyped
• java.awt.event.MouseListener
– mouseEntered, mouseExited,
mousePressed, mouseReleased, mouseClicked
• java.awt.event.MouseMotionListener
– mouseDragged, mouseMoved

2
• java.awt.event.TextListener
– textValueChanged
• java.awt.event.WindowListener
windowOpened, windowClosing, windowClosed, windowActivated,
windowDeactivated, windowIconified, windowDeiconified

Event Sources and Their Listeners Interface

• Frame - WindowListener
• Button - ActionListener
• Choice - ItemListener
• Checkbox - ItemListener
• CheckboxMenuItem - ItemListener
• List - ItemListener, ActionListener when an item
is double-

• MenuItem - ActionListener
clicked

• Scrollbar - AdjustmentListener

• TextField - ActionListener, TextListener


• TextArea - TextListener

Steps to handle the Event

(i) Import the package i.e import java.awt.event.*;


(ii) Implement the particular interface in your class.
(iii) Register the event on the component on which you want to generate the event.
(iv) Add the Event handler method.

3
Q: WAP to create two textfields and one button for sum of two numbers. If user
clicks button, sum of two input values is displayed on the result textfield.
Q: Create a simple calculator which can perform basic arithmetic operations like addition,
subtraction, multiplication, or division depending upon the user input.

import java.awt.*;

import java.awt.event.*;

class Calculator extends Frame implements ActionListener

Label lblfno,lblsno,lblrs;

TextField txtfno,txtsno,txtrs;

Button btnAdd;

Panel p1;

public Calculator()

lblfno=new Label("Enter the First No:");

lblfno.setBounds( 10, 50, 150, 20 );

4
lblsno=new Label("Enter the Second No:");

lblsno.setBounds( 10, 70, 150, 20 );

lblrs=new Label("Result:");

lblrs.setBounds( 10, 90, 150, 20 );

txtfno=new TextField(20);

txtfno.setBounds(175, 50, 150, 20);

txtsno=new TextField(20);

txtsno.setBounds(175, 70, 150, 20);

txtrs=new TextField(20);

txtrs.setBounds(175, 90, 150, 20);

btnAdd=new Button("ADD");

btnAdd.setBounds(10,150,100,20);

p1=new Panel(null);

add(p1);

p1.add(lblfno); p1.add(txtfno);

p1.add(lblsno); p1.add(txtsno);

p1.add(lblrs); p1.add(txtrs);

p1.add(btnAdd);

//register listener

btnAdd.addActionListener(this); //passing current instance

p1.setBackground(Color.yellow);

public void actionPerformed(ActionEvent evt)

5
Object obj=evt.getSource();

int a,b,rs;

a=Integer.parseInt(txtfno.getText());

b=Integer.parseInt(txtsno.getText());

if(obj==btnAdd)

rs=a+b;

txtrs.setText(String.valueOf(rs));

public class Test {

public static void main(String args[])

Calculator c=new Calculator();

c.setSize(400, 400);

c.setLocation(100,200);

c.setVisible(true);

c.setLayout(null);

c.setBackground(Color.yellow);

6
Q: Demonstrate the use of Checkbox Control in Java AWT.

import java.awt.*;

import java.awt.event.*;

public class DemoCheckbox extends Frame implements ItemListener{

Checkbox chkRed,chkGreen,chkBlue;

Panel p1;

public DemoCheckbox()

super("Demo Checkbox");

chkRed=new Checkbox("Red");

chkGreen=new Checkbox("Green");

chkBlue=new Checkbox("Blue");

p1=new Panel();

7
add(p1);

p1.add(chkRed);

p1.add(chkGreen);

p1.add(chkBlue);

chkRed.addItemListener(this);

chkGreen.addItemListener(this);

chkBlue.addItemListener(this);

p1.setBackground(Color.PINK);

public void itemStateChanged(ItemEvent evt)

Object obj=evt.getSource();

if(obj==chkRed)

p1.setBackground(Color.red);

chkGreen.setState(false);

chkBlue.setState(false);

else if(obj==chkGreen)

p1.setBackground(Color.green);

chkRed.setState(false);

8
chkBlue.setState(false);

else if(obj==chkBlue)

p1.setBackground(Color.blue);

chkGreen.setState(false);

chkRed.setState(false);

public static void main(String[] args) {

DemoCheckbox d=new DemoCheckbox();

d.setSize(600, 400);

d.setLocation(100, 100);

d.setVisible(true);

Q: Demonstrate the use of RadioButton in Java AWT.

9
import java.awt.*;

import java.awt.event.*;

public class DemoRadioButton extends Frame implements ItemListener{

CheckboxGroup cg;

Checkbox chkMale,chkFemale;

Label lblmsg;

Panel p1;

public DemoRadioButton()

super("DEMO RADIO BUTTON");

lblmsg=new Label("Example to Check Message on Radio Button Click");

lblmsg.setBounds(10,50,250,20);

cg=new CheckboxGroup();

chkMale=new Checkbox("MALE",cg,true);

chkMale.setBounds(10,70,70,20);

chkFemale=new Checkbox("FEMALE",cg,false);

chkFemale.setBounds(100,70,70,20);

p1=new Panel(null);

10
add(p1);

p1.add(lblmsg);

p1.add(chkMale);

p1.add(chkFemale);

chkMale.addItemListener(this);

chkFemale.addItemListener(this);

p1.setBackground(Color.PINK);

public void itemStateChanged(ItemEvent evt)

Object obj=evt.getSource();

Checkbox chk_label;

if(obj==chkMale)

p1.setBackground(Color.red);

chk_label=cg.getSelectedCheckbox();

lblmsg.setText(chk_label.getLabel());

else if(obj==chkFemale)

p1.setBackground(Color.green);

chk_label=cg.getSelectedCheckbox();

lblmsg.setText(chk_label.getLabel());

11
public static void main(String[] args) {

DemoRadioButton d=new DemoRadioButton();

d.setSize(600, 400);

d.setVisible(true);

d.setLocation(200, 150);

Q: Demonstrate the use of Checkbox Control in Java AWT.

import java.awt.*;

import java.awt.event.*;

public class DemoChoice extends Frame implements ItemListener{

Choice chk_Color;

Panel p1;

public DemoChoice()

super("Demo Choice in AWT");

12
chk_Color=new Choice();

chk_Color.add("Red");

chk_Color.add("Green");

chk_Color.add("Blue");

p1=new Panel();

add(p1);

p1.add(chk_Color);

chk_Color.addItemListener(this);

p1.setBackground(Color.pink);

public void itemStateChanged(ItemEvent evt)

Object obj=evt.getSource();

if(obj==chk_Color)

String str=chk_Color.getSelectedItem();

if(str.equals("Red"))

p1.setBackground(Color.red);

else if(str.equals("Green"))

13
p1.setBackground(Color.green);

else if(str.equals("Blue"))

p1.setBackground(Color.blue);

public static void main(String[] args) {

DemoChoice d=new DemoChoice();

d.setSize(600, 400);

d.setLocation(100, 100);

d.setVisible(true);

14
Adapter class
The Adapter class provides the default modification of all methods of an interface; we don't need to
modify all the methods of the interface so we can say it reduces coding burden. Sometimes or often
we need a few methods of an interface. For that the Adapter class is very helpful since it already
modifies all the methods of an interface and by implementing the Adapter class, we only need to
modify the required methods.

The following examples contain the following Adapter classes:

● ContainerAdapter class.
● KeyAdapter class.
● FocusAdapter class.
● WindowAdapter class.
● MouseAdapter class.
● ComponentAdapter class.
● MouseMotionAdapter class.

Examples
The frame created by the programmer and displayed on monitor comes with title bar and three
icons(buttons) on the title bar
I. Minimize button
II. Maximize button
III. Close button
The first two button works implicitly and the close button does not work and requires extra code to
close the Frame.
There are three different styles exist to close the Frame are:
I. WindowListener
II. WindowAdaptor
III. Anonymous inner class

Example of WindowAdapter class


import java.awt.*;
import java.awt.event.*;

class windowAdapter1 extends Frame


{
public windowAdapter1()
{
super("MyFrame");
//addWindowListener(new myClass()); or
myClass m=new myClass();
addWindowListener(m);
setSize(300,400);
setVisible(true);
}
public static void main(String args[])
{
new windowAdapter1();
}
}

class myClass extends WindowAdapter


{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}

}
Anonymous class
If you write a class without name then it’s known as Anonymous class.
import java.awt.*;
import java.awt.event.*;

class myFrame extends Frame


{
public myFrame()
{
super("My App");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
setSize(300,400);
setVisible(true);
}
public static void main(String args[])
{
new myFrame();
}

Q: create a LOGIN form that contains only two fields, i.e., username and password using
frame and awt components. We also create a button for performing the action. After
submitting the login form, the underlying code of the form checks whether the credentials
are authentic or not to allow the user to access the restricted page. If the users provide
authentic credentials, print “Login Successful” otherwise print “Enter valid user id and
password”.

import java.sql.*;
import java.awt.event.*;
import java.awt.*;
public class Login extends Frame implements ActionListener,WindowListener{
Label lbluid,lblpwd;
TextField txtuid,txtpwd;
Button btnSignIn;
Panel p1;
public Login()
{
super("LOGIN FORM");
lbluid=new Label("Enter the User ID:");
lblpwd=new Label("Enter the Password:");
txtuid=new TextField(20);
txtpwd=new TextField(20);
txtpwd.setEchoChar('*');
btnSignIn=new Button("SignIn");
p1=new Panel();
p1.setBackground(Color.red);
add(p1);
p1.add(lbluid); p1.add(txtuid);
p1.add(lblpwd); p1.add(txtpwd);
p1.add(btnSignIn);
btnSignIn.addActionListener(this);
addWindowListener(this);

public void actionPerformed(ActionEvent evt)


{
Object obj=evt.getSource();
if(obj==btnSignIn)
{
String query="select * from login where uid='"+txtuid.getText()+"' and
pwd='"+txtpwd.getText()+"'";
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection
conn=DriverManager.getConnection("jdbc:derby://localhost:1527/bns","bns","bns");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(query);
boolean status= rs.next();
if(status)
{
DemoMenu dc=new DemoMenu();
dc.setSize(400,400);
dc.setVisible(true);
dc.setLocation(200, 150);
}
else
{
DemoChoice dc=new DemoChoice();
dc.setSize(400,400);
dc.setVisible(true);
System.out.println("Enter the valid user id or password");
}

}catch(Exception ex){ex.printStackTrace();}

}
}

public static void main(String args[])


{
Login l=new Login();
l.setSize(600,600);
l.setVisible(true);
l.setLocation(300, 100);
}

@Override
public void windowOpened(WindowEvent e) {

@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}

@Override
public void windowClosed(WindowEvent e) {

@Override
public void windowIconified(WindowEvent e) {

@Override
public void windowDeiconified(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of
generated methods, choose Tools | Templates.
}

@Override
public void windowActivated(WindowEvent e) {

@Override
public void windowDeactivated(WindowEvent e) {

You might also like