SlideShare a Scribd company logo
Java Class 6
“Don't worry if it doesn't work right [when coding]. If
everything did, you'd be out of a job.”
Agenda
•Threads in Java
•Applets
•Swing GUI
•JDBC
•Access Modifiers in Java
Java Values 2
What is a Thread?
•A thread is a lightweight sub-process, the smallest unit of
processing.
•Multiprocessing and multithreading, both are used to achieve
multitasking.
•Represents a separate path of execution of a group of
statements
•Java is the first language to include threading within the
language, rather than treating it as a facility of the OS
•Video Game example
1.one thread for graphics
2.one thread for user interaction
3.one thread for networking
•Server Example
1.Do various jobs
2.Handle Several Clients
Advantage:
1. Easier
2. better Performance
3. Multiple task
4.Share Resource
Java Values 3
Main Thread
Default Thread in any Java Program
JVM uses to execute program statements
 Program To Find the Main Thread
Class Current
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
System.out.println(“Name is: “+t.getName());
}
}
Output??
Threads in Java
Java Values 4
•Creating threads in Java:
1. Extend java.lang.Thread class
run() method must be overridden (similar to main method
of sequential program)
•run() is called when execution of the thread begins
•A thread terminates when run() returns
•start() method invokes run()
2. Implement java.lang.Runnable interface
Methods : run() , Start (), Sleep(), Wait (), Join(), getPriority()
, setPriority(), notify(), notifyall(),yield(),getname(), getid(),
isAlive(), currentthread(), isDaemon(),setDaemon() etc….
Life cycle of a Thread
Java Values 5
New
The thread is in new state if you create an instance of Thread
class but before the invocation of start() method.
Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the
running thread.
Running
The thread is in running state if the thread scheduler has
selected it
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently
not eligible to run.
Terminated
A thread is in terminated or dead state when its run() method
exits. Java Values 6
Thread Priority
Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5).
You can reset the priority using setPriority (int priority).
Some constants for priorities include:
o Thread.MIN_PRIORITY (1)
o Thread.MAX_PRIORITY (10)
Daemon thread in java is a service provider thread that
provides services to the user thread. Its life depend on the
mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.
There are many java daemon threads running automatically
e.g. gc, finalizer etc.
setDaemon(); isDaemon() is a method used for daemon thread.
Java Values 7
Thread Synchronization
Java Values 8
•A shared resource may be corrupted if it is accessed
simultaneously by multiple threads.
•Example: two unsynchronized threads accessing the same
bank account may cause conflict.
• Known as a race condition in multithreaded programs.
•A thread-safe class does not cause a race condition in the
presence of multiple threads.
•Problem : race conditions
•Solution : give exclusive access to one thread at a time to code
that manipulates a shared object.
•It keeps other threads waiting until the object is available.
•The synchronized keyword synchronizes the method so that only
one thread can access the method at a time.
public synchronized void xMethod() {
// method body
}
obj
T1 (enter inside obj)
T2 (wait till T1 finish)
Deadlock
 Apart of multithreading
 Can occur when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is
acquired by first thread
 Since, both threads are waiting for each other to release the lock, the
condition is called deadlock
 Preventing Deadlock
 Deadlock can be easily avoided by resource ordering.
 With this technique, assign an order on all the objects whose locks must be
acquired and ensure that the locks are acquired in that order.
 Example:
