Advance+Java+5th+Semester
Advance+Java+5th+Semester
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?
Technology is the application of scientific knowledge to the practical aims of human life, e.g.
online communication, data transaction …
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
Main.java
Create a class named "Main" with a variable x:
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 constructor:
public class Main // Create a Main class {
int x; // Create a class attribute
public Main() // Create a class constructor for the Main class {
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?
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
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.
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
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
value
scan.close();
} }
Finding errors and exceptions in programs:
{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
What is the concept of Serialization in Java?
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{}
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name); //printing the data of the serialized object
} catch(Exception e){System.out.println(e);}
}
}
Output:
211 ravi
What is the concept of Serialization in Java?
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
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.
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.
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
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5 Steps to connect to the Database
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
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.
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
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
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 {}
More than one program are running concurrently, e.g. unix, windows
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.
System.out.println ("Second thread went for 10 seconds sleep " ); Second thread is suspended itself
A graphical user interface (GUI) is an interface through the use of icons, menus and other visual
GUI by a pointing device such as a mouse, trackball, stylus/Graph, or by a finger on a touch screen.
Canvas is not hierarchy part of applet or Frame windows, canvas encapsulates a blank window, which can be
drawn upon.
Types of containers:
Java applets are used to provide interactive features to web applications and can be executed
Method Description
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.
3. Label(String text, int It constructs a label with the specified string and
alignement) the specified alignment.
Java AWT
Label Class Methods Specified:
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.
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.
2. TextField(String text) It constructs a new text field initialized with the given string
text to be displayed.
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
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");
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:
s.setBounds(100,50,100,50);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }}
Java AWT USER PASSWORD: Example:
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
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.
}
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
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:
ActionEvent ActionListener
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