0% found this document useful (0 votes)
8 views

Advance+Java+5th+Semester

The document outlines a course on Advanced Java Programming for 5th semester BCS students, detailing various topics such as technology, object-oriented programming (OOP), and the use of Java in different applications. It emphasizes the importance of information technology in various fields, including business, education, finance, and healthcare, while also providing an overview of Java's applications in desktop, web, mobile, and enterprise development. Additionally, it covers key Java concepts like classes, objects, methods, and constructors, along with their practical implementations.

Uploaded by

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

Advance+Java+5th+Semester

The document outlines a course on Advanced Java Programming for 5th semester BCS students, detailing various topics such as technology, object-oriented programming (OOP), and the use of Java in different applications. It emphasizes the importance of information technology in various fields, including business, education, finance, and healthcare, while also providing an overview of Java's applications in desktop, web, mobile, and enterprise development. Additionally, it covers key Java concepts like classes, objects, methods, and constructors, along with their practical implementations.

Uploaded by

Rehan Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 214

Introduction!

Faculty: BCS
Semester: 5th
Subject: Advance JAVA programming
Lecturar: NASIR AHMAD AGHA
Agenda:
Advanc Java
Programing Learning
AGENDA Topics:
7. What is
1. WHAT IS Technology ? serialization and
deserialization?
2. Using Java in
technology
8.What is JDBC
3.What is oop with java?

4.What are class and 9.What is thread ?


object

5.What are java 10. What is API &


general generic GUI?
concepts
11.Java AWT & Applet package
6. What is EXCEPTION
handling in java? 12. Java connection with
oracle/mysql/access …
What is the simple definition of technology?

Technology is the application of scientific knowledge to the practical aims of human life, e.g.
online communication, data transaction …

What is information technology?


Information technology involves a combination of hardware and software that is
used to perform the essential tasks that people need and use on the everyday
basis.
Why IT is important?

IT is the application of computers and other electronic equipment to receive,


store, retrieve, transmit, and manipulate data.
IT Provide the following key points:
o electronic security Chain
o Storage
o efficient communication
o exchange information
o establish faster communication
o Artificial intelligence
o cloud computing
o Drones
o IoT
There are many types of roles in the
field for IT such as:
1. Network Administrator
2. System Administrator
3. System analyst
4. Technology Specialist
5. Data scientist
6. Database administrator
7. IT Manager
8. Support Analyst
9. Database developer
10. A software tester, Engineer, Architect
11. Software Development Manager
12. Network engineer
13. Software / Application developer
Uses
We can see Of Information
the uses Technology:
and role of information technology in our
society in many fields:
Business:
Information Technology is important and it is possible with computers and
software’s.
The use of IT such as finance, human resources, manufacturing, and
security.

Education:
Technology enables teachers to be up to date with new techniques and
help their students to be updated with latest technologies such as use
of tablets, mobile phones, computers, etc.

Finance:
Information Technology is used to do online purchases such as Banks keep
records of all the transactions and accounts through computers.
Uses Of Information Technology:

Healthcare:
For doctors, sending and receiving information, checking patients, and
discussing with other experts.
Security:
Online transactions and keeping records of all the online transactions are
now more safe than earlier times.
Communication:
Information can be shared quickly and easily from all over the glob and
geographic boundaries.
Employment:
With Information Technology, new jobs have been introduced.
It creates new jobs for programmers, hardware and software developers,
systems analyzers, web designers and many others.
Using Java in technologies:
What Is Java Used For:
o Java Applications are use in 12 parts:
o Since its development in 1995 by Sun Microsystems the language
has become a backbone as far as millions of applications are
concerned.
o According to Oracle, almost 3 billion devices of their platform such
as (Windows, Mac OS, UNIX, Android).
Using Java in technologies:
What Is Java Used For:
1) Desktop GUI Applications
2) Web Applications
3) Mobile Applications
4) Enterprise Applications
5) Scientific Applications
6) Web Servers & Applications Servers
7) Embedded Systems
8) Server Apps In Financial Industry
9) Software Tools
10) Trading Applications
11) J2ME Apps
12) Big Data Technologies
Using Java in technologies:
Let’s now discuss some in detail;
1) Desktop GUI Applications
Java language provides many features that help us to develop GUI
applications.
Java provides AWT, Swing API or the latest JavaFX.
GUI applications including advanced 3D graphical applications
2) Web Applications
Using Java in technologies:
Java provides features for web development as well as Servlets, Struts
is an
open source framework that extends the Java Servlet API , Spring,
hibernate, java server package(JSPs), etc. that allow us to develop
highly
secured easily program software.
Using Java in technologies:
3) Mobile Applications
Java language provides a cross-platform framework to build mobile
applications
that can run across Java-supported smartphones and feature phones.
One of the popular mobile operating systems is Android.
Using
4) Enterprise Applications Java in technologies:
Java is the first choice for developing enterprise programs because of
its
powerful features delivering high performance.
Java also makes applications more powerful, secure, and easily
scalable.
According to Oracle, almost 97% of enterprise computers are running
on Java
Using Java in technologies:
5) Scientific Applications
it is popular for developing scientific applications.
Java also provides powerful mathematical calculations that give the
same results
on different platforms.
6) Web Servers & Applications Servers
Using Java in technologies:
Among web servers, we have Apache Tomcat, Project Jigsaw, Rimfaxe Web Server
(RWS).
Similarly, application servers like WebSphere, JBoss, WebLogic, etc.
Apache Tomcat is a web container. It allows the users to run Servlet and JAVA
Server
Pages that are based on the web applications.
Project Jigsaw: Make it easier for developers to construct and maintain libraries
The Rimfaxe Web Server (short name RWS): is a powerful Web Server with a
servlet engine.
Using Java in technologies:
7) Embedded Systems
Embedded systems are low-level systems like tiny/small chips, processors,
etc.,
also called integrated systems.
Java can produce robust tools that can handle application and are fast too
it is better for developing low-level programs.
Embedded systems applications using Java:
o SIM cards use Java technology
o Blue-ray disc player(CD, DVD)
Using Industry
8) Server Apps In Financial Java in technologies:
In Financial the banks and investors need various software programs to run
their day
to-day business like front and backend electronic trading systems, data
processing,
etc.
Java is mostly used for server-side applications that receive data from one
server
and send the processed data to the other servers.
Using Java in technologies:
9) Software Tools

Many software tools used for development are written in Java.

For example, integrated development environment(IDEs) like Eclipse, and


Net beans are all written and developed in Java.
These are also the most popular desktop GUI-based tools used today.

swing and Abstract Window Toolkit(AWT ) & JavaFx.


Using
10) Trading Applications Java in technologies:
The popular trading application Murex, which is used in many banks for
front-to-bank
connectivity, is written in Java.
Murex is a company that provides financial software
for trading, treasury, risk,
for financial markets.
Using Java in technologies:
11) Java 2 Platform, Micro Edition(J2ME) Apps
Apart from iOS and android based mobile handsets, there are handsets
from Nokia
and Samsung that use J2ME.
J2ME is also popular with products like Blu-ray, Cards, Set-Top Boxes, etc.
The popular application WhatsApp available on Nokia is available in J2ME.
12) Big Data Technologies
Using Java in technologies:
Bigdata is a term used to describe a collection of data that is huge in size and yet
growing exponentially with time
An open framework that is associated with Big data is entirely written in Java.
With features like automatic garbage collection, memory distribution, and stack
provision system.

Applications of Big Data