Thread 1: lock A lock B
Thread 2: wait for A lock C(when A is locked)
Thread 3: wait for A wait for B wait for C
Java Values 9
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each other.
It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
Java Values 10
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or
notifyAll() methods
after the specified amount of time, sleep
is completed.
Applets
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.
Java Values 11
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.
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.
Lifecycle of Java Applet
Java values
How to run an Applet?
 There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).
 Html file Example:
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Java Values 13
Output?
Swing GUI
What is Java Swing ?
• Part of the Java Foundation Classes (JFC)
• Provides a rich set of GUI components.
• Used to create a Java program with a graphical user
interface (GUI)
Features Of Swing
1) Java Look and Feel
2) Data Transfer
3) Internationalization and Localization
4) Accessibility
5) System Tray Icon Support
Java Values 14
Java Swing Components…
• Top Level Containers
• General Purpose Containers
• Special Purpose Containers
• Basic Controls
• Un-editable Information Displays
• Interactive Displays of Highly Formatted Information
Java Values 15
Top Level Containers
• Window
-Dialog
-Frame
Special Purpose Containers
• Internal Frame
• Layered Pane
• Root Pane
Java Values 16
Basic Controls
• Buttons
• Combo Box
• List
• Menu
Java Values 17
Uneditable Information Displays
• Label
• Progress Bar
Java Values 18
Interactive Displays of
Highly Formatted
Information
Java Values 19
Java Layout Management...
1) BorderLayout
2) FlowLayout
3) GridBagLayout
4) GridLayout
Java Events Handling…
button Action listener
ActionEvent
•Types of Event Listeners
1) ActionListener
2) WindowListener
3) MouseListener
4) MouseMotionListener
5) ComponentListener
Implementing an Event Handler
• Implement the methods in the listener interface to
handle the event.
Conclusion
• You can use any helpful tools out there that are for
Java development like eclipse IDE, NetBeans IDE.
We will see all the swing component Examples while
doing Desktop application using Netbeans IDE.
Java Values 20
JDBC
Java Values 21
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.
Four types of JDBC drivers
1. JDBC-ODBC Bridge Driver,
2. Native Driver,
3. Network Protocol Driver, and
4. Thin Driver
Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and
execute the query with the database.
But, 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).
We can use JDBC API to handle database using Java program
and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Java Values 22
Java Database Connectivity with 5 Steps
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Statement interface
Java Values 24
1) public ResultSet executeQuery(String sql): is used to execute
SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute
specified query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries
that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of
commands.
•The Statement interface provides methods to execute
queries with the database.
•The statement interface is a factory of ResultSet i.e. it
provides factory method to get the object of ResultSet.
•Commonly used methods of Statement interface:
Java Values 25
JDBC RowSet
•The instance of RowSet is the java bean component
because it has properties and java bean notification
mechanism.
•It is introduced since JDK 5.
•It is the wrapper of ResultSet.
•It holds tabular data like ResultSet but it is easy and
flexible to use.
Advantage of RowSet
The advantages of using RowSet are
given below:
•It is easy and flexible to use
•It is Scrollable and Updatable by
default
Java Values 26
Statement PreparedStatement CallableStatement
It is used to execute normal
SQL queries.
It is used to execute
parameterized or dynamic
SQL queries.
It is used to call the stored
procedures.
It is preferred when a
particular SQL query is to
be executed only once.
It is preferred when a
particular query is to be
executed multiple times.
It is preferred when the
stored procedures are to be
executed.
You cannot pass the
parameters to SQL query
using this interface.
You can pass the
parameters to SQL query at
run time using this interface.
You can pass 3 types of
parameters using this
interface. They are – IN,
OUT and IN OUT.
This interface is mainly
used for DDL statements
like CREATE, ALTER,
DROP etc.
It is used for any
kind of SQL queries which
are to be executed multiple
times.
It is used to execute stored
procedures and functions.
The performance of this
interface is very low.
The performance of this
interface is better than the
Statement interface (when
used for multiple execution
of same query).
The performance of this
interface is high
Access Modifiers in Java
The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class.
We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
 Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
 Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not
specify any access level, it will be the default.
 Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the package.
 Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package
and outside the package.
Java Values 27
Access Modifiers in Java
There are many non-access modifiers, such as
static, abstract, synchronized, native, volatile, transient, etc.
A class cannot be private or protected except nested class.
Java Values 28
Access
Modifier
within class within
package
outside
package by
subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Summary
Threads in Java
Process , Thread , Lifecycle of thread, Multithread,
communication between thread, Synchronization, priority
Daemon thread etc
Applets
what is applet, life cycle , and example and uses.
Swing GUI
Component, events, used and advantage
JDBC
Introduction, features,Drivers,Writing JDBC code to connect to DB,CRUD
Operations, Statement types ,Rowset, ResultSet
Access Modifiers in Java
Java Values 29
Java Values 30
Thank you !!!
GitHub Repository : https://github.com/eewsagar
YouTube: https://youtu.be/TBpu4Tlu7Q8
For any question please feel free to
comment.
Never
Assume
Clear it !!!

More Related Content

What's hot (20)

Core java lessons
Core java lessons
vivek shah
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
Prof. Erwin Globio
 
Java basic
Java basic
Arati Gadgil
 
Core Java
Core Java
Priyanka Pradhan
 
