Java PDF Merge
Java PDF Merge
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.
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.");
}
};
D:\javac Test.java
If everything is OK, the “javac” compiler creates a file called “Test.class” containing
byte code of the 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.
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.
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.
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.
1. Temporary
2. Permanent
To set the temporary path of JDK, you need to follow following steps:
For Example:
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
-> write path of bin folder in variable value -> ok -> ok -> ok
Variable Name: path
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);
}
}
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);
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
Types of Java Applications
There are mainly 4 types of applications that can be created using java programming:
1) Standalone Application
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
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.
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.
➢ 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).
3
➢ Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
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
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
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.
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
• 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
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
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.
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.
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.
1. Temporary
2. Permanent
To set the temporary path of JDK, you need to follow following steps:
For Example:
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
-> write path of bin folder in variable value -> ok -> ok -> ok
9
10
Variable in Java
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.
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;
}
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
1. Keywords
2. Identifiers
3. Literals or Constants
4. Operator
5. Separator
1. Keywords :
• Keywords are special words that are significant to the java compiler.
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.)
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.
Syntax:
1. Integer literals
3. Character literals
4. String literals
5. Boolean literals
4. Operator:
Types of Operators:
I. Arithmetic Operators
Operator Description
Example:
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
< (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.
Example:
int a = 5;
Output:
false
true
true
IV. Assignment Operator
Operator Description
*=
This operator multiplies right operand with the left operand
and assigns the result to the left operand.
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 {
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:
int variable = 5;
System.out.println("Original value of the variable = " + variable);
Output
Original value of the variable = 5
variable = 6
preIncrement = 6
++preIncrement = 7
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.
// postIncrement = 101
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 102
System.out.println("postIncrement++ = " + postIncrement++);
// postIncrement = 103
System.out.println("postIncrement++ = " + postIncrement++);
Output
Original variable = 100
postIncrement = 100
variable = 101
postIncrement++ = 100
postIncrement++ = 101
postIncrement++ = 102
postIncrement = 103
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
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:
// 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:
Output
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:
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:
Output :
63
55
Example:
class Test {
System.out.println(Ans);
}
}
Output :
Example:
class Test
int number = 8;
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.
Data Type
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;
// 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
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;
// 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 ch = 'S';
System.out.println(ch);
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.
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.
2. Explicitly
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
double d = 100.04;
}
}
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;
}
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.
• 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.
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
1
Wrapper class Example:
Primitive to Object
int a=20;
Output: 20 20 20
2
Wrapper class Example:
int j=a; //auto unboxing, now compiler will write a.intValue() internally
Output: 333
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.
1. By string literal
2. By new keyword
1. By string literal
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";
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.
To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).
2. By new keyword
In such case, JVM will create a new string object in normal (non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap (non
pool).
Example:
//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{
String s="Sachin";
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{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
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.
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{
String str="Ram";
System.out.println(str.charAt(0)); // R }}
4
Eg:
class Demo{
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{
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{
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{
String str="Manjeet";
7. String toLowerCase() – return a new string identical to this string. All uppercase letters are
converted to their lowercase equivalent.
class Demo{
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{
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.
This method returns new String object containing the substring of the
given string from specified startIndex.
class Demo{
String str="manjeet";
System.out.println(""+str.substring(3));
o/p: jeet
This method returns new String object containing the substring of the
given string from specified startIndex to endIndex – 1.
class Demo{
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.
Parameter
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{
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
class Demo{
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{
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{
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{
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{
String str="10/01/2020";
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{
String str="Manjeet";
char ch[]=str.toCharArray();
int i;
for( i=0;i<ch.length;i++ )
System.out.print(""+ch[i]); }
Output:
Manjeet
import java.io.*;
import java.util.*;
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.
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.
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);
}
}
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)
;
}
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[]){
}
}
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
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.
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
o/p:
6|Page
Access Specifiers 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.
In java we have four Access Specifiers and they are listed below.
1. Public
2. Private
3. Protected
4. Default(no specifier)
Public specifiers :
Private specifiers :
Example:
class Demo {
class Test
{
class Demo
{
private int age=18;
private void Msg()
{
System.out.println("Age="+age);
}
}
class Test
{
}
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.
Example:
class Demo {
→ 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
{
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();
}
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 Test {
Output:
Animals can move
Dogs can walk and run
Interface
Interface just defines what a class must do without saying anything about its
implementation.
There are mainly three reasons to use interface. They are given below.
• One interface reference variable can hold different types of implementing class memory.
Example:
Vodafone
Airtel
Idea
TataDoccomo
Declare interface
Syntax:
interface <interface_name>
// 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.
obj.display();
Example:
Example:
interface Drawable{
void draw();
class TestInterface{
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.*;
void rectangleArea();
import java.io.*;
int l,b,s,r;
double a;
try{
l=Integer.parseInt(br.readLine());
a=l*b;
System.out.println("Area of Rectangle:"+a);
}catch(Exception ex){ex.printStackTrace();}
s=Integer.parseInt(br.readLine());
a=s*s;
System.out.println("Area of SquareArea:"+a);
r=Integer.parseInt(br.readLine());
a=Math.PI*Math.pow(r,2);
System.out.println("Area of CircleArea:"+a);
a.squareArea();
a.circleArea();
Example:
import java.util.*;
interface Tax
{
final int trate=5;
void calculateTax();
}
}
Multiple inheritance in Java by interface
interface A{
void m1();
interface B{
void m2();
obj.m1();
obj.m2();
} }
interface Tax
void calculateTax();
class Publication{
String pname;
public Publication(String n)
pname=n;
int priceAfterTax;
super(pn);
this.bname=bn;
this.bid=id;
this.bprice=bp;
void display(){
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();
}}
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.
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;
String department;
double salary;
public void accept() throws IOException{
name=br.readLine();
address=br.readLine();
department=br.readLine();
salary=Double.parseDouble(br.readLine());
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("Department: "+department);
System.out.println("Salary: "+salary);
System.out.println("----------------------");
name=br.readLine();
address=br.readLine();
hours=Integer.parseInt(br.readLine());
rate=Integer.parseInt(br.readLine());
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("----------------------");
}
public class Menu {
int i;
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
int n=Integer.parseInt(br.readLine());
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:
int m=Integer.parseInt(br.readLine());
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.
1. sharing resources
2. centralize software management
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) Protocol
For example:
• TCP
• FTP
• Telnet
• SMTP
• POP etc.
3) Port Number
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.
6) Socket
(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)
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
Example: socket programming in which client sends a text and server receives it.
File: MyServer.java
import java.io.*;
import java.net.*;
try{
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.*;
try{
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{
Socket s=ss.accept();
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
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{
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
dout.close();
s.close();
}}
6
Java DatagramSocket and DatagramPacket
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
DatagramSocket class
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.
Example: //DSender.java
7
import java.net.*;
InetAddress ip = InetAddress.getByName("127.0.0.1");
ds.send(dp);
//DReceiver.java
import java.net.*;
ds.receive(dp);
System.out.println(str);
public String(byte[] bytes, int offset, int length)
ds.close();
bytes – the bytes to decoded into characters
}
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
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.
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{
class 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".
};
p.eat();
3
Java anonymous inner class example using interface
interface Eatable{
void eat();
class TestAnnonymousInner1{
};
e.eat();
Example
void display(){
class Local{
void msg(){System.out.println(data);}
l.msg();
obj.display();
} }
4
Note: Local inner class cannot be invoked from outside the method.
Example
classTestOuter{
obj.msg();
class TestOuter{
}
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.
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
abstract int It is used to return the minimum value for the given
getMinimum(int field) calendar field of this Calendar instance.
import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating Calendar object
Calendar calendar = Calendar.getInstance();
import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
max = calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in a year: " + max);
}
}
import java.util.*;
public class DemoCalendar {
public static void main(String[] args)
{
// creating calendar object
Calendar calendar = Calendar.getInstance();
min = calendar.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + min);
}
}
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());
}
}
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:
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:
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(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
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");
}
}
String cby="Manjeet";
java.util.Date dt=new java.util.Date();
}catch(Exception ex){ex.printStackTrace();}
}
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
OR
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.
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:
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.
eg:
→ 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.
public static int MIN_PRIORITY: This is minimum priority that a thread can
have. Value for MIN_PRIORITY is 1.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for
MAX_PRIORITY is 10.
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
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
Example:
• 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.
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.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if 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:
• Each process has its own address in memory i.e. each process allocates separate memory
area.
• Process is heavyweight.
• 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)
• Thread is lightweight.
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
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.
But for better understanding the threads, we are explaining it in the 5 states.
1] Newborn state
2] Runnable state
3] Running state
start stop
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:
Newborn
state
start stop
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
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
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
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
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.
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.
Syntax:
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.
Example:
d1.start();
d2.start();
}
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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public static Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
8
17. public void stop(): is used to stop the thread(depricated).
19. public void setDaemon(boolean b): marks the thread as daemon or user 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:
• When the thread gets a chance to execute, its target run() method will run.
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
} }
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.
Example
System.out.println("running...");
t1.start();
t1.start();
Output: running
• 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.
System.out.println("running...");
10
public static void main(String args[]){
} }
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
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:
Example of join()
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
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
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
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{
System.out.println("running...");
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");
} }
16
The public static Thread currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
Example
System.out.println(Thread.currentThread().getName());
t1.start();
t2.start();
{ int i;
for(i=1;i<=5;i++){
if(i==1)
yield();
17
}
{ int j;
for(j=1;j<=5;j++)
if(j==3)
stop();
{ int k;
for(k=1;k<=5;k++) {
if(k==1) {
try{Thread.sleep(1000);}
catch(Exception ex){ex.printStackTrace();}
18
}
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadA.start();
threadB.start();
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
20
Java JDBC
• JDBC stands for Java Database connectivity.
• 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
int eid=1001;
String ename="Manjeet";
double salary=20000;
System.out.println(eid+"\t"+ename+"\t"+salary);
Java JDBC
Application API
SQL Driver SQL
Access Driver
Acces
s
JDBC Drivers
• JDBC Driver is a software component that enables Java application to interact with the
database.
JDBC API
• java.sql.DriverManager
• java.sql.Connection
• java.sql.Statement
• java.sql.ResultSet
• java.sql.PreparedStatment
• java.sql.SQLException
2
Steps to :
Mysql-connector.jar
3
Steps to :
Set JDBC Driver for NetBeans IDE/Add jar file to the application
➔ Libraries
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:
• 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.
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.mysql.jdbc.Driver");
Class.forName("org.apache.derby.jdbc.ClientDriver");
The getConnection() method of DriverManager class is used to establish connection with the
database.
throws SQLException
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
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","");
Connection
conn=DriverManager.getConnection("jdbc:derby://localhost:1527/bns","bns","bns");
Password
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();
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
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
con.close();
import java.sql.*;
import java.util.*;
class query{
try{
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));
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().
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 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.
• 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{
try{
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");
Statement stat=conn.createStatement();
if(x>0)
}//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.
ResultSet.CONCUR_UPDATABLE);
12
import java.sql.*;
class FetchRecord{
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");
ResultSet.CONCUR_UPDATABLE);
rs.absolute(3);
System.out.println(rs.getInt(1)+" "+rs.getString(2));
conn.close();
}}
13
PreparedStatement interface
Note: we are passing parameter (?) for the values. Its value will be set by calling the setter methods
of PreparedStatement.
import java.sql.*;
import java.util.*;
class query{
try{
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/manjeet","root","");
String n=scan.next();
stat.setString(1,n);
int x=stat.executeUpdate();
if(x>0)
conn.close();
stat.close();
else
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
Note: The setBounds(int xaxis, int yaxis, int width, int height) method is used to
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");
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);
t1.setEchoChar(‘*’);
6
*To retrieve the data from the TextField
t1.getText();
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);
add(p1);
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();
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();
btn.setLabel(“OK”);
eg:
Button btn=new Button();
btn.setLabel(“OK”);
TextArea
TextArea ta;
ta=new TextArea(4,4);
9
Q: Demonstrate the AWT program for the following Student Entry Form using Frame
import java.awt.*;
Label lblRno,lblName,lblAddr;
TextField txtRno,txtName;
TextArea txtAddr;
Button btnOk,btnCancel;
Panel p1;
public StudentForm()
lblRno.setBounds(10,50,150,20);
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);
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 );
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);
}
c.setSize(400, 400);
c.setLocation(100,200);
c.setVisible(true);
c.setLocation(300,100);
}
Choice
Constructor
Choice()
Creates a new choice menu.
Eg:
Choice c1;
c1=new Choice();
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.
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
Eg:
List l1;
l1=new List(5,true); // 5 is number of visible items, and true for multi-selection and & false for
single.
l1.add(“MCA”);
l1.add(“M.Tech”);
l1.add(“MBA”);
l1.add(“MCS”);
p1.add(l1);
14
Removes the item at the specified position from 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.
15
RadioButton
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.*;
Label lblRno,lblName,lblAddr,lblQ,lblSubject;
TextField txtRno,txtName;
TextArea txtAddr;
Button btnOk,btnCancel;
Choice c1;
Checkbox chk1,chk2;
Panel p1;
public StudentForm1()
lblRno.setBounds(10,50,150,20);
lblName.setBounds(10,70,150,20);
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);
18
p1.add(chk1); p1.add(chk2);
p1.add(btnOk);p1.add(btnCancel);
setSize(800, 600);
setVisible(true);
p1.setBackground(Color.yellow);
19
What is an Event?
Eg: click on button, dragging mouse, entering a character through keyboard, selecting an item from list
etc.
Types of Event
• 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.
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.
2
• java.awt.event.TextListener
– textValueChanged
• java.awt.event.WindowListener
windowOpened, windowClosing, windowClosed, windowActivated,
windowDeactivated, windowIconified, windowDeiconified
• Frame - WindowListener
• Button - ActionListener
• Choice - ItemListener
• Checkbox - ItemListener
• CheckboxMenuItem - ItemListener
• List - ItemListener, ActionListener when an item
is double-
• MenuItem - ActionListener
clicked
• Scrollbar - AdjustmentListener
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.*;
Label lblfno,lblsno,lblrs;
TextField txtfno,txtsno,txtrs;
Button btnAdd;
Panel p1;
public Calculator()
4
lblsno=new Label("Enter the Second No:");
lblrs=new Label("Result:");
txtfno=new TextField(20);
txtsno=new TextField(20);
txtrs=new TextField(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
p1.setBackground(Color.yellow);
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));
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.*;
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);
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);
d.setSize(600, 400);
d.setLocation(100, 100);
d.setVisible(true);
9
import java.awt.*;
import java.awt.event.*;
CheckboxGroup cg;
Checkbox chkMale,chkFemale;
Label lblmsg;
Panel p1;
public DemoRadioButton()
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);
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) {
d.setSize(600, 400);
d.setVisible(true);
d.setLocation(200, 150);
import java.awt.*;
import java.awt.event.*;
Choice chk_Color;
Panel p1;
public DemoChoice()
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);
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);
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.
● 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
}
Anonymous class
If you write a class without name then it’s known as Anonymous class.
import java.awt.*;
import java.awt.event.*;
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);
}catch(Exception ex){ex.printStackTrace();}
}
}
@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) {