Banking Application.
Education Application.
Media Application.
Healthcare Application.
Agriculture Application.
Travel Application.
Second part using java in technologies:
Web Development in Java:
Java is a commonly used for web development, especially on the server
side.
Web development with Java allows us to create dynamic web pages where
users can
Interact/act with the interface.
Static Website Dynamic Website
Content of Web pages can not be Content of Web pages can be
change at runtime. changed.
No interaction with database
Interaction with database is possible
possible.
Second part using java in technologies:
Java Web Application:
A web application helps clients to interact with the server and access
information.
Java is perfect for developing large web applications
Java can communicate with a large number of systems.
like peer-web services, database connectivity, and back-end.
Second part using java in technologies:
Java web application technologies:
1. Servlet API
A servlet is a Web component that is managed by a container and generates
dynamic contents of Web applications.
Servlet increases the capability of servers that are used to host applications.
Servlets runs on web server or application server.
Execution of Servlets basically involves six basic steps:
1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and
the client browser displays it on the screen.
2. JSP: Second part using java in technologies:
o JSP technology is used to create web application just like Servlet technology.
o can be written in HTML, wireless markup lang(WML), XML, etc.
o Servlets can accept and process all type of protocol requests.
o JSP on the other hand is compatible with HTTP request only
o CGI (Common Gateway Interface) files for embedding dynamic elements in HTML
pages
o 1) Extension to Servlet
o 2) Easy to maintain
o 3) Fast Development: No need to recompile and redeploy
o 4) Less code than Servlet
Second part using java in technologies:
3. JDBC API
Java Database Connectivity (JDBC) contains methods and queries for
accessing the
database.
Clients can update any information in the database via web
applications that
contain JDBC drivers.
Second part using java in technologies:
4. Java Persistence API
Java Persistence API (JPA) uses object-relational mapping to connect an object
oriented model to the database.
JPA is a collection of efficient classes and methods that can connect you to the
database.
Second part using java in technologies:
5) Java Server Faces Technology:
Java Server Faces (JSF) Technology is a UI framework to create web-based
interfaces.
It is a server-side Java framework for web development.
JSF provides a simple model in various scripting/ markup languages.
What is OOP?
What is OOP?
OOP stands for Object-Oriented Programming.
they use objects as a primary source to implement what is to happen in the code.
Objects are seen by the viewer or user, performing tasks assigned by you.
Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism etc
OOP advantages:
A. OOP is faster and easier to execute
B. OOP provides a clear structure for the programs
C. OOP helps to keep the Java code DRY "Don't Repeat Yourself",
D. OOP makes it possible to create full reusable applications with less code
What is OOP?
Java - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.
a class is a template for objects, and an object is an instance of a class
Look at the following Example:
What is OOP?

Java - What are Classes and Objects?


a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.

Main.java
Create a class named "Main" with a variable x:

public class Main


{ int x = 5; }
Note:
a class should always start with an uppercase first letter.
What is OOP?
Java - What are Classes and Objects?
Create an object called "myObj" and print the value of x:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
What is OOP with java?
Multiple Objects Example:
Create two objects of Main:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}}
What is OOP with java?
Java Class Attributes:
class attributes are variables within a class:
Example:
Create a class called "Main" with two attributes: x and y:

public class Main


{
int x = 5; int y = 3;
}
Accessing Attributes:
You can access attributes by creating an object of the class, and by using the dot syntax (.):
What is OOP with java?
Modify Attributes:
You can also modify attribute values:
Example:

Set the value of x to 40:


public class Main
{
int x;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 40;
System.out.println(myObj.x);
}}
What is OOP with java?
override existing values:
Example
Change the value of x to 25:
public class Main
{
int x = 10;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 25; // x is now 25
System.out.println(myObj.x);
}}
What is OOP with java?
If you don't want the ability to override existing values, declare the attribute as final:
Final key word is used for restriction.
The final keyword is a non-access modifier used for classes, attributes and methods (impossible to inherit
or override) .

Example:
public class Main
{
final int x = 10;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}}
What is OOP with java?
Multiple Attributes:
You can specify as many attributes, as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
public static void main(String args[])
{
Main myObj = new Main();
System.out.println("Name: " + myObj.fname + " " + myObj.lname);
System.out.println("Age: " + myObj.age);

}}
What is OOP with java?
Java Class Methods:
methods are declared within a class, and that they are used to perform certain actions it means
method() is used to reuse portion of program:
Example:
Note: To call a method, write the method's name followed by two parentheses () and a
semicolon;

Create a method named myMethod() in Main:


public class Main
{
static void myMethod()
{
System.out.println("Hello World!");
}}
What is OOP with java?
Inside main, call myMethod():
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "Hello World!"
What is OOP with java?
Java Constructors:
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes:

Create a constructor:
public class Main // Create a Main class {
int x; // Create a class attribute
public Main() // Create a class constructor for the Main class {

x = 5; // Set the initial value for the class attribute x }


public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
} }
// Outputs 5
What is OOP with java?
Types of Constructor

In Java, constructors can be divided into 3 types:


1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor. For
example,

private Constructor()
{
// body of the constructor
}
What is OOP with java?
Java private no-arg constructor:
class Main
{
int i;
private Main( ) // constructor with no parameter
{
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args)
{
Main obj = new Main(); // calling the constructor without any parameter
System.out.println("Value of i: " + obj.i);
}}
Output:
Constructor is called Value of i: 5
What is OOP with java?
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).
Parameterized constructor:
class Main {
String languages;
Main(String lang) // constructor accepting single value
{
languages = lang;
Output:
System.out.println(languages + " Programming Language"); }
Java Programming Language
public static void main(String[] args) Python Programming Language
{ C Programming Language
Main obj1 = new Main("Java"); // call constructor by passing a single value
Main obj2 = new Main("Python"); // call constructor by passing a single value
Main obj3 = new Main("C"); // call constructor by passing a single value
}}
3. Java Default ConstructorWhat is OOP with java?
If we do not create any constructor, the Java compiler automatically create a
no-arg constructor during the execution of the program. This constructor is
called default constructor.
Default Constructor:
class Main {
int a;
boolean b;
public static void main(String[] args)
{
Main obj = new Main(); // A default constructor is called
Output:
Default Value:
System.out.println("Default Value:"); a=0
System.out.println("a = " + obj.a); b = false
System.out.println("b = " + obj.b);
}}
What is OOP with java?
Java Constructors:
Note that the constructor name must match the class name/same as class nmae, and it cannot
have a return type (like void).
public class Main // Create a Main class {
int x; // Create a class attribute
public Main() // Create a class constructor for the Main class {
x = 5; // Set the initial value for the class attribute x }
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
} }
// Outputs 5
Constructor Parameters: What is OOP with java?

Constructors can also take parameters, which is used to initialize attributes.


The following example adds an int y parameter to the constructor.
Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the
constructor (5), which will set the value of x to 5:
public class Main {
int x;
public Main(int y) {
x = y; }
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println(myObj.x); }}
// Outputs 5
What is OOP with java?
Constructor Parameters:
You can have as many parameters in constructor as you want: Example:
public class Main {
int modelYear;
String modelName;
public Main(int year, String name) {
modelYear = year;
modelName = name;
}
public static void main(String[] args)
{
Main myCar = new Main(1969, "Mustang");
System.out.println( myCar.modelYear + " " + myCar.modelName );
} }
// Outputs 1969 Mustang
Quize_1
 Multiple Objects program?

 Modify Attributes program?

 override existing values program?

 Java Class Methods program?

 Why IT is important ?
Language types: STUDENTS ASSIGNMENT:
1. Machine language or low level language:
2. Assembly language /meno manic code:
3. High-level language:
Translator two types:
4. Interpreter ?
5. Compiler ?
A program need some basic requirement:
6. Variable ?
7. Constant ?
8. Operator ?
9. Operand
10. Expression?
11. Statement ?
Classes have several access levels and there are different types of classes;
 abstract classes, final classes, public class, private class & inner class.
Source File Declaration Rules:
What
look into the source file declaration rules.is OOP with java?
These rules are essential when declaring classes, import statements
and package statements in a
source file.
 There can be only one public class per source file.
 A source file can have multiple non-public classes.
 The public class name should be the name of the source file as well which should be
appended
by .java at the end.
For example:
the class name is public class Employee{ } then the source file should be as
Employee.java.
What is OOP with java?
Source File Declaration Rules:
If the class is defined inside a package, then the package statement should be the first
statement in
the source file.
Import and package statements will imply to all the classes present in the source file.

import java.io.*;
When developing applications in Java, hundreds of classes and interfaces will
What is OOP with java?
be
written, therefore categorizing these classes is a must as well as makes life
much easier.
Import Statements:
Import statement is a way of giving the proper location for the compiler to
find that
particular class.
For example, the following line would ask the compiler to load all the classes
available in
directory java_installation/java/io.