Core Java Tutorial
Core Java Tutorial
eMexo Technologies
 
Presentation on java
Presentation on java
shashi shekhar
 
Java - OOPS and Java Basics
Java - OOPS and Java Basics
Victer Paul
 
Core java
Core java
Ravi varma
 
Java training in delhi
Java training in delhi
APSMIND TECHNOLOGY PVT LTD.
 
Basic Java Programming
Basic Java Programming
Math-Circle
 
Java introduction
Java introduction
Sagar Verma
 
Basics of Java
Basics of Java
Sherihan Anver
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Introduction to java 101
Introduction to java 101
kankemwa Ishaku
 
Core java notes with examples
Core java notes with examples
bindur87
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
iimjobs and hirist
 
Object+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
Java Tutorial
Java Tutorial
Singsys Pte Ltd
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Core java lessons
Core java lessons
vivek shah
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
Prof. Erwin Globio
 
Java - OOPS and Java Basics
Java - OOPS and Java Basics
Victer Paul
 
Basic Java Programming
Basic Java Programming
Math-Circle
 
Java introduction
Java introduction
Sagar Verma
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
Java interview questions 1
Java interview questions 1
Sherihan Anver
 
Introduction to java 101
Introduction to java 101
kankemwa Ishaku
 
Core java notes with examples
Core java notes with examples
bindur87
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
iimjobs and hirist
 
Object+oriented+programming+in+java
Object+oriented+programming+in+java
Ye Win
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 

Similar to Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Access Modifiers in Java | Java Program (20)

Basic java part_ii
Basic java part_ii
Khaled AlGhazaly
 
Advance java prasentation
Advance java prasentation
dhananajay95
 
J threads-pdf
J threads-pdf
Venketesh Babu
 
Thread.pptx
Thread.pptx
Karthik Rohan
 
Thread.pptx
Thread.pptx
Karthik Rohan
 
Thread.pptx
Thread.pptx
Karthik Rohan
 
Java Threading
Java Threading
Guillermo Schwarz
 
JAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
JAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
Java Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
suthi
 
Thread model of java
Thread model of java
myrajendra
 
advanced java ppt
advanced java ppt
PreetiDixit22
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
Java1
Java1
computertuitions
 
Java
Java
computertuitions
 
Java solution
Java solution
1Arun_Pandey
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Introduction to Java
Introduction to Java
Namit Khanduja
 
Java ppts unit1
Java ppts unit1
Priya11Tcs
 
Advance java prasentation
Advance java prasentation
dhananajay95
 
JAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
JAVA INTRODUCTION
JAVA INTRODUCTION
Prof Ansari
 
Java Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
suthi
 
Thread model of java
Thread model of java
myrajendra
 
Module 4 - Part 4 - Multithreaded Programming.pptx
Module 4 - Part 4 - Multithreaded Programming.pptx
FahmaFamzin
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Java ppts unit1
Java ppts unit1
Priya11Tcs
 
Ad

More from Sagar Verma (8)

Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Springboot introduction
Springboot introduction
Sagar Verma
 
2015-16 software project list
2015-16 software project list
Sagar Verma
 
Ns2 new project list
Ns2 new project list
Sagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_ppt
Sagar Verma
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
Springboot introduction
Springboot introduction
Sagar Verma
 
2015-16 software project list
2015-16 software project list
Sagar Verma
 
Ns2 new project list
Ns2 new project list
Sagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_ppt
Sagar Verma
 
Ad

Recently uploaded (20)

