SlideShare ist ein Scribd-Unternehmen logo
1 von 30
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 !!!

Weitere ähnliche Inhalte

Was ist angesagt?

Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)Prof. Erwin Globio
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Java introduction
Java introductionJava introduction
Java introductionSagar Verma
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaEdureka!
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101kankemwa Ishaku
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 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+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 

Was ist angesagt? (20)

Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
Java basic
Java basicJava basic
Java basic
 
Core Java
Core JavaCore Java
Core Java
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Core java
Core java Core java
Core java
 
Java training in delhi
Java training in delhiJava training in delhi
Java training in delhi
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java introduction
Java introductionJava introduction
Java introduction
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 

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

Ähnlich wie 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_iiBasic java part_ii
Basic java part_ii
 
Java programming and security
Java programming and securityJava programming and security
Java programming and security
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Java solution
Java solutionJava solution
Java solution
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
 
JAVA for Every one
JAVA for Every oneJAVA for Every one
JAVA for Every one
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdf
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java review00
Java review00Java review00
Java review00
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)Java programming basics notes for beginners(java programming tutorials)
Java programming basics notes for beginners(java programming tutorials)
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Javanotes ww8
Javanotes ww8Javanotes ww8
Javanotes ww8
 

Mehr von Sagar Verma

Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...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 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar 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...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 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introductionSagar Verma
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project listSagar Verma
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project listSagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_pptSagar Verma
 

Mehr von Sagar Verma (8)

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

Kürzlich hochgeladen

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 

Kürzlich hochgeladen (20)

Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 

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 !!!