import java.io.*;
Public class Bost {
What is OOP with java?
Java Package:
The java.io package contains nearly every class you might ever need to perform input
and output (I/O) in Java.
All these streams represent an input source and an output destination.
Stream
A stream can be defined as a sequence of data.
There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.
What is OOP with java?
Java Package:
Java io package is used for stream concet to make I/O operation fast.
Stream:
1. Stream is a sequence of data.
o Composed of bytes
System.out-----------system. In----------system. Error

Source : text file, cmd, n/w (Socket)


Destination : file , console , socket
Source + (01001) + program = input stream/read operation (011101) + Destination= output
stream/writing operation
Input/Output package

A Simple Case Study:


we will be creating two classes.
They are Employee and EmployeeTest.

Following are the ways to use 'this' keyword in java :


The this keyword refers to the current object in a method or constructor.
o Using 'this' keyword to refer current class instance variables.
o Using this() to invoke current class constructor.
o Using 'this' keyword to return the current class instance.
o Using 'this' keyword as method parameter.
Input/Output package

import java.util.Scanner;
class apple
{
public static void main(String args[])
{
Scanner inp=new Scanner(System.in);
System.out.println(inp.nextLine());
}}
Input/Output package
import java.io.*;
public class SimpleIO {
public static void main(String args[])
throws IOException
{ // InputStreamReader class to read input
InputStreamReader inp = null;
// Storing the input in inp
inp = new InputStreamReader(System.in);
System.out.println("Enter characters, " + " and '0' to quit.");
char c;
do {
c = (char)inp.read();
System.out.println(c);
}
while (c != '0'); }}
What is OOP with java?
What is java general generic concepts?
o Java Generic methods and generic classes enable programmers to specify, with a
single method declaration, a set of related methods, or with a single class
declaration
o Using Java Generic concept, we might write a generic method for sorting an
array of objects, then invoke the generic method with Integer arrays,
Double
arrays, String arrays and so on, to sort the array elements.
What is OOP with java?
Why java Generic concepts uses?
o The Java Generics allows us to create a single class, interface, and method that can
be used with
different types of data (objects).
o Generics enable the use of stronger type-checking, the elimination of casts, and the
ability to develop generic algorithms.

He most commonly used type parameter names are:


E - Element
K - Key.
N - Number.
T - Type.
V - Value.
etc. - 2nd, 3rd, 4th types.
Advantages of Generics: What is OOP with java?
1. Code Reuse: We can write a method/class/interface once and use it for any type we
want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s always
better to know problems in your code at compile time rather than making your code
fail at run time).
Suppose you want to create an ArrayList that store name of students, and if by
mistake the programmer adds an integer object instead of a string, the compiler
allows it.
But, when we retrieve this data from ArrayList, it causes problems at runtime.
Following are the rules to define Generic Methods:

o
What is OOP with java?
All generic method declarations have a type parameter section delimited by angle

brackets (< and >) that precedes the method's return type ( < E > in the next

example).

o Each type parameter section contains one or more type parameters separated by

commas.

o The type parameters can be used to declare the return type and act as place holders

for the types of the arguments passed to the generic method, which are known as

actual type arguments.

o A generic method's body is declared like that of any other method.


How define generic class: What is OOP with java?
class name <T1, T2 ...> this is paramaters of class
class Test<T> // We use < > to specify Parameter type {
T obj; // An object of type T is declared
Test(T obj) // constructor { this.obj = obj; }
public T getObject() { return this.obj; }}
class Main // Driver class to test above {
public static void main(String[] args) {
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject()); Output:
15
// instance of String type
Ali Ahmad
Test<String> sObj
= new Test<String>(“Ali Ahmad");
System.out.println(sObj.getObject());
}}
What is OOP with java?
class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U
Test(T obj1, U obj2) // constructor {
this.obj1 = obj1;
this.obj2 = obj2; }
Output:
public void print() // To print objects of T and U
GfG
{
15
System.out.println(obj1);
System.out.println(obj2); }}
class Main // Driver class to test above
{ public static void main (String[] args) {
Test <String, Integer> obj = new Test<String, Integer>("GfG", 15);
obj.print();
} }
What is OOP with java?
public class Box<T> {
private T t;
public void add(T t) {
this.t = t; }
public T get() {
return t; }
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Output
Box<String> stringBox = new Box<String>(); Integer Value : 10
integerBox.add(new Integer(10)); String Value : Hello World
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}}
What Is Exception Handling?
Finding errors and exceptions in programs:
The Exception Handling in Java is a mechanism using which the normal flow of
the application is maintained.
we employ a powerful mechanism to handle runtime errors or exceptions in a
program.
A sequence of code that is used to handle the exception is called the
“Exception handler”.
the exception occurred and then restores the Java program to continue with
normal flow.
user should understand why the program stopped
we can handle the exception and provide meaningful messages to the user
about the
issue.
Finding errors and exceptions in programs:

Major Reasons for the Exception to Occur:


o Invalid user input
o Device failure
o Loss of network connection
o Physical limitations (out of disk memory)
o Code errors
o Opening an unavailable file
Finding errors and exceptions in programs:
Benefits Of Exception Handling:

1. It maintains the normal flow of the application Having an exception handler


in a program will not cause the program to terminate
2. Separating Error-Handling Code from "Regular" Code.
3. Provision to Complete Program Execution
4. Easy Identification of Program Code and Error-Handling Code
5. Meaningful Error Reporting
6. Identifying Error Types
Exception Hierarchy
FindingIn Java: and exceptions in programs:
errors
 all exception classes are subtypes if the java.Language.Eception class.
 Throwable class is super/root class of java Exception and contain
subclasses.
 the Exception class is a subclass of the Throwable class.
 there is another subclass called Error which is derived from the Throwable
class.
Finding errors and exceptions in programs:

Types of Exception in Java with Examples:


Finding errors and exceptions in programs:
Types of Exception in Java with Examples:
1. Built-in Exceptions
o Checked Exception: these exceptions are checked at compile-time by the
compiler.
o Unchecked Exception: The compiler will not check these exceptions at compile
time.

2. User-Defined Exceptions:
Finding errors and exceptions in programs:
Built-in Exception:
Built-in exceptions are the exceptions, which are available in Java libraries.
These exceptions are suitable to explain certain error situations.
1) Arithmetic exception: It is thrown when an exceptional condition has occurred in
an arithmetic operation.
class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e)
{
System.out.println ("You Shouldn't divide a number by zero");
} }}
Finding errors and exceptions in programs:
2) NullPointer Exception:
Class: Java.lang.NullPointer Exception
An object of this class is created whenever a member is invoked with a “null” object.
class Exception2
{
public static void main(String args[])
{
try{
String str = null;
System.out.println (str.length()); }
catch(NullPointerException e){
System.out.println("NullPointerException..");
}}}
3. Java Scanner ioException() Method:
Finding errors and exceptions in programs:
The ioException() is a method of Java Scanner class which is used to get
the
IOException last thrown by this Scanner's readable. It returns null if no such
exception
exists.
Syntax
Following is the declaration of ioException() method:
Public IOException ioException()

Returns
The ioException() method returns the last exception thrown by this scanner's
readable.
Finding errors and exceptions in programs:
3. Java Scanner ioException() Method:
import java.util.*;
public class ScannerIOExceptionExample1 {
public static void main(String[] args) {
//Create a new scanner with the specified String Object
Scanner scan = new Scanner("Hello World!");
System.out.println("" + scan.nextLine()); //scan=Hello World
//Check if there is an IO exception

System.out.println("Exception Output: " + scan.ioException()); // null

value
scan.close();
} }
Finding errors and exceptions in programs:

