UNIT 3
UNIT 3
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.
It causes the currently executing thread object to pause and allow other threads to execute
12) static void yield()
temporarily.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
19) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static boolean interrupted() It tests whether the current thread has been interrupted.
22) static int activeCount() It returns the number of active threads in the current thread's thread group.
23) void checkAccess() It determines if the currently running thread has permission to modify the thread.
24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object.
25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error stream.
26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements representing the stack dump of the thread.
27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the specified array.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread belongs
It is used to return a string representation of this thread, including the thread's name, priority, and
30) String toString()
thread group.
31) void notify() It is used to give the notification for only one thread which is waiting for a particular object.
32) void notifyAll() It is used to give the notification to all waiting threads of a particular object.
33) void setContextClassLoa It sets the context ClassLoader for the Thread.
der()
34) ClassLoader getContextClassLoa It returns the context ClassLoader for the thread.
static der()
35) Thread.UncaughtExce getDefaultUncaugh It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
ptionHandler tExceptionHandler(
)
36) static void setDefaultUncaugh It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.
tExceptionHandler(
)
Life cycle of a Thread (Thread States)
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
1. public static final Thread.State NEW : It represents the first state of a thread that is the NEW state.
2. public static final Thread.State RUNNABLE : It represents the runnable state.It means a thread is waiting in the queue to run.
3. public static final Thread.State BLOCKED : It represents the blocked state. In this state, the thread is waiting to acquire a lock.
4. public static final Thread.State WAITING: It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to
complete its task.
5. public static final Thread.State TIMED_WAITING: It represents the timed waiting state. The main difference between waiting
and timed waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A
thread invoking the following method reaches the timed waiting state.
sleep
join with timeout
wait with timeout
parkUntil
parkNanos
6. public static final Thread.State TERMINATED: It represents the final state of a thread that is terminated or dead. A terminated
thread means it has completed its execution.
Java Threads | How to create a thread in Java
1. Thread class
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class
and implements Runnable interface.
t1.start();
}
}
Output:
thread is running...
Declarative Programming Paradigm
Java Database Connectivity (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. There are four types of JDBC drivers:
JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
• We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we
can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC)
provided by Microsoft.
A list of popular interfaces of JDBC API are given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement
is responsible to execute queries with the database.
Syntax
public Statement createStatement()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.
Syntax
public ResultSet executeQuery(String sql)throws SQLException
Syntax
public void close()throws SQLException
Example
con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to follow 5 following steps.
• In this example we are using MySql as the database. So we need to know following informations for the mysql
database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo
where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we
may also use IP address, 3306 is the port number and sonoo is the database name. We may use any
database, in such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
• Let's first create a table in the mysql database, but before creating table, we need to create database first.
create database sonoo;
use sonoo;
create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql database
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
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);}
}
}
To connect java application with the mysql database, mysqlconnector.jar file is required to be loaded.
Two ways to load the jar file:
1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath
1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath
There are two ways to set the classpath:
• temporary
• Permanent
How to set the temporary classpath
open command prompt and write:
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.;
as C:\folder\mysql-connector-java-5.0.8-bin.jar
Graphical User Interface Based Programming Paradigm:
Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.
Advantage of Applet
• 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.
Hierarchy of Applet
• As displayed in the diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component
class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It
provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.
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. It provides Graphics class object
that can be used for drawing oval, rectangle, arc etc.
Java Plug-in software is responsible to manage the life cycle of an applet.
How to run an Applet?
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet
code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150); } }
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for
testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150); } }
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
public abstract void drawString(String str, int x, int y): is used to draw the specified string.
public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified
width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and
height.
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified
width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
Example of Graphics in applet:
import java.applet.Applet;
import java.awt.*;
myapplet.html
public class GraphicsDemo extends Applet{ <html>
public void paint(Graphics g){ <body>
g.setColor(Color.red); <applet code="GraphicsDemo.cla
g.drawString("Welcome",50, 50); ss" width="300" height="300">
g.drawLine(20,30,20,300); </applet>
</body>
g.drawRect(70,100,30,30);
</html>
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
} }
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose image is required to be displayed. The
java.awt.Graphics class provide a method drawImage() to display the image.
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg"); }
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this); } }
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is
required to be moved.
myapplet.html
Example of animation in applet: <html>
<body>
import java.awt.*;
<applet code="DisplayImage.class" width="300"
import java.applet.*; height="300">
public class AnimationExample extends Applet { </applet>
Image picture; </body>
public void init() { </html>
picture =getImage(getDocumentBase(),"bike_1.gif"); }
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){} } } }
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple example of event
handling in applet that prints a message by click on the button.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox,
JMenu, JColorChooser etc.
4 AWT provides less components than Swing. Swing provides more powerful components such as
tables, lists, scrollpanes, colorchooser, tabbedpane
etc.
5 AWT doesn't follows MVC(Model View Controller) where model Swing follows MVC.
represents data, view represents presentation and controller acts as an
interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside
the main() method.
FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Model View Controller
The Model-View-Controller (MVC) is a well-known design pattern in the web development field. It is way to
organize our code. It specifies that a program or application shall consist of data model, presentation
information and control information. The MVC pattern needs all these components to be separated as different
objects.
The model designs based on the MVC architecture follow MVC design pattern. The application logic is
separated from the user interface while designing the software using model designs.