New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Webinar On Steel Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
MODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational Autoencoder
DivyaMeenaS
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Webinar On Steel Melting IIF of steel for rdso
Webinar On Steel Melting IIF of steel for rdso
KapilParyani3
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
International Journal of Advance Robotics & Expert Systems (JARES)
International Journal of Advance Robotics & Expert Systems (JARES)
jaresjournal868
 
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
May 2025 - Top 10 Read Articles in Artificial Intelligence and Applications (...
gerogepatton
 
MODULE 6 - 1 VAE - Variational Autoencoder
MODULE 6 - 1 VAE - Variational Autoencoder
DivyaMeenaS
 
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Numerical Investigation of the Aerodynamic Characteristics for a Darrieus H-t...
Mohamed905031
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Software Engineering Project Presentation Tanisha Tasnuva
Software Engineering Project Presentation Tanisha Tasnuva
tanishatasnuva76
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 

Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Access Modifiers in Java | Java Program

  • 1. Java Class 6 “Don't worry if it doesn't work right [when coding]. If everything did, you'd be out of a job.” Agenda •Threads in Java •Applets •Swing GUI •JDBC •Access Modifiers in Java
  • 2. Java Values 2 What is a Thread? •A thread is a lightweight sub-process, the smallest unit of processing. •Multiprocessing and multithreading, both are used to achieve multitasking. •Represents a separate path of execution of a group of statements •Java is the first language to include threading within the language, rather than treating it as a facility of the OS •Video Game example 1.one thread for graphics 2.one thread for user interaction 3.one thread for networking •Server Example 1.Do various jobs 2.Handle Several Clients Advantage: 1. Easier 2. better Performance 3. Multiple task 4.Share Resource
  • 3. Java Values 3 Main Thread Default Thread in any Java Program JVM uses to execute program statements  Program To Find the Main Thread Class Current { public static void main(String args[]) { Thread t=Thread.currentThread(); System.out.println(“Current Thread: “+t); System.out.println(“Name is: “+t.getName()); } } Output??
  • 4. Threads in Java Java Values 4 •Creating threads in Java: 1. Extend java.lang.Thread class run() method must be overridden (similar to main method of sequential program) •run() is called when execution of the thread begins •A thread terminates when run() returns •start() method invokes run() 2. Implement java.lang.Runnable interface Methods : run() , Start (), Sleep(), Wait (), Join(), getPriority() , setPriority(), notify(), notifyall(),yield(),getname(), getid(), isAlive(), currentthread(), isDaemon(),setDaemon() etc….
  • 5. Life cycle of a Thread Java Values 5
  • 6. New The thread is in new state if you create an instance of Thread class but before the invocation of start() method. Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. Running The thread is in running state if the thread scheduler has selected it Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run. Terminated A thread is in terminated or dead state when its run() method exits. Java Values 6
  • 7. Thread Priority Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5). You can reset the priority using setPriority (int priority). Some constants for priorities include: o Thread.MIN_PRIORITY (1) o Thread.MAX_PRIORITY (10) Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc. setDaemon(); isDaemon() is a method used for daemon thread. Java Values 7
  • 8. Thread Synchronization Java Values 8 •A shared resource may be corrupted if it is accessed simultaneously by multiple threads. •Example: two unsynchronized threads accessing the same bank account may cause conflict. • Known as a race condition in multithreaded programs. •A thread-safe class does not cause a race condition in the presence of multiple threads. •Problem : race conditions •Solution : give exclusive access to one thread at a time to code that manipulates a shared object. •It keeps other threads waiting until the object is available. •The synchronized keyword synchronizes the method so that only one thread can access the method at a time. public synchronized void xMethod() { // method body } obj T1 (enter inside obj) T2 (wait till T1 finish)
  • 9. Deadlock  Apart of multithreading  Can occur when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread  Since, both threads are waiting for each other to release the lock, the condition is called deadlock  Preventing Deadlock  Deadlock can be easily avoided by resource ordering.  With this technique, assign an order on all the objects whose locks must be acquired and ensure that the locks are acquired in that order.  Example: Thread 1: lock A lock B Thread 2: wait for A lock C(when A is locked) Thread 3: wait for A wait for B wait for C Java Values 9
  • 10. Inter-thread communication in Java Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. It is implemented by following methods of Object class: wait() notify() notifyAll() Java Values 10 wait() sleep() wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class is the non-static method is the static method is the non-static method is the static method should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.
  • 11. Applets 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. Java Values 11
  • 12. 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. 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. Lifecycle of Java Applet Java values
  • 13. How to run an Applet?  There are two ways to run an applet  By html file.  By appletViewer tool (for testing purpose).  Html file Example: import java.applet.Applet; import java.awt.Graphics; public class First extends Applet{ public void paint(Graphics g){ g.drawString("welcome",150,150); } } <html> <body> <applet code="First.class" width="300" height="300"> </applet> </body> </html> Java Values 13 Output?
  • 14. Swing GUI What is Java Swing ? • Part of the Java Foundation Classes (JFC) • Provides a rich set of GUI components. • Used to create a Java program with a graphical user interface (GUI) Features Of Swing 1) Java Look and Feel 2) Data Transfer 3) Internationalization and Localization 4) Accessibility 5) System Tray Icon Support Java Values 14
  • 15. Java Swing Components… • Top Level Containers • General Purpose Containers • Special Purpose Containers • Basic Controls • Un-editable Information Displays • Interactive Displays of Highly Formatted Information Java Values 15
  • 16. Top Level Containers • Window -Dialog -Frame Special Purpose Containers • Internal Frame • Layered Pane • Root Pane Java Values 16
  • 17. Basic Controls • Buttons • Combo Box • List • Menu Java Values 17
  • 18. Uneditable Information Displays • Label • Progress Bar Java Values 18 Interactive Displays of Highly Formatted Information
  • 19. Java Values 19 Java Layout Management... 1) BorderLayout 2) FlowLayout 3) GridBagLayout 4) GridLayout Java Events Handling… button Action listener ActionEvent •Types of Event Listeners 1) ActionListener 2) WindowListener 3) MouseListener 4) MouseMotionListener 5) ComponentListener
  • 20. Implementing an Event Handler • Implement the methods in the listener interface to handle the event. Conclusion • You can use any helpful tools out there that are for Java development like eclipse IDE, NetBeans IDE. We will see all the swing component Examples while doing Desktop application using Netbeans IDE. Java Values 20
  • 21. JDBC Java Values 21 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. Four types of JDBC drivers 1. JDBC-ODBC Bridge Driver, 2. Native Driver, 3. Network Protocol Driver, and 4. Thin Driver
  • 22. Why Should We Use JDBC Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, 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). We can use JDBC API to handle database using Java program and can perform the following activities: 1. Connect to the database 2. Execute queries and update statements to the database 3. Retrieve the result received from the database. Java Values 22
  • 23. Java Database Connectivity with 5 Steps import java.sql.*; class OracleCon{ public static void main(String args[]){ try{ //step1 load the driver class Class.forName("com.mysql.jdbc.Driver"); //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","root","root"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //step5 close the connection object con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 24. Statement interface Java Values 24 1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. 3) public boolean execute(String sql): is used to execute queries that may return multiple results. 4) public int[] executeBatch(): is used to execute batch of commands. •The Statement interface provides methods to execute queries with the database. •The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet. •Commonly used methods of Statement interface:
  • 25. Java Values 25 JDBC RowSet •The instance of RowSet is the java bean component because it has properties and java bean notification mechanism. •It is introduced since JDK 5. •It is the wrapper of ResultSet. •It holds tabular data like ResultSet but it is easy and flexible to use. Advantage of RowSet The advantages of using RowSet are given below: •It is easy and flexible to use •It is Scrollable and Updatable by default
  • 26. Java Values 26 Statement PreparedStatement CallableStatement It is used to execute normal SQL queries. It is used to execute parameterized or dynamic SQL queries. It is used to call the stored procedures. It is preferred when a particular SQL query is to be executed only once. It is preferred when a particular query is to be executed multiple times. It is preferred when the stored procedures are to be executed. You cannot pass the parameters to SQL query using this interface. You can pass the parameters to SQL query at run time using this interface. You can pass 3 types of parameters using this interface. They are – IN, OUT and IN OUT. This interface is mainly used for DDL statements like CREATE, ALTER, DROP etc. It is used for any kind of SQL queries which are to be executed multiple times. It is used to execute stored procedures and functions. The performance of this interface is very low. The performance of this interface is better than the Statement interface (when used for multiple execution of same query). The performance of this interface is high
  • 27. Access Modifiers in Java The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.  Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.  Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.  Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.  Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. Java Values 27
  • 28. Access Modifiers in Java There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. A class cannot be private or protected except nested class. Java Values 28 Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y
  • 29. Summary Threads in Java Process , Thread , Lifecycle of thread, Multithread, communication between thread, Synchronization, priority Daemon thread etc Applets what is applet, life cycle , and example and uses. Swing GUI Component, events, used and advantage JDBC Introduction, features,Drivers,Writing JDBC code to connect to DB,CRUD Operations, Statement types ,Rowset, ResultSet Access Modifiers in Java Java Values 29
  • 30. Java Values 30 Thank you !!! GitHub Repository : https://github.com/eewsagar YouTube: https://youtu.be/TBpu4Tlu7Q8 For any question please feel free to comment. Never Assume Clear it !!!