class myexception extends Exception {


user-defined exception:
public class main {
public myexception (String s)
public static void main(String[] args) {
{
try super(s);
{ }
int no1=11, no2=2;
if (no1<no2)
{ }
throw new myexception("this vlue is not possible");
}
else
{
System.out.println(no1 - no2);
}}
catch(myexception e)
{
System.out.println("error“+ e.getmessage);
} } }
Finding errors and exceptions in programs:
user-defined exception
class MyException extends Exception {
public MyException(String s) {
// Call constructor of parent Exception
super(s); // A Class that uses above MyException
}}
public class Main // Driver Program {
public static void main(String args[]) {
try {
// Throw an object of user defined exception
throw new MyException(“Jan"); }
catch (MyException ex) {
System.out.println("Caught"); // Print the message from MyException object
System.out.println(ex.getMessage());
} } }
Serialization in Java is a mechanism of writing the state of an object into a
What is the concept of Serialization in Java?
byte-stream.
The reverse operation of serialization is called deserialization where byte-
stream is
converted into an object.
The serialization and deserialization process is platform-independent, it means
you can
serialize an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method
deserialization we call the readObject() method
What isinthe
What is Serialization concept of Serialization in Java?
Java?
Serialization in Java is the process of converting the Java code Object into
a Byte
Stream, to transfer the Object Code from one Java Virtual machine to another
and
recreate it using the process of Deserialization.
What is the concept of Serialization in Java?
Why do we need Serialization in Java?
We need Serialization for the following reasons:
Communication: This enables multiple computer systems to design, share
and execute objects simultaneously.
Caching: The time consumed in building an object is more compared to the
time required for de-serializing it. Serialization minimizes time consumption
by caching the giant objects.
Deep Copy: Cloning process is made simple by using Serialization. An
exact replica of an object is obtained by serializing the object to a byte
array, and then de-serializing it.
What is the concept of Serialization in Java?
Cross JVM Synchronization: The major advantage of Serialization is that
it works across different JVMs that might be running on
different architectures or Operating Systems
Persistence: The State of any object can be directly stored by applying
Serialization on to it and stored in a database so that it can be retrieved
later.
What is the concept of Serialization in Java?
java.io.Serializable interface:
Serializable is a marker interface (has no data member and method).
It is used to "mark" Java classes so that the objects of these classes may get a
certain
capability.
The Cloneable and Remote are also marker interfaces.
The String class and all the wrapper classes implement
the java.io.Serializable interface by default.
What is the concept of Serialization in Java?
import java.io.Serializable;
public class Student implements Serializable //Student class implements Serializable
interface

{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
What is the concept of Serialization in Java?

Constructor: It creates an ObjectOutputStream


that writes to the specified
1) public ObjectOutputStream(OutputStream out) throws
OutputStream.
IOException { }

Important Methods: Description

1) public final void writeObject(Object obj) throws It writes the specified object to the
IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} It flushes the current output stream.

3) public void close() throws IOException {} It closes the current output stream.
What is the concept of Serialization in Java?
ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive
data written using an ObjectOutputStream.
Constructor:
1) public ObjectInputStream(InputStream It creates an ObjectInputStream that reads
in) throws IOException {} from the specified InputStream.

Important Methods:
Description

1) public final Object readObject() throws It reads an object from the input stream.
IOException, ClassNotFoundException{}

2) public void close() throws IOException {} It closes ObjectInputStream.


What is the concept of Serialization in Java?
How do we serialize an Object?
Example of Java Serialization
In this example, we are going to serialize the object of Student class from
above code.
The writeObject() method of ObjectOutputStream class provides the
functionality to serialize the object. We are saving the state of the object in the
file named f.txt.
Persist.java
What is the concept of Serialization in Java?
import java.io.*;
class Persist{
public static void main(String args[]){
try{
Student s1 =new Student(211,"ravi"); //Creating the object
FileOutputStream fout=new FileOutputStream("f.txt"); //Creating stream and writing the object
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
out.close(); //closing the stream
System.out.println("success"); }
catch(Exception e) {
System.out.println(e);
} } }
What is the concept of Serialization in Java?
Deserialization:
Deserialization: It is the reverse process of Serialization where the Serialized Byte Stream of an
object from the sender is recreated at the receiving end.
Example of Java Deserialization:
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization.
Let's see an example where we are reading the data from a deserialized object.
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse
operation of serialization.
Let's see an example where we are reading the data from a deserialized object.
What is the concept of Serialization in Java?
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt")); //Creating stream to read the object

Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name); //printing the data of the serialized object

in.close(); //closing the stream

} catch(Exception e){System.out.println(e);}
}
}
Output:
211 ravi
What is the concept of Serialization in Java?

Advantages and Disadvantages of Serialization


in Java?
How to use JDBC technology:

What is API?
API (Application programming interface) is a document that contains a description of
all the features of a product or software.
It represents classes and interfaces that software programs can follow to
communicate with each other.
API can be created for applications, libraries, operating systems, etc.
How to use JDBC technology:
Java JDBC:
JDBC stands for Java Database Connectivity.
JDBC is a Java API to connect and execute the query with the database.
It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database.
How to use JDBC technology:
Open Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017.
It is based on SQL Call Level Interface.
The java.sql package contains classes and interfaces for JDBC API.
How to use JDBC technology:
A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface

Why Should We Use JDBC:


Before JDBC, ODBC API was the database API to connect and execute the query with the
database.
However, ODBC API uses ODBC driver, which is written in C language (i.e. platform dependent
and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java
language).
How to use JDBC technology:
We can use JDBC API to handle database using Java program and can perform the
following activities:
o Connect to the database
o Execute queries and update statements to the database
o Retrieve the result received from the database

What are Java JDBC topics?


JDBC Drivers:
JDBC Driver is a software component that enables java application to interact with the database.
How to use JDBC technology:
There are 4 types of JDBC drivers:
o JDBC-ODBC bridge driver
o Native-API driver (partially java driver)
o Network Protocol driver (fully java driver)
o Thin driver (fully java driver)
1) JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method into the ODBC function.
How to use JDBC technology:
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
How to use JDBC technology:
2) Native-API driver
The Native API driver uses the client-side libraries of the database.

The driver converts JDBC method calls into native calls of the database API.
How to use JDBC technology:
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
How to use JDBC technology:
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol.
It is fully written in java.
How to use JDBC technology:
Advantage:
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding.
o Maintenance of Network Protocol driver becomes costly.
How to use JDBC technology:
4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.

That is why it is known as thin driver.

It is fully written in Java language.


How to use JDBC technology:
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
5 Steps to connect to the Database
Java Database Connectivity with 5 Steps:
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection
5 Steps to connect to the Database
1) Register the driver class:

The forName() method of 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


Example to register the Oracle Driver class:
Java program is loading oracle driver to establish database connection.

Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object:

The getConnection() method of DriverManager class is used to establish connection with the
database.
5 Steps to connect to 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)
3) throws SQLException
Example to establish connection with the Oracle database:
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe
","system","password");
3) Create the Statement object:
The create Statement() method of Connection interface is used to create statement.

The object of statement is responsible to execute queries with the database.


5 Steps to connect to the Database
Syntax of create Statement() method:
public Statement create Statement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();

4) Execute the query:

The executeQuery() method of Statement interface is used to execute queries to the


database.

This method returns the object of ResultSet that can be used to get all the records of
a table.
5 Steps to connect to the Database

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 Steps to connect to the Database

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();
5 Steps to connect to the Database
Connectivity with Oracle using JDBC:
Java Database Connectivity with Oracle:
To connect java application with the oracle database, we need to follow 5 following steps.
Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe
jdbc is the API.
oracle is the database.
thin is the driver.
localhost is the server name on which oracle is running
we may also use IP address, 1521 is the port number
XE is the Oracle service name.
5 Steps to connect to the Database

Connectivity with Oracle using JDBC:

Java Database Connectivity with Oracle:

Username: The default username for the oracle database is system.

Password: It is the password given by the user at the time of installing the oracle database.
5 Steps to connect to the Database

Create a Table:
Before establishing connection, let's first create a table in oracle database. Following
is the SQL query to create a table.

create table emp(id number(10),name varchar2(40),age number(3));


ExecuteQuery("select * from emp");
5 Steps to connect to the Database
Example to Connect Java Application with Oracle database:
import java.sql.*;
class OracleCon{ Note:
public static void main(String args[]){ To connect java application with the Oracle
try{ database ojdbc14.jar file is required to be loaded.
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

Statement stmt=con.createStatement();

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


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}
catch(Exception e)

{ System.out.println(e); } } }
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related
to each other by inheritance. Polymorphism is derived from 2 words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java:
1. compile-time polymorphism
2. Runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
1. Compile-time polymorphism:
Polymorphism
 Compile-time polymorphism is obtained through method overloading.
 When two or more methods in the same class have the same name but different parameters, it’s called overloading.
 Overloading has more than one method with the same name but different parameters.
 Overloading has only one class
 Purpose : increase program readability.
 It is compile time polymorphism compiler decide call which method
public class Processor {
public void process(int i, int j)
{ /* ... */ }
public void process(int[] ints)
{ /* ... */ }
public void process(Object[] objs)
{ /* ... */ } }
Polymorphism
1. Method overloading/ Compile-time polymorphism:
public class polymorphismoverlaod {
public void show(int No1)
{
System.out.println(No1); }
void show(int No2, int No3) {
System.out.println("Values: " + No2 + " Values: "+ No3); }
public static void main(String args[]) {
polymorphismoverlaod b=new polymorphismoverlaod();
b.show(4);
b.show(4 , 5);
}}
2. Runtime Polymorphism in Java:
Polymorphism
 Method overriding is an example of runtime polymorphism.
 the method signature (name and parameters) are the same in the superclass and the child class, it’s called overriding
 overriding has two classes super and sub-class, inheritance include.
 Name and parameter are both same.
 overriding Method call is decided by JVM
Purpose: use method in the child class already present in parent class

public class Processor {


public void process(int i, int j)
{ /* ... */ } } /* ... */
class MathProcessor extends Processor
{ @Override
public void process(int i, int j)
{ /* ... */ } }
Polymorphism
an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Let's first understand the upcasting before Runtime Polymorphism.
Up casting:
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting.

class A { }
class B extends A { }
A a=new B(); //upcasting
Polymorphism
For upcasting, we can use the reference variable of class type or an interface type.
For Example:
interface I {}
class A{}
class B extends A implements {}

Here, the relationship of B class would be:


B IS-A A
B IS-A I
B IS-A Object
Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Polymorphism
Example of Java Runtime Polymorphism/ overriding:
class Bost {
public void add()
{
System.out.println("running-1");
} }
class BCS1 extends Bost {
public void add() {
System.out.println("running safely with 60km");
}
class BCS2 extends Bost { }
public static void main(String args[]) {
Bost b = new BCS(); //upcasting
b.add();
} }
Java Runtime Polymorphism Example: Shape
class Shape {
void draw() { System.out.println("drawing..."); } } s.draw();
class Rectangle extends Shape{ s=new Circle();
void draw() { System.out.println("drawing rectangle..."); } } s.draw();
class Circle extends Shape{ s=new Triangle();
void draw() { System.out.println("drawing circle..."); } } s.draw();
class Triangle extends Shape{ } }
void draw() { System.out.println("drawing triangle..."); } }
class TestPolymorphism2{
Output:
public static void main(String args[]) {
Shape s;
drawing rectangle...
s=new Rectangle(); drawing circle...
drawing triangle...
Java File Class:
The File class of the java.io package is used to perform various operations on files and directories.
There is another package named java.io that can be used to work with files.
File and Directory:
A file is a named location that can be used to store related information.
For example, main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories.
A directory inside a directory is known as subdirectory.
Java File Class:
Create a Java File Object:
we need to import the java.io.File package first.
Then we can create objects of file.
File file = new File(String pathName); // creates an object of File using the path
Here, we have created a file object named file

Java File Operation Methods:


Operation Method Package
To create file createNewFile() java.io.File
To read file read() java.io.FileReader
To write file write() java.io.FileWriter
To delete file delete() java.io.File
Java File Class:
Java create files:
To create a new file, we can use the createNewFile() method.
• True if a new file is created.
• False if the file already exists in the specified location.
Java File Class:
Example: Create a new File:
java.io.File; // importing the File class import
class Main {
public static void main(String[] args) {
File file = new File("newFile.txt"); // create a file object for the current location
try {
// trying to create a file based on the object
boolean value = file.createNewFile();
if (value) {
System.out.println("The new file is created."); }
else {
System.out.println("The file already exists."); } }
catch(Exception e) {
e.getStackTrace();
} }}
Java File Class:
Example: Create a new File:
The file object is linked with the specified file path.
File file = new File("newFile.txt");
Here, we have used the file object to create the new file with the specified path.
If newFile.txt doesn't exist in the current location, the file is created and this message is shown.
The new file is created.
if newFile.txt already exists, we will see this message.
The file already exists.
Java File Class:
To delete a file in Java, use the delete() method:
import java.io.File;
public class DeleteFile
{ public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName()); }
else {
System.out.println("Failed to delete the file.");
} }}
Threads Concept in Java:
 Thread is an individual, lightweight and smallest unit of given process.
 A thread is a single sequential flow of control within a program.
 Multiple threads running at the same time and performing different tasks in a single program
 Threads can be used to perform complicated tasks in the background without interrupting the
main program.
 all the programs have at least one thread, known as the main thread, that is provided by the
JVM at the starting of the program's execution
Examples: browser tabs.
Note : lightweight means, a thread that takes less processing time
Threads Concept in Java:
all the threads have their own separate path for execution, so each thread of a process is
independent.
if a thread gets an exception or an error at the time of its execution, it doesn't affect the execution
of the other threads.
Threads Concept in Java:
Why do we use thread in java.
 Thread allows a program to switch between lightweight process
 A process use thread not use More CPU time.
 Give priority to program units on time base processing.
 If there is only one CPU one thread be runnable at time.
 Threads context switch without any need of kernel involve and user level define library and
kernel not know of switching the threads each others.
 Some demand of swing application in java.
Threads Concept in Java:
In a simple way, a Thread is a:
 we can perform multiple activities within a single process.
 Lightweight process(take less processing time).
 Series of executed statements.
 Nested sequence of method calls.
Multithreading in Java:
Multithreading in Java is a process of executing multiple threads simultaneously.
Multiprocessing and multithreading, both are used to achieve multitasking.
 threads use a shared memory area, not allocate separate memory
 Java Multithreading is mostly used in games, animation, etc.
Multitasking vs multithreading

 Multitasking refers to a computer’s ability to perform multiple jobs concurrently.

More than one program are running concurrently, e.g. unix, windows

 A thread is a single sequence of execution within a program.

 Multithreading refers to multiple threads of control within a single program.

Each program can run multiple threads of control within it .e.g browser tabs.
.
.
Process vs threads
 Executing state of a program is called process.
 Subset/ subpart of the processing is called thread.
Threads Concept in Java:
Advantages of Java Multithreading:
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, no affect other threads if an exception occurs in a single thread.
Multitasking:
Multitasking is a process of executing multiple tasks simultaneously.
Multitasking can be achieved in two ways:
1. Process-based Multitasking (Multiprocessing)
2. Thread-based Multitasking (Multithreading)
Threads Concept in Java:
1) Process-based Multitasking (Multiprocessing)
1. Each process has an address in memory. each process allocates a separate memory area.
2. A process is heavyweight.
3. Cost of communication between the processes is high.
4. Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
Example : listen to music and browse the internet at the same time
2) Thread-based Multitasking (Multithreading)
5. Threads share the same address space.
6. A thread is lightweight.
7. Cost of communication between the thread is low.
Life cycle of threads:
Thread Model:
Just like a process, a thread exists in several states.
Life cycle of threads:
Newborn : When a thread is created (by new statement ) but not yet to run.
Runnable : a thread is ready to run and is awaiting for the control of the processor, or in other
words, threads are in this state in a queue and wait their turns to be executed.
Running : Running means that the thread has control of the processor, its code is currently being
executed and thread will continue in this state until it get preempted by a higher priority thread, or
until it relinquishes control.
Blocked : A thread is Blocked means that it is being prevented from the Runnable ( or Running)
state and is waiting for some event in order for it to reenter the scheduling queue.
Dead : A thread is Dead when it finishes its execution or is stopped (killed) by another thread.
Life cycle of threads:
Below, we are to summarize these methods :
start ( ) : A newborn thread with this method enter into Runnable state and Java run time create a
system thread context and starts it running.
stop( ) : This method causes a thread to stop immediately and to end a thread.
suspend( ) : This method is different from stop( ) method. Only stop running, and later on can be
restored by calling it again.
resume ( ) : This method is used to revive a suspended thread. There is no guarantee that the
thread will start running right way, since there might be a higher priority thread running already, but,
resume () causes the thread to become eligible for running.
sleep (int n ) : This method causes the run time to put the current thread to sleep for n
milliseconds. After n milliseconds have expired.
Life cycle of threads:
Below, we are to summarize these methods :
yield( ) : The yield() method causes the run time to switch the context from the current thread to
the next available runnable thread.
Life cycle of threads:
1) New (Ready to run) A thread is in New when it gets CPU time.
2) Running A thread is in a Running state when it is under execution.
3) Suspended A thread is in the Suspended state when it is temporarily inactive or under execution.
4) Blocked A thread is in the Blocked state when it is waiting for resources.
5) Terminated A thread comes in this state when at any given time, it halts its execution immediately.
Java Thread Methods:
Thread Classes:
A Thread class has several methods and constructors which allow us to perform various
operations on a thread.
The Thread class extends the Object class.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Java Thread Methods:
.
S. Modifier and Type Method Description
N.
1) Void start() It is used to start the execution of the thread.
2) Void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing
thread object.
5) Void join() It waits for a thread to die.
6) String getName() It returns the name of the thread.
7) Void setName() It changes the name of the thread.
8) Long getId() It returns the id of the thread.
Java Thread Methods:
.
9) static void yield() It causes the currently executing thread object to pause and
allow other threads to execute temporarily.
10) Void suspend() It is used to suspend the thread.
11) Void stop() It is used to stop the thread.
12) Void destroy() It is used to destroy the thread group and all of its subgroups.
13) Void notify() It is used to give the notification for only one thread which is
waiting for a particular object.
14) Void notifyAll() It is used to give the notification to all waiting threads of a
particular object.
0
Java Thread Methods:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

1) Java Thread Example by extending Thread class


class Bost extends Thread {
1) Extend Syntax: public void run(){
public class Main extends Thread System.out.println("thread is running...");
{
public void run() }
{ public static void main(String args[]){
System.out.println("This code is running in a thread"); Bost t1=new Bost();
}} t1.start();
} } OUTPUT:
thread is running...
Java Thread Methods:
There are two ways to create a thread:

Another way to create a thread is to implement the Runnable interface:


2) Implement Syntax
class Multi implements Runnable{
public class Main implements Runnable { public void run() {

public void run() System.out.println("thread is running...");


}
{
public static void main(String args[]){
System.out.println("This code is running in a thread"); Multi m1=new Multi();

}} Thread t1 =new Thread(m1);


// Using the constructor Thread(Runnable r)
t1.start();
} }
Java Thread program:
3) Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors.

public class MyThread1 // Main method {


public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
t.start(); // the start() method moves the thread to the active state
String str = t.getName(); // getting the thread name by invoking the getName() method
System.out.println(str);
} }
Spawn :a function that loads and executes a new child process
Java Thread program in interface :
class Hi implements Runnable
{
public void run() {
for(int x=1; x<=5; x++)
{
System.out.println("jan");
try { Thread.sleep(1000);} catch (Exception e){}
} } }
class hello implements Runnable {
public void run()
{
for(int x=1; x<=5; x++)
{
System.out.println("jan----------------jan");
//System.out.println(" vlaue :" + Thread.currentThread().getName()); // this will display thread name
try { Thread.sleep(1000);} catch (Exception e) {}
} } }
Java Thread program:
public class simplethread {
public static void main(String args[])
{
Runnable obj1=new Hi();
Runnable obj2=new hello();
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
try {
Thread.sleep(10000); }
catch(Exception e) {}
t2.start();
t2.suspend(); // this will suspend t2
t2.resum(); // this will restart t2
}
}
Java Thread program:
class A extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getPriority()); } }
public class Threadpriority {
public static void main(String args[]) {
A t1=new A();
A t2=new A();
A t3=new A();
// t1.setName("t1 Thread");
// t2.setName("t2 Thread");
// t3.setName("t3 Thread");
t1.setPriority(5); // use for set priority by default priority is 0 => 10
t2.setPriority(2);
t1.start();
t2.start();
t3.start();
} }
Thread Example: Java Thread program:
/* Use of suspend() and resume() methods */
class Thread1 extends Thread {
public void run( ) {
try {
System.out.println (" First thread starts running" );
sleep(10000);
System.out.println (" First thread finishes running" ); }
catch(Exception e) { } } }

class Thread2 extends Thread {


public void run( ) { try {
System.out.println ( "Second thread starts running");
System.out.println ( "Second thread is suspended itself ");
suspend( );
System.out.println (" Second thread runs again" ); }
Java Thread program:
catch(Exception e) { } } }
class Demonstration_116 {
public static void main (String args[ ] ){
try{
Thread1 first = new Thread1( ); // It is a newborn thread i.e. in Newborn state
Thread2 second= new Thread2( ); // another new born thread
first.start( ); // first is scheduled for running OUTPUT:
second.start( ); // second is scheduled for running Revive the second thread
System.out.println("Revive the second thread" ); First thread starts running
second.resume( ); // If it is suspended Second thread starts running

System.out.println ("Second thread went for 10 seconds sleep " ); Second thread is suspended itself

second.sleep (10000); Second thread went for 10 seconds sleep

System.out.println ("Wake up second thread and finishes running" );


System.out.println ( " Demonstration is finished "); }
catch(Exception e) { } } }
What Does Application Programming Interface (API)
Mean?
An application-programming interface (API) is a collection of prewritten packages, classes, and
interfaces with their respective methods and constructors.
a user interface, which facilitates interaction between humans and computers
minimizing the number of lines written within pieces of code.
Java Development Kit (JDK) is comprised of three basic components, as follows:
 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)
What Does Application Programming Interface (API)
Mean?
The official API includes packages, e.g., applet packages, graphics and GUI swing packages,
input/output (IO) packages and Abstract Windows Toolkit (AWT), among others.
There are three frames when an API starts, as follows:
 The first frame shows all API components (classes and packages).
 The second frame shows all interfaces, classes and exceptions of that particular package.
 The third and primary frame provides all of API packages, which can be expanded in the
main frame to show the index, class hierarchy and help sections.
What Does Graphical User Interface (GUI) Mean?

What Does Graphical User Interface (GUI) Mean?

GUI no knowledge of any programming language.

A graphical user interface (GUI) is an interface through the use of icons, menus and other visual

indicators or representations (graphics).

GUI by a pointing device such as a mouse, trackball, stylus/Graph, or by a finger on a touch screen.

The first human/computer use (DOS prompt).


Java AWT (Abstract Window Toolkit)
Java AWT:
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Why AWT is platform independent?


AWT calls directly the native platform (operating systems) subroutine for creating API
components
For example, an AWT GUI look and feel for the different platforms like Windows, MAC OS, and
Unix.
Java AWT Hierarchy:
The hierarchy of Java AWT classes are given below.
Java AWT Hierarchy:
Components:
Component is an abstract class that encapsulates all of the attributes of a visual components.
every component in a particular position on a screen, we need to add them to a container.

Canvas is not hierarchy part of applet or Frame windows, canvas encapsulates a blank window, which can be
drawn upon.

Types of containers:

Container class is a subclass of component.

There are four types of containers in Java AWT:


1. Window
2. Panel
3. Frame
4. Dialog
Java AWT Hierarchy:
1. Java AWT Window:
The window is the container that have no borders and menu bars.
You must use frame, dialog or another window for creating a window.
Java AWT Hierarchy:
2. Java AWT Panel:
The Panel is the container that doesn't contain title bar, border or menu bar.
It is generic container for holding the components.
It can have other components like button, text field etc.
Java AWT Hierarchy:
3. Java AWT Frame:
The Frame is the container that contain title bar and border and can have menu bars.
It can have other components like button, text field, scrollbar etc.
Java AWT Hierarchy:
4. Java AWT Dialog:
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. Unlike Frame, it doesn't have maximize and minimize buttons
Java AWT Hierarchy:
Applet in Java?

Java applets are used to provide interactive features to web applications and can be executed

by browsers for many platforms.


Java AWT
Useful Methods of Component Class:

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default false.
Java AWT
There are two ways to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
import java.awt.*;
class First extends Frame {
First() { Button b=new Button("click me");
b.setBounds(30,100,80,30); // R,T,L,D, setting button position
f.add(b); //adding button into frame
f.setSize(300,300); //frame size 300 width and 300 height
f.setLayout(null); //no layout now by default Border Layout
f.setVisible(true); //now frame willbe visible, bydefault not visible
} public static void main(String args[]) {
First f=new First(); } }
Java AWT
There are two ways to create a GUI using Frame in AWT.
2) By creating the object of Frame class (association)
import java.awt.*;
Public class First2{
First2() {
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30); //R, T, L, D
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} public static void main(String args[]){
First2 f=new First2();
} }
Java AWT
Java AWT Label:
It is used to display a single line of read only text.

The java.awt.Component class has following fields:


static int LEFT: It specifies that the label should be left justified.
static int RIGHT: It specifies that the label should be right justified.
static int CENTER: It specifies that the label should be placed in center.
Java AWT
Label class Constructors:

Sr. no. Constructor Description

1. Label() It constructs an empty label.

2. Label(String text) It constructs a label with the given string (left


justified by default).

3. Label(String text, int It constructs a label with the specified string and
alignement) the specified alignment.
Java AWT
Label Class Methods Specified:

Sr. no. Method name Description

1. void setText(String text) It sets the texts for label with the specified text.

2. void setAlignment(int alignment) It sets the alignment for label with the specified
alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

5. void addNotify() It creates the peer for the label.

6. AccessibleContext getAccessibleContext() It gets the Accessible Context associated with the


label.

7. protected String paramString() It returns the string the state of the label.
Java AWT(Label Example)
import java.awt.*;
public class LabelExample {
public static void main(String args[]) {
Frame f = new Frame ("Label example"); // creating the object of Frame class and Label class
Label l1, l2; // initializing the labels
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30); // set the location of label
l2.setBounds(50, 150, 100, 30);
f.add(l1); // adding labels to the frame
f.add(l2);
f.setSize(400,400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true); } }
Java AWT TextField:
The object of a TextField class is a text component that allows a user to enter a single line text
and edit it.

TextField Class constructors:

Sr. no. Constructor Description

1. TextField() It constructs a new text field component.

2. TextField(String text) It constructs a new text field initialized with the given string
text to be displayed.

3. TextField(int columns) It constructs a new textfield (empty) with given number of


columns.

4. TextField(String text, int It constructs a new text field with the given text and given
columns) number of columns (width).
Java AWT TextField:

Method Inherited:
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
Java AWT TextField:
Java AWT TextField Example:
import java.awt.*;
public class TextFieldExample1 {
public static void main(String args[]) {
Frame f = new Frame("TextField Example");
TextField t1, t2; // creating objects of textfield
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);

f.setVisible(true); }}
Java AWT TextArea:
Java AWT TextArea:
The object of a TextArea class is a multiline region that displays text. It allows the editing of multiple line text.
It inherits TextComponent class.
import java.awt.*;
public class TextAreaExample {
TextAreaExample() // constructor to initialize {
Frame f = new Frame();
TextArea area = new TextArea("Welcome to javatpoint"); // creating a text area
area.setBounds(10, 30, 300, 300); // setting location of text area in frame
f.add(area);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[])
{
new TextAreaExample(); } }
Java AWT Checkbox
Java AWT Checkbox:
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Checkbox Class Constructors:
Sr. no. Constructor Description

1. Checkbox() It constructs a checkbox with no string as the label.

2. Checkbox(String label) It constructs a checkbox with the given label.

3. Checkbox(String label, boolean state) It constructs a checkbox with the given label and sets the given state.

4. Checkbox(String label, boolean state, It constructs a checkbox with the given label, set the given state in the specified
CheckboxGroup group) checkbox group.

5. Checkbox(String label, It constructs a checkbox with the given label, in the given checkbox group and
CheckboxGroup group, boolean state) set to the specified state.
Java AWT Checkbox Example:
import java.awt.*;
public class CheckboxExample1 {
CheckboxExample1() {
Frame f = new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main (String args[]) {
new CheckboxExample1(); } }
Java AWT CHECKBOX GROUP RADIO
import java.awt.Frame
import java.awt.*;
public class CHECKBOX_1 {
public static void main(String args[]) {
Frame f=new Frame("title");

CheckboxGroup chkrd2=new CheckboxGroup();


Checkbox checkBox1 = new Checkbox("C++", chkrd2, false);
checkBox1.setBounds(100,150, 50,50);
f.add(checkBox1);
CheckboxGroup chkrd3=new CheckboxGroup();
Checkbox checkBox2 = new Checkbox("C", chkrd3, false);
checkBox2.setBounds(100,200, 50,50);
f.add(checkBox2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
} }
Java AWT CHECKBOX GROUP RADIO
import java.awt.Frame
import java.awt.*;
public class CHECKBOX_1 {
public static void main(String args[]) {
Frame f=new Frame("title");

Choice ch=new Choice();


ch.add("first");
ch.add("2nd");
ch.add("3rd");
f.add(ch);
ch.setBounds(30,250,50,30);

f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
} }
Java AWT List
import java.awt.Frame
import java.awt.*;
public class CHECKBOX_1 {
public static void main(String args[]) {
Frame f=new Frame("title");
List l2=new List(5);
l2.setBounds(100, 200, 75, 75);
l2.add("Item 1");
l2.add("Item 2");
l2.add("Item 3");
l2.add("Item 4");
l2.add("Item 5");
f1.add(l2);
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
} }
Java AWT Scrollbar Example:

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a
GUI component allows us to see invisible number of rows and columns.

Where the parameters,


orientation: scrollbar will be horizontal or vertical.
Value: specify the starting position of Scrollbar .
Minimum: specify the minimum width of track on which scrollbar is moving.
Maximum: specify the maximum width of track on which scrollbar is moving.
Java AWT Scrollbar Example:

Java AWT Scrollbar


TThe fields of java.awt.Image class are as follows:
1. HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
2. VERTICAL - It is a constant to indicate a vertical scroll bar.
Java AWT Scrollbar Example:

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a
GUI component allows us to see invisible number of rows and columns.
import java.awt.*;
public class NewClass {
public static void main(String args[])
{
Frame f=new Frame();
Scrollbar s=new Scrollbar();

s.setBounds(100,50,100,50);
f.add(s);

f.setSize(400,400);
f.setLayout(null);

f.setVisible(true); }}
Java AWT USER PASSWORD: Example:

public class USER_PASSWORD { Label l2=new Label("password:");


f.add(l2);
public static void main(String[] args) { l2.setBounds(50,170, 150,20);
Frame f=new Frame("Accounts");

TextField tf2=new TextField(20);


Label l1=new Label("username:");
f.add(l1); tf2.setEchoChar('*');
l1.setBounds(50,100, 150,20); f.add(tf2);
tf2.setBounds(50,200, 150,30);
TextField tf=new TextField(“Enter name", 20);
tf.setBounds(50,130, 150,30);
f.setSize(400,400);
f.add(tf);
f.setLayout(null);
f.setVisible(true);
}}
Java AWT Canvas STUDENT ASSINMENT:

Java AWT Canvas


The Canvas class controls and represents a blank rectangular area where the application
can draw or trap input events from the user. It inherits the Component class.

Method Inherited by Canvas Class


The Canvas has inherited above methods from the following classes:
 lang.Component
 lang.Object
Applet:
What is applet ?
An applet is a Java program that runs in a Web browser.
An applet can be a fully functional Java application because it has the entire Java API .

There are some important differences between an applet and a standalone Java
application, including the following
 An applet is a Java class that extends the java.applet.Applet class.
 applet class will not be defined main().
 Applets be embedded within an HTML page.
 A JVM is required to view an applet.
The JVM can be either a plug-in of the Web browser or a separate runtime environment.
 Applets have strict security rules that are enforced by the Web browser.
Applet Life Cycle:
Life Cycle of an Applet:
Four methods in the Applet class gives you the framework
init − This method is intended for whatever initialization is needed for your applet.
start − This method is automatically called after the browser calls the init method.
stop − This method is automatically called when the user moves off the page on which the
applet sits.
destroy − This method is only called when the browser shuts down normally.
paint − after the start() method, any time the applet needs to repaint itself in the browser.
Paint() method inherited from the java.awt.
Applet Life Cycle:
It provides 4 life cycle methods of applet.

public void init(): is used to initialized the Applet. It is invoked only once.

public void start(): is invoked after the init() method or browser is maximized. It is used to

start the Applet.

public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is

minimized.

public void destroy(): is used to destroy the Applet. It is invoked only once.
Applet Life Cycle:
Java.awt.Component class:
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewer tool.
Applet Example:
import java.applet.Applet;

import java.awt.Graphics; myapplet.html


public class First extends Applet <html>
<body>
{
<applet code="First.class" width="300" height="300">
public void paint(Graphics g) { </applet>
g.drawString("welcome",150,150); </body>
</html>
}

}
Applet Example:
Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by:
appletviewer First.java.
//Now Html file is not required but it is for testing purpose only.

import java.applet.Applet;
import java.awt.Graphics; c:\>javac First.java
public class First extends Applet{ c:\>appletviewer First.HTML
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
Applet Advatages:
Advantage of Applet:
There are many advantages of applet:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

Drawback of Applet:
 Plugin is required at client browser to execute applet.
The Applet Class:
The Applet Class:
Every applet is an extension of the java.applet.Applet class.
These include methods that do the following :
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser
 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Java Swing
Java Swing :
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.

What is JFC:
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Java Swing
Hierarchy of Java Swing classes
Java AWT VS Swing

 Components are heavyweight components are light weight


 Platform dependent platform independent
 Has less advance components has more advanced components
 Executions is slower execution is faster
 Not support Model-View-Controller(MVC) pattern support MVC pattern
 Components require more memory space not require much memory space
 Import java AWT package GUI import java SWING package for application
Java Swing
Java Swing Examples:
There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
Java Swing JBUTTON
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new Jframe();

JButton b=new JButton("click”);


b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);

f.setSize(400,500);
f.setLayout(null); //using no layout managers
f.setVisible(true); //making the frame visible
} }
Java Swing JLABEL/JPasswordField:
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value);
f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
} }
Java Swing
Java JComboBox ch:
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true); }
public static void main(String[] args) {
new ComboBoxExample();
} }
Java AWT and SWING Layout OF CONTAINER:

Introduction:
Layout means the arrangement of components within the container.
The task of layouting the controls is done automatically by the Layout Manager.
If we do not use layout manager then also the components are positioned by the default
layout manager.
Java provide us with various layout manager to position the controls.
The properties like size, shape
Java AWT Layout OF CONTAINER:

AWT Layout Manager Classes with the Swing package:


Following is the list of commonly used controls while designed GUI using AWT.
BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south and center.
Java BORDER LAYOUT OF CONTAINER:

BORDER LAYOUT: f.add(b1,BorderLayout.NORTH);


import java.awt.*;
f.add(b2,BorderLayout.SOUTH);
import javax.swing.*;
public class BORDERLAYOUTT { f.add(b3,BorderLayout.EAST);
public static void main(String args[]) f.add(b4,BorderLayout.WEST);
{ JFrame f=new JFrame();
f.add(b5,BorderLayout.CENTER);
JButton b1=new JButton("NORTH");
JButton b2=new JButton("SOUTH");
JButton b3=new JButton("EAST"); f.setSize(300,300);
JButton b4=new JButton("WEST"); f.setVisible(true);
JButton b5=new JButton("CENTER");
}}
Java AWT Layout OF CONTAINER:

AWT Layout Manager Classes:


FlowLayout
The FlowLayout is the default layout. It layouts the components in a directional flow.
FlowLayout flow=new FlowLayout(FlowLayout.LEFT);
FLOW LAYOUT:
Java FLOW LAYOUT OF CONTAINER:
import java.awt.*;
import javax.swing.*; obj.add(b1);

public class BORDERLAYOUTT { obj.add(b2);

public static void main(String argvs[]) obj.add(b3);

{ JFrame obj = new JFrame(); obj.add(b4);

JButton b1 = new JButton("1"); obj.add(b5);

JButton b2 = new JButton("2"); obj.add(b6);

JButton b3 = new JButton("3"); obj.add(b7);

JButton b4 = new JButton("4"); obj.add(b8);

JButton b5 = new JButton("5"); obj.add(b9);

JButton b6 = new JButton("6"); obj.add(b10);

JButton b7 = new JButton("7"); obj.setLayout(new FlowLayout());

JButton b8 = new JButton("8"); obj.setLayout(new

JButton b9 = new JButton("9"); FlowLayout(FlowLayout.CENTER));

JButton b10 = new JButton("10"); obj.setSize(300, 300);


obj.setVisible(true);
} }
Java GridLayout OF CONTAINER:

AWT Layout Manager Classes:


GridLayout:
The GridLayout manages the components in form of a rectangular grid.
Creates a grid layout with the specified number of rows and columns.
GridLayout grid=new GridLayout(3,3,10,10);
Row=3
Columns=3
Gap=10.pixel,
Java Grid layout OF CONTAINER:

Grid layout: frameObj.add(btn1); frameObj.add(btn2);


import java.awt.*;
frameObj.add(btn3);
import javax.swing.*;
frameObj.add(btn4); frameObj.add(btn5);
public class BORDERLAYOUTT {
frameObj.add(btn6);
public static void main(String argvs[])
frameObj.add(btn7); frameObj.add(btn8);
{ JFrame frameObj = new JFrame();
JButton btn1 = new JButton("1");
frameObj.add(btn9);

JButton btn2 = new JButton("2");


JButton btn3 = new JButton("3"); frameObj.setLayout(new GridLayout());
JButton btn4 = new JButton("4"); frameObj.setSize(300, 300);
JButton btn5 = new JButton("5"); frameObj.setVisible(true);
JButton btn6 = new JButton("6"); } }
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
Java AWT Layout OF CONTAINER:
AWT Layout Manager Classes:
CardLayout
The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.
Java CARD_LAYOUT OF CONTAINER:
import java.awt.*;
import javax.swing.*;
btn1.addActionListener(this);
import java.awt.event.*;
btn2.addActionListener(this);

public class CARD_LAYOUT extends JFrame implements btn3.addActionListener(this);


ActionListener cPane.add("a", btn1); // first card is the button btn1
{ cPane.add("b", btn2); // first card is the button btn2
CardLayout n; cPane.add("c", btn3); // first card is the button btn3
JButton btn1, btn2, btn3; }
Container cPane;
public void actionPerformed(ActionEvent e)
CARD_LAYOUT()
{ n.next(cPane); }
{ cPane = getContentPane();
public static void main(String args[])
n = new CardLayout();
{ CARD_LAYOUT crdl = new CARD_LAYOUT();
cPane.setLayout(n);
crdl.setSize(300, 300);
btn1 = new JButton("Apple");
btn2 = new JButton("Boy"); crdl.setVisible(true);

btn3 = new JButton("Cat"); crdl.setDefaultCloseOperation(EXIT_ON_CLOSE); } }


Java Swing-Java JRadioButton Example
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1); bg.add(r2);
f.add(r1); f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public static void main(String[] args) {
new RadioButtonExample(); } }
Application Conversion to Applets:
Event and Listener (Java Event Handling):
Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event
handling.
Java Event classes and Listener interfaces:
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and


MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener
Java Event classes and Listener interfaces:
Java Event classes and Listener interfaces:

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

Steps to perform Event Handling


 Register the component with the Listener
Java Event classes and Listener interfaces:
Registration Methods
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Java CARD_LAYOUT OF CONTAINER:
import java.awt.*;
import javax.swing.*;
btn1.addActionListener(this);
import java.awt.event.*;
btn2.addActionListener(this);

public class CARD_LAYOUT extends JFrame implements btn3.addActionListener(this);


ActionListener cPane.add("a", btn1); // first card is the button btn1
{ cPane.add("b", btn2); // first card is the button btn2
CardLayout n; cPane.add("c", btn3); // first card is the button btn3
JButton btn1, btn2, btn3; }
Container cPane;
public void actionPerformed(ActionEvent e)
CARD_LAYOUT()
{ n.next(cPane); }
{ cPane = getContentPane();
public static void main(String args[])
n = new CardLayout();
{ CARD_LAYOUT crdl = new CARD_LAYOUT();
cPane.setLayout(n);
crdl.setSize(300, 300);
btn1 = new JButton("Apple");
btn2 = new JButton("Boy"); crdl.setVisible(true);

btn3 = new JButton("Cat"); crdl.setDefaultCloseOperation(EXIT_ON_CLOSE); } }

You might also like