KEMBAR78
advanced java programming paradigms presentation | PPTX
Unit-3 - Advanced Java Programming Paradigms
Concurrent Programming Paradigm
• Computing systems model the world, and the world contains actors that execute
independently of, but communicate with, each other. In modelling the world, many
(possibly) parallel executions have to be composed and coordinated, and that's where the
study of concurrency comes in.
• There are two common models for concurrent programming: shared memory and message
passing.
• Shared memory. In the shared memory model of concurrency, concurrent modules
interact by reading and writing shared objects in memory.
• Message passing. In the message-passing model, concurrent modules interact by
sending messages to each other through a communication channel. Modules send off
messages, and incoming messages to each module are queued up for handling
3
A Multi threaded program
Multithreaded Programming
• Java provides built-in support for multithreaded programming.
• A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
• There are two distinct types of multitasking: process-based and thread-
based.
• It is important to understand the difference between the two.
Process-based multitasking
• Process-based multitasking is the more familiar form.
• A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows
your computer to run two or more programs concurrently.
• For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a
text editor.
• In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
Thread-based multitasking
• Thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a
single program can perform two or more tasks simultaneously.
• For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being
performed by two separate threads.
• Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the details.
Lifecycle of a thread -Thread States
Thread Control Methods
Creation of a Java Thread
In Java we can implement the thread programs using two approaches -
o Using Thread class
o sing runnable interface
Thread Class and the Runnable Interface
• Java’s multithreading system is built upon the Thread class, its methods, and its companion interface,
Runnable. Thread encapsulates a thread of execution.
• The Thread class defines several methods that help manage threads.
How to start a thread in Java
how to create a single thread by extending Thread Class.
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread is created!!!");
}
}
class ThreadProg
{
public static void main(String args[])
{
MyThread t=new MyThread();
t.start();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a runnable.");
}
}
1. Create the instance of class MyClass.
2. This instance is passed as a parameter to Thread class.
3. Using the instance of class Thread invoke the start
method.
4. The start method in-turn calls the run method written
in MyClass.
Create a thread by extending the Thread Class. Also make use of constructor and display message "You are
Welcome to Thread Programming".
class MyThread extends Thread
{
String str=""; //data member of class MyThread
MyThread(String s)//constructor
{
this.str=s;
}
public void run()
{
System.out.println(str);
}
}
class ThreadProg
{
public static void main(String args[])
{
MyThread t=new MyThread("You are Welcome to Thread Programming");
t.start();
}
}
Implementing Runnable Interface
The thread can also be created using Runnable interface.
 Implementing thread program using Runnable interface is
preferable than implementing it by extending the thread class
because of the following two reasons -
1. If a class extends a thread class then it can not extends any other
class which may be required to extend.
2. If a class thread is extended then all its functionalities get
inherited.
This is an expensive operation.
class MyThread implements Runnable
{
public void run()
{
System.out.println("Thread is created!");
}
}
class ThreadProgRunn
{
public static void main(String args[])
{
MyThread obj=new MyThread();
Thread t=new Thread(obj);
t.start();
}
}
Write a Java program that prints the numbers from 1 to 10 line by line
after every 10 seconds.
class NumPrint extends Thread
{
int num;
NumPrint()
{
start();//directs to the run method
}
public void run()//thread execution starts
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
Thread.sleep(10000);
}
}
}
public class MultiThNum
{
public static void main(String args[])
{
NumPrint t1;
t1=new NumPrint();
}
}
Creating Multiple Threads
class A extends Thread //class A implements Runnable
{
public void run()
{
for(int i=0;i<=5;i++)//printing 0 to 5
{
System.out.println(i);
} }}
class B extends Thread //class B implements Runnable
{
public void run()
{
for(int i=10;i>=5;i--)//printing 10 to 5
{
System.out.println(i);
} }}
The multiple threads can be created both by extending Thread class and by implementing the
Runnable interface.
class ThreadProg
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
t1.start();
t2.start();
}
}
// Runnable interface
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
Write a Java application program for generating four threads to perform the
following operations - i) Getting N numbers as input ii) Printing the numbers divisible
by five iii) Printing prime numbers iv) Computing the average.
import java.io.*;
import java.util.*;
class FirstThread extends Thread
{
public void run() //generating N numbers
{
int i;
System.out.println("nGenerating Numbers:
");
for (i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
class SecondThread extends Thread
{
public void run() //Displaying the numbers
divisible by five
{
int i;
System.out.println("nDivisible by Five: ");
for (i=1;i<=10;i++) //10 can be replaced by any
desired value
{
if (i%5==0)
System.out.println(i);
}
}
}
class ThirdThread extends Thread
{
public void run() //generating the prime
numbers
{
int i;
System.out.println("nPrime Numbers: ");
for (i=1;i<=10;i++) //10 can be replaced by
any desired value
{
int j;
for (j=2; j<i; j++)
{
int n = i%j;
if (n==0)
break;
}
if(i == j)
System.out.println(i);
} }}
class FourthThread extends Thread
{
public void run() //generating the prime numbers
{
int i,sum;
double avg;
sum=0;
System.out.println("nComputing Average: ");
for (i=1;i<=10;i++) //10 can be replaced by any
desired value
sum=sum+i;
avg=sum/(i-1);
System.out.println(avg);
}
}
class MainThread
{
public static void main(String[] args) throws IOException
{
FirstThread T1 = new FirstThread(); //creating first thread
SecondThread T2 = new SecondThread(); //creating second
thread
ThirdThread T3 = new ThirdThread(); //creating Third thread
FourthThread T4 = new FourthThread(); //creating Fourth
thread
T1.start(); //First Thread starts executing
T2.start();//Second Thread starts executing
T3.start();//Third Thread starts executing
T4.start();//Fourth Thread starts executing
}
}
Generating Numbers:
1
2
3
4
5
6
7
8
9
10
Divisible by Five:
5
10
Computing Average:
5.0
Prime Numbers:
2
3
5
7
Thread Priorities
• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form:
final void setPriority(int level)
• Here, level specifies the new priority setting for the calling thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.
• Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5. These priorities are defined as final variables within Thread.
• You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:
final int getPriority( )
1. Write a java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of cube of the number.
2. Write a java program for to solve producer consumer problem in which a producer produce
a value and consumer consume the value before producer generate the next value.
3. Write a java program in which thread sleep for 5 sec and change the name of thread.
Graphics User Interface (GUI) based Programming
• The graphics programming in Java is supported by the AWT
package.
• The AWT stands for Abstract Window Toolkit.
• The AWT contains large number of classes which help to include
various graphical components in the Java program.
• The graphical components include text box, buttons, labels,
radio buttons, list items and so on.
• These classes are arranged in hierarchical manner which is
recognized as AWT hierarchy.
GUI - AWT
• Graphical User Interface (GUI)
Java Abstract Window Toolkit (AWT) is an Application Program Interface (API) to develop GUI or window-
based application in java. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous
classes and methods that allow you to create and manage the GUI window.
• AWT is an Application programming interface (API) for creating Graphical User Interface (GUI) in Java.
• It allows Java programmers to develop window-based applications.
• AWT represents a class library to develop applications using GUI.
• AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program.
AWT components use the resources of the operating system, i.e., they are platform-dependent, which means,
component's view can be changed according to the view of the operating system. The classes for AWT are
provided by the Java.awt package for various AWT components.
• The Java.awt package contains classes and interfaces that help create graphical user interfaces and enable
more user-friendly programme interaction.
Hierarchy of AWT components
Hierarchy of components - AWT
1. Component : This is the super class of all the graphical classes from which
variety of graphical classes can be derived. It helps in displaying the
graphical object on the screen. It handles the mouse and keyboard events.
2. Container : This is a graphical component derived from the component
class. It is responsible for managing the layout and placement of graphical
components in the container.
3. Window : The top level window without border and without the menu bar
is created using the window class. It decides the layout of the window.
4. Panel : The panel class is derived from the container class. It is just
similar to window - without any border and without any menu bar, title
bar.
5. Frame : This is a top-level window with a border and menu bar. It
supports the common window events such as window open, close, activate
and deactivate.
Example
// importing Java AWT class
import java.awt.*;
public class AWTExample1 extends Frame {
AWTExample1() {
Button b = new Button("Click Me!!");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {
AWTExample1 f = new AWTExample1();
}
}
JAVA APPLETS
• A java applet is a program that appears embedded in a web document and
applet come into effect when the browser browse the web page.
• to generate the dynamic content. It runs inside the browser and works at client side.
 It is a similar kind of programs like in C,C++ and Pascal. etc., to solve a
problem.
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.
 Applets are small applications that are accessed on an Internet server,
transported over the Internet, automatically installed, and run as part of a
web document.
What are Applets in Java?
The interactive components of web applications are provided by Java applets, which can be easily run by many
different platforms' browsers. They can launch automatically when the pages are browsed and are tiny, portable Java
programmes embedded in HTML pages.
• Applet inherits awt Component class and awt Container class
Life cycle of an Applet
There are various methods which are typically used in applet for initialization and
termination purpose.
1. Initialization
2. Running state
3. Idle state
4. Dead or destroyed state
Lifecycle of an applet
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
• 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. Within the method
paint() we will call the drawString() method to print a text message in the applet
window.
Example
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
When applet begins, the AWT calls following methods in sequence -
a) init() b) start() c) paint()
When applet is terminated following methods are invoked in sequence.
a) stop() b) destroy()
Executing an Applet
There are two methods to run the applet
1. Using web browser
2. Using Appletviewer
Using web browser
Step 1 : Compile your Applet source program using javac compiler, i.e. D:test>javac FirstApplet.java
Step 2 : Write following code in Notepad/Wordpad and save it with filename and extension .html.
For example following code is saved as Exe_FirstApplet.html, The code is
<applet code="FirstApplet" width=300 height=100>
</applet>
Step 3 : Load html file with some web browser, This will cause to execute your html file
Using Appletviewer
Step 1 : To run the applet without making use of web browser or using command prompt we need to modify the
code little bit.
Step 2 :
D:test>javac FirstApplet.java
D:test>Appletviewer FirstApplet.java
Example of an Applet
Java Program[ColorDemo.java]
import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=100>
</applet>
*/
public class ColorDemo extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.cyan);
setForeground(Color.red);
g.drawString("Its a colorful Applet",50,30);
Color newColor=new Color(255,255,0);
//creating red+green=yellow color
g.setColor(newColor);
g.drawString("Its a colorful Applet",50,70);
}
Write an applet program for displaying the circle in green color.
import java.awt.*;
import java.applet.*;
/*
<applet code="CircleDemo" width=300 height=300>
</applet>
*/
public class CircleDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillOval(10,10,50,50);
}
}
Example of an applet
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
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);
}
}
<html>
<body>
<applet code="GraphicsDemo.class" width="300" heig
ht="300">
</applet>
</body>
</html>
Event Handling in applet
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListner{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
1.<html>
2.<body>
3.<applet code="EventApplet.class" width="300" height="300">
4.</applet>
5.</body>
6.</html>
Applets
Advantages of applets
• The response time is quicker because it operates on the client-side. It is secured.
• Web browsers must adhere to tight security regulations while using applets.
• It is compatible with browsers on various operating systems, including Linux, Windows, and Mac OS.
Disadvantages of applets
• The client browser requires a plugin to run the applet.
• The mobile browser on iOS or Android does not run any Java applets. Desktop browsers have dropped support for
Java applets along with the rise of mobile operating systems.
Applet features over HTML
• It displays the dynamic web pages of a web application.
• Play audio files.
• Display documents.
• Play animations.
• Swing in Java is a lightweight and
platform-independent class of the
Java foundation class. It's used to make
applications that run in windows.
• It contains elements such as a button, a scroll
bar, and a text field. A graphical user interface
is created by combining all of these
elements.
• Swing Framework includes several classes that
provide more vital and more versatile
GUI (Graphical User Interface)
components than AWT(Abstract Window
Toolkit).
• Swing is a Sun Microsystems-published official
Java GUI toolkit that closely resembles the
look and feels of modern Java GUIs. It is
used to create the graphical user
interface for Java Class.
Java SWING - Introduction
43
Platform Independent
It is platform-independent, as the swing components used to construct the program are not
platform-specific. It works on any platform and in any location.
Customizable
Swing controls are simple to customize. It can be changed, and the swing component
application's visual appearance is independent of its internal representation.
Plugging
• Java Swing has pluggable look and feel. This feature allows users to change the appearance
and feel of Swing components without having to restart the application.
• The Swing library will enable components to have the same look and feel across
all platforms, regardless of where the program is running.
• The Swing library provides an API that allows complete control over the appearance and
feel of an application's graphical user interface
Java SWING FEATURES
44
• MVC stands for Model-View-Controller.
• The model agrees with the state information associated with the Component in
MVC terminology.
• The view determines how the component appears on screen and any aspects of the
view that are influenced by the model's current state.
• The controller is in charge of determining how the component responds to the user.
Manageable Look and Feel
• It's simple to manage and configure.
• Its mechanism and composition pattern allows changes to be made to the settings while
the program runs.
• Constant changes to the application code can be made without making any changes to the
user interface.
Java SWING FEATURES(Contd.)
45
Java SWING FEATURES (Contd.)
Lightweight
• Lightweight Components: The JDK's AWT has supported lightweight component
development.
• A component must not rely on non-Java [O/s based] system classes to
be considered light.
• The look and feel classes in Java help Swing components have their view.
46
• Swing is another approach of graphical programming in Java.
• Swing creates highly interactive GUI applications.
• It is the most flexible and robust approach.
JFC and Swing
JFC stands for Java Foundation Classes, a set of classes used to create graphical user
interfaces (GUIs) and add rich graphical features and interactivity to Java
applications.
The Java Classes Foundation holds Java Swing (JFC).
47
Swing Hierarchy
JFC stands for Java Foundation
Classes, a set of classes used to
create graphical user interfaces
(GUIs) and add rich graphical
features and interactivity to Java
applications. The Java Classes
Foundation holds Java Swing
(JFC).
48
What are Swing Components in Java?
•A component is independent visual control, and Java Swing
Framework contains a large set of these components,
providing rich functionalities and allowing high customization.
•They all are derived from JComponent class. All these
components are lightweight components.
•This class offers some standard functionality like pluggable look
and feel, support for accessibility, drag and drop, layout, etc.
•A container holds a group of components.
• It delivers a space where a component can be managed and
displayed. Containers are of two types:
49
Swing Components
50
Jbutton
• JButton class to create a push button on the UI.
• The button can include some display text or images.
• It yields an event when clicked and double-clicked.
• Can implement a JButton in the application
by
calling one of its
constructors.
Syntax:
JButton okBtn = new JButton(“Click”);
Display:
Top Swing components in Java
51
JLabel
• Use JLabel class to render a read-only text label or images on the UI. It does not generate
any event.
Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);
• This constructor returns a label with specified text.
JLabel imgLabel = new JLabel(carIcon);
It returns a label with a car icon.
The JLabel Contains four constructors. They are as follows:
1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)
52
The JTextField renders an editable single-line text box. Users can input non-formatted text
in the box.
Can initialize the text field by calling its constructor and passing an optional
integer parameter.
This parameter sets the box width measured by the number of columns.
Also, it does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50); It
is the most widely used text component. It
has three constructors:
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)
Note: cols represent the number of
columns in the text field.
JTextField
53
JCheckBox
The JCheckBox renders a check-box with a label.
The check-box has two states, i.e., on and off. On selecting, the state is set to "on,"
and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);
• It returns a checkbox with the label Pepperoni pizza.
• Notice the second parameter in the constructor.
• It is a boolean value that denotes the default state of the check-box.
• True means the check-box defaults to the "on" state.
54
JRadioButton
•A radio button is a group of related buttons from which can
select only
one.
•Use JRadioButton class to create a radio button in Frames and render a
group of radio buttons in the UI.
•Users can select one choice from the group.
Syntax:
JRadioButton jrb = new JRadioButton("Easy");
Display:
55
JComboBox
• The combo box is a combination of text fields and a drop-down list
• Use JComboBox component to create a combo box in Swing.
Syntax:
JcomboBox jcb = new JComboBox(name);
JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package
javax.swing.JTextArea class. It is used for displaying multiple-line text.
Declaration:
public class JTextArea extends JTextComponent
56
Syntax:
JTextArea textArea_area=new JTextArea("Ninja! please write something in the text area.");
The JTextArea Contains four constructors. They are as follows:
1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)
Display:
57
JPasswordField
• In Java, the Swing toolkit contains a JPasswordField Class.
• It is under package javax.swing.JPasswordField class.
• It is specifically used for the password, and we can edit them.
Declaration:
public class JPasswordField extends JTextField
Syntax:
JPasswordField password = new JPasswordField();
The JPasswordFieldContains 4 constructors. They are as follows:
• JPasswordField()
• JPasswordField(int columns)
• JPasswordField(String text)
• JPasswordField(String text, int columns)
58
JTable
• In Java, the Swing toolkit contains a JTable Class.
• It is under package javax.swing.JTable class.
• It is used to draw a table to display data.
Syntax:
JTable table = new JTable(table_data, table_column);
The JTable contains two constructors. They are as follows:
1. JTable()
2. JTable(Object[][] rows, Object[] columns)
59
JList
• In Java, the Swing toolkit contains a JList Class.
• It is under package javax.swing.JList class.
• It is used to represent a list of items together.
• We can select one or more than one items from the list.
Declaration:
public class JList extends JComponent implements Scrollable,
Accessible
Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1); 60
The JListContains 3 constructors. They are as
follows: JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)
Display:
61
JOptionPane
In Java, the Swing toolkit contains a JOptionPane Class. It is under package javax.swing.JOptionPane class. It
is used for creating dialog boxes for displaying a message, confirm box, or input dialog box.
Declaration:
public class JOptionPane extends JComponent implements Accessible
Syntax:
JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");
The JOptionPaneContains 3 constructors. They are as following:
1. JOptionPane()
2. JOptionPane(Object message)
3. JOptionPane(Object message, intmessageType)
62
JScrollBar
• In Java, the Swing toolkit contains a JScrollBar class.
• It is under package javax.swing.JScrollBar class.
• It is used for adding horizontal and vertical scrollbars.
Declaration:
public class JScrollBar extends JComponent implements Adjustable,
Accessible
Syntax:
JScrollBar scrollBar = new JScrollBar();
The JScrollBarContains 3 constructors. They are as following:
1. JScrollBar()
2. JScrollBar(int orientation)
3. JScrollBar(int orientation, int value, int extent, int min_, intmax_)
63
• In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class.
• It is under package javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem
class.
• The JMenuBar class is used for displaying menubar on the frame.
• The JMenu Object is used to pull down the menu bar's components.
• The JMenuItem Object is used for adding the labeled menu item.
JMenuBar, JMenu and JMenuItem Declarations:
public class JMenuBar extends JComponent implements MenuElement,
Accessible public class JMenu extends JMenuItem implements MenuElement,
Accessible
JMenuBar, JMenu and JMenuItem
64
Syntax:
JMenuBar menu_bar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuItem1 = new JMenuItem("Never");
menuItem2 = new JMenuItem("Stop");
menuItem3 = new JMenuItem("Learing");
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
65
JPopupMenu
• In Java, the Swing toolkit contains a JPopupMenu Class.
• It is under package javax.swing.JPopupMenu class.
• It is used for creating popups dynamically on a specified position.
Declaration:
public class JPopupMenu extends JComponent implements Accessible,
MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");
The JPopupMenuContains 2 constructors. They are as follows:
1. JPopupMenu()
2. JPopupMenu(String label)
66
JCheckBoxMenuItem
• In Java, the Swing toolkit contains a JCheckBoxMenuItem Class.
• It is under package javax.swing.JCheckBoxMenuItem class.
•It is used to create a checkbox on a
menu. Syntax:
JCheckBoxMenuItem item = new
JCheckBoxMenuItem("Option_1");
The JCheckBoxMenuItem Contains 2
constructors. They are as following:
1. JCheckBoxMenuItem()
2. JCheckBoxMenuItem(Action a)
3. JCheckBoxMenuItem(Icon icon)
4. JCheckBoxMenuItem(String text)
5. JCheckBoxMenuItem(String text,
boolean b)
6. JCheckBoxMenuItem(String text, Icon 67
JSeparator
• In Java, the Swing toolkit contains a JSeparator Class.
• It is under package javax.swing.JSeparator class.
• It is used for creating a separator line between two components.
Declaration:
public class JSeparator extends JComponent implements SwingConstants,
Accessible
Syntax:
jmenu_Item.addSeparator();
The JSeparatorContains 2 constructors. They are as following:
1. JSeparator()
2. JSeparator(int orientation)
68
/* Write a program to create a frame with the following menus, such that
the corresponding geometric object is created when a menu is clicked. (i) circle
(ii)
Rectangle (iii) Line (iv) Diagonal for the rectangle */
package swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class shapes extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu menu;
JMenuItem rect,line,oval;
shapes()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
mb=new JMenuBar();
menu=new JMenu("Shapes");
mb.add(menu);
rect=new JMenuItem("Rectangle");
rect.addActionListener(this);
menu.add(rect);
line=new JMenuItem("Line");
line.addActionListener(this);
oval=new JMenuItem("Circle");
oval.addActionListener(this);
menu.add(oval);
line=new JMenuItem("Rectangle_Diagonal");
line.addActionListener(this);
menu.add(line);
setJMenuBar(mb);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
Graphics g=getGraphics();
if(str=="Rectangle")
g.drawRect(200,200,50,50);
if(str=="Line")
g.drawLine(300,100,400,200);
if(str=="Circle")
g.drawOval(200,300,100,100);
if(str=="Rectangle_Diagonal")
g.drawLine(200,200,250,250);
}
public static void main(String args[])
{
shapes f=new shapes();
f.setTitle("SHAPES DEMO");
f.setSize(500,500);
f.setVisible(true);
}
}
package swing;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class dialogbox
implements ActionListener
{
JFrame f;
public static void main(String[] args)
{
new dialogbox();
}
public dialogbox()
{
f=new JFrame("Dialox Box Demo");
JButton B=new JButton("Click Me!!");
Container container=f.getContentPane();
container.setLayout(new FlowLayout());
container.add(B);
B.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(f,"Swing Programming is
a real
fun!!!","MyMessage",JOptionPane.INFORMATION_MESSAGE);
} }
Model-View-Controller
• MVC is a blueprint for organizing code which represents one of several design patterns. To understand
the need for these patterns, think about good and bad software.
• Good software is easy to change and work with, while bad software is difficult to modify. Design
patterns help us create the good kind of software.
Software evolves over time due to various factors:
• A new feature needs to be added.
• A bug needs to be fixed.
• Software needs to be optimized.
•The software design needs to be
improved. Indicators of bad software includes:
• Rigidity – Software requires a cascade of
changes when a change is made in one
place.
• Fragility – Software breaks in multiple
places when a change is made.
• Needless complexity – Software is
97
28-08-2023
Model-View-Controller
• Software can be intentionally designed to handle changes that might occur later on.
• The best approach is to create components in the application that are loosely connected to each other.
• In a loosely coupled application, you can make a change to one component of an application
without making changes to other parts.
• There are several principles that enable reducing dependencies between different parts of an application.
• Software design patterns represent strategies for applying software design principles. MVC is one of those
patterns.
In general, a visual component is a composite of three distinct aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
• Throughout time, a particular architectural approach has demonstrated remarkable efficiency: namely,
the Model-View-Controller, often referred to as MVC.
98
• The Model-View-Controller (MVC) software design pattern is a method for separating concerns within a
software application.
• As the name implies, the MVC pattern has three layers:
• The Model defines the business layer of the application,
• the Controller manages the flow of the application,
• the View defines the presentation layer of the application.
Model: Handles data and business logic. Represents the business layer of the application
View: Presents the data to the user whenever asked for. Defines the presentation of the application
Controller: Entertains user requests and fetch necessary resources. Manages the flow of the
application
Each of the components has a demarcated set of tasks which ensures smooth functioning of the
entire application along with complete modularity.
99
Model-View-Controller
Model :
• Model is where the application’s data objects are stored. It represents knowledge as a structure of
objects.
• The model doesn’t know anything about views and controllers but it can contain logic to update
controller if its data changes.
• The model is quite simply the data for our application.
• The data is “modelled” in a way it’s easy to store, retrieve, and edit.
• The model is how we apply rules to our data, which eventually represents the concepts our
application manages.
• For any software application, everything is modelled as data that can be handled easily.
• What is a user, a book, or a message for an app? Nothing really, only data that must be processed
according to specific rules. Like, the date must not be higher than the current date, the email must
be in the correct format, the name mustn’t be more than “x” characters long, etc.
28-08-2023 100
Model-View-Controller
Model:
• Whenever a user makes any request from the controller, it contacts the appropriate model which
returns a data representation of whatever the user requested.
• This model will be the same for a particular work, irrespective of how we wish to display it to the
user.
• That is why we can choose any available view to render the model data.
• Additionally, a model also contains the logic to update the relevant controller whenever there is
any change in the model’s data.
101
Model-View-Controller
VIEW:
• The view determines how the component is displayed on the screen, including any aspects of the view that
are affected by the current state of the model.
• View can also update the model by sending appropriate messages. Users interact with an application through
its View.
• As the name suggests, the view is responsible for rendering the data received from the model. There may
be pre-designed templates where you can fit the data, and there may even be several different views
per model depending on the requirements.
• Any web application is structured keeping these three core components in mind. There may be a primary
controller that is responsible for receiving all the requests and calling the specific controller for
specific actions.
102
Model-View-Controller
CONTROLLER:
• The controller determines how the component reacts to the user.
• Example : When the user clicks a check box, the controller reacts by changing the model to reflect the user’s
choice (checked or unchecked).
• The controller is like housekeeper of the application – it performs coordination between model and view
to entertain a user request. The user requests are received as HTTP get or post request – for example,
when the user clicks on any GUI elements to perform any action.
• The primary function of a controller is to call and coordinate with the model to fetch any necessary
resources required to act.
• Usually, on receiving a user request, the controller calls the appropriate model for the task at hand.
103
Model-View-Controller
• A common problem faced by application developers these days is the support for different type of
devices.
• The MVC architecture solves this problem as developers can create different interfaces for different
devices, and based on from which device the request is made, the controller will select an
appropriate view.
• The model sends the same data irrespective of the device being used, which ensures a complete
consistency across all devices.
• The MVC separation beautifully isolates the view from the business logic.
• It also reduces complexities in designing large application by keeping the code and workflow structured.
• This makes the overall code much easier to maintain, test, debug, and reuse.
28-08-2023
28-08-2023 104
Dr.Maivizhi AssistanAt
Advantages of the MVC Architecture
• We are going to create a Student object acting as a model.
• StudentView will be a view class which can print student details on console
• StudentController is the controller class responsible for storing data in the Student object and updating
StudentView accordingly.
• MVCPatternDemo, our demo class, will use StudentController to demonstrate the use of MVC
pattern.
Model-View-Controller
APP Faculties - CINTEL
28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 80
Model-View-Controller
APP Faculties - CINTEL
28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 81
Step 1: Create the Model :
Model-View-Controller
Step 2: Create the View
Dr.Maivizhi AssistanAt
28-08-2023 82
28-08-2023 APP Faculties - CINTEL
28-08-2023 108
Model-View-Controller
Step 3: Create the Controller
public class StudentController
{ private Student model;
private StudentView view;
public StudentController(Student model, StudentView view)
{ this.model = model;
this.view = view;
}
public void setStudentName(String name)
{ model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo)
{ model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView()
{ view.printStudentDetails(model.getName(),
model.getRollNo());
}
}
Dr.Maivizhi Assistant Professor / CINTEL
28-08-2023
28-08-2023 109
Dr.Maivizhi AssistanAtPPProFafecsuslotires/
Model-View-Controller
Step 4: Create the main Java file
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the
database Student model = retriveStudentFromDatabase();
//Create a view : to write student details on
console StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
//update model data
controller.setStudentName("John");
controller.updateView();
}
private static Student retriveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}
• “MVCPatternDemo.java” fetches
the
student data from the
database or a
function (in this case we’re
using a
function to set the values) and pushes it
on to the Student model.
• Then, it initializes the view we
had
created earlier.
• Further, it also initializes our controller
and binds it to the model and the view.
• The updateView() method is a part of the
controller which updates the
student details on the console.
Model-View-Controller
APP Faculties - CINTEL
28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 85
Step 5: Test the Result
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
• Graphical User Interface (GUI) elements are the visual components that allow users to interact with
software applications.
• These elements are often referred to as "widgets," which are essentially building blocks that make up
the user interface.
• Each widget serves a specific purpose and provides a way for users to input information, view data, or
trigger actions. Here is a list of controls in the javax.swing package
Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist )
Widgets
APP Faculties - CINTEL
28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 86
Information Display Components
• JLabel
• Progress bars (JProgressBar)
•Tool tips (using JComponent's setToolTipText(s)
method) Choosers
• File chooser (JFileChooser)
•Color chooser
(JColorChooser) More complex
displays
• Tables (JTable)
• Trees (JTree)
28-08-2023 112
Widgets
java.sql package
This package provides classes and interfaces to perform most of the JDBC functions like creating and
executing SQL queries.
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.
• 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.
JDBC Connection Steps
There are 6 basic steps to connect with JDBC.
Import Packages
•First, to import the existing packages to use it in our Java program.
Import will make sure that JDBC API classes are available for
the program. We can then use the classes and subclasses of the
packages.
import java.sql.*;
JDBC API 4.0 mainly provides 2 important packages:
•java.sql
•javax.sql
javax.sql package
•It is a JDBC extension API and provides server-side data access and
processing in Java Program.
Load Driver
First, we should load/register the driver in the program before connecting
to the Database. You need to register it only once per database in the
program.
We can load the driver in the following 2 ways:
1. Class.forName()
2. DriverManager.registerDriver()
Class.forName()
In this way, the driver’s class file loads into the memory at runtime. It
implicitly loads the driver. While loading, the driver will register with
JDBC automatically.
DriverManager.registerDriver()
DriverManager is an inbuilt class that is available in the java.sql package.
It acts as a mediator between Java application and database which you want to connect. Before
you connect with the database, you need to register the driver with DriverManager.
The main function of DriverManager is to load the driver class of the Database and create a connection
with DB.
• Public static void registerDriver(driver) – This method will register the driver with the
Driver Manager. If the driver is already registered, then it won’t take any action.
• It will throw SQLException if the database error occurs.
• It will throw NullPointerException if the driver is null.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())
Establish Connection
After loading the driver, the next step is to create and establish the connection. Once
required, packages are imported and drivers are loaded and registered, then we can
go for establishing a Database connection.
DriverManager class has the getConnection method, we will use this method to get
the connection with Database.
To call getConnection() method, we need to pass 3 parameters. The 3 parameters are
string data type URL, a username, and a password to access the database.
• The getConnection() method is an overloaded method. The 2 methods are:
• getConnection(URL,username,password); – It has 3 parameters URL, username,
password.
• getConnection(URL); – It has only one parameter. URL has a username and
password also.
Establish Connection
The following table lists the JDBC connection strings for the different
databases:
Example:
Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost
:1521:xe,System,Pass123@)
Here in this example,
•thin refers to the Driver type.
•localhost is where the Oracle database is running.
•1521 is the port number to connect to DB.
•xe – SID
•System – User name to connect to the Oracle Database.
•Pass123@ – Password
Create And Execute Statement
Once the connection has established, we can interact with the connected Database. First, we need to
create the statement to perform the SQL query and then execute the statement.
(i) Create Statement
Now we will create the statement object that runs the query with the connected database. We use the
createStatement method of the Connection class to create the query.
There are 3 statement interfaces are available in the java.sql package. These are explained below:
a) Statement
This interface is used to implement simple SQL statements with no parameter. It returns the
ResultSet object.
Statement statemnt1 = conn.createStatement();
Create And Execute Statement
b) PreparedStatement
This PreparedStatement interface extends the Statement interface. So, it
has more features than the Statement interface. It is used to implement
parameterized and precompiled SQL statements. The performance of
the application increases because it compiles the query only once.
•It is easy to reuse this interface with a new parameter. It supports the
IN parameter. Even we can use this statement without any parameter.
String select_query = “Select * from states where state_id = 1”;
PreparedStatement prpstmt = conn.prepareStatement(select_query);
Create And Execute Statement
c) CallableStatement
CallableStatement interface extends the PreparedStatement interface. So, it
has more features than the PreparedStatement interface. It is used to
implement a parameterized SQL statement that invokes procedure or function
in the database. A stored procedure works like a method or function in a class.
It supports the IN and OUT parameters.
• The CallableStatement instance is created by calling the prepareCall method
of the Connection object.
CallableStatementcallStmt = con.prepareCall("{call procedures(?,?)}");
Create And Execute Statement
(ii) Execute The Query
There are 4 important methods to execute the query in Statement interface. These are explained
below:
• ResultSet executeQuery(String sql)
• int executeUpdate(String sql)
• boolean execute(String sql)
• int []executeBatch()
a) ResultSet executeQuery(String sql)
The executeQuery() method in Statement interface is used to execute the
SQL query and retrieve the values from DB. It returns the ResultSet object.
Normally, we will use this method for the SELECT query.
b) executeUpdate(String sql)
The executeUpdate() method is used to execute value specified queries like
INSERT, UPDATE, DELETE (DML statements), or DDL statements that return
nothing. Mostly, we will use this method for inserting and updating.
c) execute(String sql)
The execute() method is used to execute the SQL query. It returns true if it
executes the SELECT query. And, it returns false if it executes INSERT or
UPDATE query.
d) executeBatch()
This method is used to execute a batch of SQL queries to the Database and
if all the queries get executed successfully, it returns an array of update
cA
oP
uP
nFa
tc
su
.lt
Wies
e- C
wIN
iT
llEL
use this method to insert/update the bulk
Retrieve Results
• When we execute the queries using the executeQuery() method, the result will be stored
in the ResultSet object.
• The returned ResultSet object will never be null even if there is no matching record in the
table. ResultSet object is used to access the data retrieved from the Database.
ResultSet rs 1= statemnt1.executeQuery(QUERY));
• The executeQuery() method for the SELECT query. When someone tries to execute the
insert/update query, it will throw SQLExecption with the message “executeQuery method
can not be used for update”.
• A ResultSet object points to the current row in the Resultset. To iterate the data in the
ResultSet object, call the next() method in a while loop. If there is no more record to
read, it will return FALSE.
• ResultSet can also be used to update data in DB. We can get the data from ResultSet using
getter methods such as getInt(), getString(), getDate(). We need to pass the column
index or column name as the parameter to get the values using Getter methods.
APP Faculties - CINTEL
Dr.Maivizhi Assistant Professor / CINTEL
Close Connection
• To close the JDBC connection. need to make sure that we have closed the resource after
we have used it. If we don’t close them properly we may end up out of connections.
• When we close the connection object, Statement and ResultSet objects will be closed
automatically.
conn.close();
• From Java 7 onwards, we can close the JDBC connections automatically using a try-catch
block. JDBC connection should be opened in the parenthesis of the try block. Inside the
try block, you can do the database connections normally as we do.
• Once the execution exits the try block, it will automatically close the connection. In this
case, we don’t need to close the connection by calling conn.close method in the Java
program.
try(Connection conn = DriverManager.getConnection(url, user, password))
{
//database connection and operation
}
Java JDBC Connection Example
Implement the 6 basic steps to connect with database using JDBC in Java program.
Create Table
• Before that, first, create one table and add some entries into it.
• Below is the SQL query to create a table.
• create table employee_details (empNum INT(10), lastName varchar(50), firstName varchar(50), email
varchar(255) , deptNum INT(10), salary INT(10));
Insert Data Into Table
• Using the following queries, insert the data into the “employee_details” table.
insert into employee_details values (1001, 'Luther', 'Martin', 'ml@gmail.com', 1, 13000);
insert into employee_details values (1002, 'Murray', 'Keith', 'km@gmail.com', 2, 25000);
insert into employee_details values (1003, 'Branson', 'John', 'jb@gmail.com', 3, 15000);
insert into employee_details values (1004, 'Martin', 'Richard', 'rm@gmail.com', 4, 16000);
insert into employee_details values (1005, 'Hickman', 'David', 'dh@gmail.com', 5, 17000);
Java Program - Oracle
import java.sql.*;
public class Sample_JDBC_Program {
public static void main(String[] args) throws
ClassNotFoundException, SQLException {
// store the SQL statement in a string
String QUERY = "select * from
employee_details“
//register the oracle driver with DriverManager
Class.forName("oracle.jdbc.driver.OracleDriver");
/*Here we have used Java 8 so opening the connection in try
statement*/
try(Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:system/pass123@
localhost:1521:XE"))
{
Statement statemnt1 = conn.createStatement();
//Created statement and execute it
ResultSet rs1 = statemnt1.executeQuery(QUERY);
{
//Get the values of the record using while loop
while(rs1.next())
{
int empNum = rs1.getInt("empNum");
String lastName = rs1.getString("lastName"); String
firstName = rs1.getString("firstName"); String
email = rs1.getString("email");
String deptNum = rs1.getString("deptNum"); String
salary = rs1.getString("salary");
//store the values which are retrieved using ResultSet and print it
System.out.println(empNum + "," +lastName+ "," +firstName+ ","
+email +","+deptNum +"," +salary);
}
}
}
catch (SQLException e) {
//If exception occurs catch it and exit the program
e.printStackTrace();
}
}
}
Java Program - Mysql
import java.sql.*;
public class javamysql {
public static void main(String arg[])
{ Connection connection = null;
try {
// below two lines are used for connectivity.
Class.forName("com.mysql.cj.jdbc.Driver");
connection =
DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/mydb","mydbuser",
"mydbuser");
// mydb is database; mydbuser is name of database ;mydbuser is password of database
Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery("select * from designation"); int
code;
String title;
while (resultSet.next()) {
code = resultSet.getInt("code");
title = resultSet.getString("title").trim();
System.out.println("Code : " + code
+ " Title : " + title);
}
resultSet.close();
statement.close();
connection.close();
}
}
}

advanced java programming paradigms presentation

  • 1.
    Unit-3 - AdvancedJava Programming Paradigms
  • 2.
    Concurrent Programming Paradigm •Computing systems model the world, and the world contains actors that execute independently of, but communicate with, each other. In modelling the world, many (possibly) parallel executions have to be composed and coordinated, and that's where the study of concurrency comes in. • There are two common models for concurrent programming: shared memory and message passing. • Shared memory. In the shared memory model of concurrency, concurrent modules interact by reading and writing shared objects in memory. • Message passing. In the message-passing model, concurrent modules interact by sending messages to each other through a communication channel. Modules send off messages, and incoming messages to each module are queued up for handling 3
  • 4.
  • 6.
    Multithreaded Programming • Javaprovides built-in support for multithreaded programming. • A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. • There are two distinct types of multitasking: process-based and thread- based. • It is important to understand the difference between the two.
  • 7.
    Process-based multitasking • Process-basedmultitasking is the more familiar form. • A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows your computer to run two or more programs concurrently. • For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor. • In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler. Thread-based multitasking • Thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. • For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads. • Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the details.
  • 11.
    Lifecycle of athread -Thread States
  • 12.
  • 13.
    Creation of aJava Thread In Java we can implement the thread programs using two approaches - o Using Thread class o sing runnable interface
  • 14.
    Thread Class andthe Runnable Interface • Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. • The Thread class defines several methods that help manage threads.
  • 15.
    How to starta thread in Java how to create a single thread by extending Thread Class. class MyThread extends Thread { public void run() { System.out.println("Thread is created!!!"); } } class ThreadProg { public static void main(String args[]) { MyThread t=new MyThread(); t.start(); } } class MyRunnable implements Runnable { public void run() { System.out.println("This is a runnable."); } } 1. Create the instance of class MyClass. 2. This instance is passed as a parameter to Thread class. 3. Using the instance of class Thread invoke the start method. 4. The start method in-turn calls the run method written in MyClass.
  • 16.
    Create a threadby extending the Thread Class. Also make use of constructor and display message "You are Welcome to Thread Programming". class MyThread extends Thread { String str=""; //data member of class MyThread MyThread(String s)//constructor { this.str=s; } public void run() { System.out.println(str); } } class ThreadProg { public static void main(String args[]) { MyThread t=new MyThread("You are Welcome to Thread Programming"); t.start(); } }
  • 17.
    Implementing Runnable Interface Thethread can also be created using Runnable interface.  Implementing thread program using Runnable interface is preferable than implementing it by extending the thread class because of the following two reasons - 1. If a class extends a thread class then it can not extends any other class which may be required to extend. 2. If a class thread is extended then all its functionalities get inherited. This is an expensive operation.
  • 18.
    class MyThread implementsRunnable { public void run() { System.out.println("Thread is created!"); } } class ThreadProgRunn { public static void main(String args[]) { MyThread obj=new MyThread(); Thread t=new Thread(obj); t.start(); } }
  • 19.
    Write a Javaprogram that prints the numbers from 1 to 10 line by line after every 10 seconds. class NumPrint extends Thread { int num; NumPrint() { start();//directs to the run method } public void run()//thread execution starts { for(int i=1;i<=10;i++) { System.out.println(i); Thread.sleep(10000); } } } public class MultiThNum { public static void main(String args[]) { NumPrint t1; t1=new NumPrint(); } }
  • 20.
    Creating Multiple Threads classA extends Thread //class A implements Runnable { public void run() { for(int i=0;i<=5;i++)//printing 0 to 5 { System.out.println(i); } }} class B extends Thread //class B implements Runnable { public void run() { for(int i=10;i>=5;i--)//printing 10 to 5 { System.out.println(i); } }} The multiple threads can be created both by extending Thread class and by implementing the Runnable interface. class ThreadProg { public static void main(String args[]) { A t1=new A(); B t2=new B(); t1.start(); t2.start(); } } // Runnable interface Thread t1=new Thread(obj1); Thread t2=new Thread(obj2);
  • 21.
    Write a Javaapplication program for generating four threads to perform the following operations - i) Getting N numbers as input ii) Printing the numbers divisible by five iii) Printing prime numbers iv) Computing the average. import java.io.*; import java.util.*; class FirstThread extends Thread { public void run() //generating N numbers { int i; System.out.println("nGenerating Numbers: "); for (i=1;i<=10;i++) { System.out.println(i); } } } class SecondThread extends Thread { public void run() //Displaying the numbers divisible by five { int i; System.out.println("nDivisible by Five: "); for (i=1;i<=10;i++) //10 can be replaced by any desired value { if (i%5==0) System.out.println(i); } } }
  • 22.
    class ThirdThread extendsThread { public void run() //generating the prime numbers { int i; System.out.println("nPrime Numbers: "); for (i=1;i<=10;i++) //10 can be replaced by any desired value { int j; for (j=2; j<i; j++) { int n = i%j; if (n==0) break; } if(i == j) System.out.println(i); } }} class FourthThread extends Thread { public void run() //generating the prime numbers { int i,sum; double avg; sum=0; System.out.println("nComputing Average: "); for (i=1;i<=10;i++) //10 can be replaced by any desired value sum=sum+i; avg=sum/(i-1); System.out.println(avg); } }
  • 23.
    class MainThread { public staticvoid main(String[] args) throws IOException { FirstThread T1 = new FirstThread(); //creating first thread SecondThread T2 = new SecondThread(); //creating second thread ThirdThread T3 = new ThirdThread(); //creating Third thread FourthThread T4 = new FourthThread(); //creating Fourth thread T1.start(); //First Thread starts executing T2.start();//Second Thread starts executing T3.start();//Third Thread starts executing T4.start();//Fourth Thread starts executing } } Generating Numbers: 1 2 3 4 5 6 7 8 9 10 Divisible by Five: 5 10 Computing Average: 5.0 Prime Numbers: 2 3 5 7
  • 24.
    Thread Priorities • Threadpriorities are used by the thread scheduler to decide when each thread should be allowed to run. • To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form: final void setPriority(int level) • Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. • Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as final variables within Thread. • You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here: final int getPriority( )
  • 26.
    1. Write ajava program that implements a multi-thread application that has three threads. First thread generates random integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of cube of the number. 2. Write a java program for to solve producer consumer problem in which a producer produce a value and consumer consume the value before producer generate the next value. 3. Write a java program in which thread sleep for 5 sec and change the name of thread.
  • 27.
    Graphics User Interface(GUI) based Programming • The graphics programming in Java is supported by the AWT package. • The AWT stands for Abstract Window Toolkit. • The AWT contains large number of classes which help to include various graphical components in the Java program. • The graphical components include text box, buttons, labels, radio buttons, list items and so on. • These classes are arranged in hierarchical manner which is recognized as AWT hierarchy.
  • 28.
    GUI - AWT •Graphical User Interface (GUI) Java Abstract Window Toolkit (AWT) is an Application Program Interface (API) to develop GUI or window- based application in java. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous classes and methods that allow you to create and manage the GUI window. • AWT is an Application programming interface (API) for creating Graphical User Interface (GUI) in Java. • It allows Java programmers to develop window-based applications. • AWT represents a class library to develop applications using GUI. • AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program. AWT components use the resources of the operating system, i.e., they are platform-dependent, which means, component's view can be changed according to the view of the operating system. The classes for AWT are provided by the Java.awt package for various AWT components. • The Java.awt package contains classes and interfaces that help create graphical user interfaces and enable more user-friendly programme interaction.
  • 29.
    Hierarchy of AWTcomponents
  • 30.
    Hierarchy of components- AWT 1. Component : This is the super class of all the graphical classes from which variety of graphical classes can be derived. It helps in displaying the graphical object on the screen. It handles the mouse and keyboard events. 2. Container : This is a graphical component derived from the component class. It is responsible for managing the layout and placement of graphical components in the container. 3. Window : The top level window without border and without the menu bar is created using the window class. It decides the layout of the window. 4. Panel : The panel class is derived from the container class. It is just similar to window - without any border and without any menu bar, title bar. 5. Frame : This is a top-level window with a border and menu bar. It supports the common window events such as window open, close, activate and deactivate.
  • 31.
    Example // importing JavaAWT class import java.awt.*; public class AWTExample1 extends Frame { AWTExample1() { Button b = new Button("Click Me!!"); b.setBounds(30,100,80,30); add(b); setSize(300,300); setTitle("This is our basic AWT example"); setLayout(null); setVisible(true); } public static void main(String args[]) { AWTExample1 f = new AWTExample1(); } }
  • 32.
    JAVA APPLETS • Ajava applet is a program that appears embedded in a web document and applet come into effect when the browser browse the web page. • to generate the dynamic content. It runs inside the browser and works at client side.  It is a similar kind of programs like in C,C++ and Pascal. etc., to solve a problem.  It works at client side so less response time.  Secured  It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.  Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.
  • 33.
    What are Appletsin Java? The interactive components of web applications are provided by Java applets, which can be easily run by many different platforms' browsers. They can launch automatically when the pages are browsed and are tiny, portable Java programmes embedded in HTML pages. • Applet inherits awt Component class and awt Container class
  • 34.
    Life cycle ofan Applet There are various methods which are typically used in applet for initialization and termination purpose. 1. Initialization 2. Running state 3. Idle state 4. Dead or destroyed state
  • 35.
    Lifecycle of anapplet • 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. Within the method paint() we will call the drawString() method to print a text message in the applet window.
  • 36.
    Example import java.awt.*; import java.applet.*; publicclass SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } When applet begins, the AWT calls following methods in sequence - a) init() b) start() c) paint() When applet is terminated following methods are invoked in sequence. a) stop() b) destroy()
  • 37.
    Executing an Applet Thereare two methods to run the applet 1. Using web browser 2. Using Appletviewer Using web browser Step 1 : Compile your Applet source program using javac compiler, i.e. D:test>javac FirstApplet.java Step 2 : Write following code in Notepad/Wordpad and save it with filename and extension .html. For example following code is saved as Exe_FirstApplet.html, The code is <applet code="FirstApplet" width=300 height=100> </applet> Step 3 : Load html file with some web browser, This will cause to execute your html file Using Appletviewer Step 1 : To run the applet without making use of web browser or using command prompt we need to modify the code little bit. Step 2 : D:test>javac FirstApplet.java D:test>Appletviewer FirstApplet.java
  • 38.
    Example of anApplet Java Program[ColorDemo.java] import java.awt.*; import java.applet.*; /* <applet code="ColorDemo" width=300 height=100> </applet> */ public class ColorDemo extends Applet { public void paint(Graphics g) { setBackground(Color.cyan); setForeground(Color.red); g.drawString("Its a colorful Applet",50,30); Color newColor=new Color(255,255,0); //creating red+green=yellow color g.setColor(newColor); g.drawString("Its a colorful Applet",50,70); }
  • 39.
    Write an appletprogram for displaying the circle in green color. import java.awt.*; import java.applet.*; /* <applet code="CircleDemo" width=300 height=300> </applet> */ public class CircleDemo extends Applet { public void paint(Graphics g) { g.setColor(Color.green); g.fillOval(10,10,50,50); } }
  • 40.
    Example of anapplet import java.applet.Applet; import java.awt.*; public class GraphicsDemo extends Applet{ public void paint(Graphics g){ g.setColor(Color.red); g.drawString("Welcome",50, 50); g.drawLine(20,30,20,300); g.drawRect(70,100,30,30); 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); } } <html> <body> <applet code="GraphicsDemo.class" width="300" heig ht="300"> </applet> </body> </html>
  • 41.
    Event Handling inapplet import java.applet.*; import java.awt.*; import java.awt.event.*; public class EventApplet extends Applet implements ActionListner{ Button b; TextField tf; public void init(){ tf=new TextField(); tf.setBounds(30,40,150,20); b=new Button("Click"); b.setBounds(80,150,60,50); add(b);add(tf); b.addActionListener(this); setLayout(null); } public void actionPerformed(ActionEvent e){ tf.setText("Welcome"); } 1.<html> 2.<body> 3.<applet code="EventApplet.class" width="300" height="300"> 4.</applet> 5.</body> 6.</html>
  • 42.
    Applets Advantages of applets •The response time is quicker because it operates on the client-side. It is secured. • Web browsers must adhere to tight security regulations while using applets. • It is compatible with browsers on various operating systems, including Linux, Windows, and Mac OS. Disadvantages of applets • The client browser requires a plugin to run the applet. • The mobile browser on iOS or Android does not run any Java applets. Desktop browsers have dropped support for Java applets along with the rise of mobile operating systems. Applet features over HTML • It displays the dynamic web pages of a web application. • Play audio files. • Display documents. • Play animations.
  • 43.
    • Swing inJava is a lightweight and platform-independent class of the Java foundation class. It's used to make applications that run in windows. • It contains elements such as a button, a scroll bar, and a text field. A graphical user interface is created by combining all of these elements. • Swing Framework includes several classes that provide more vital and more versatile GUI (Graphical User Interface) components than AWT(Abstract Window Toolkit). • Swing is a Sun Microsystems-published official Java GUI toolkit that closely resembles the look and feels of modern Java GUIs. It is used to create the graphical user interface for Java Class. Java SWING - Introduction 43
  • 44.
    Platform Independent It isplatform-independent, as the swing components used to construct the program are not platform-specific. It works on any platform and in any location. Customizable Swing controls are simple to customize. It can be changed, and the swing component application's visual appearance is independent of its internal representation. Plugging • Java Swing has pluggable look and feel. This feature allows users to change the appearance and feel of Swing components without having to restart the application. • The Swing library will enable components to have the same look and feel across all platforms, regardless of where the program is running. • The Swing library provides an API that allows complete control over the appearance and feel of an application's graphical user interface Java SWING FEATURES 44
  • 45.
    • MVC standsfor Model-View-Controller. • The model agrees with the state information associated with the Component in MVC terminology. • The view determines how the component appears on screen and any aspects of the view that are influenced by the model's current state. • The controller is in charge of determining how the component responds to the user. Manageable Look and Feel • It's simple to manage and configure. • Its mechanism and composition pattern allows changes to be made to the settings while the program runs. • Constant changes to the application code can be made without making any changes to the user interface. Java SWING FEATURES(Contd.) 45
  • 46.
    Java SWING FEATURES(Contd.) Lightweight • Lightweight Components: The JDK's AWT has supported lightweight component development. • A component must not rely on non-Java [O/s based] system classes to be considered light. • The look and feel classes in Java help Swing components have their view. 46 • Swing is another approach of graphical programming in Java. • Swing creates highly interactive GUI applications. • It is the most flexible and robust approach.
  • 47.
    JFC and Swing JFCstands for Java Foundation Classes, a set of classes used to create graphical user interfaces (GUIs) and add rich graphical features and interactivity to Java applications. The Java Classes Foundation holds Java Swing (JFC). 47
  • 48.
    Swing Hierarchy JFC standsfor Java Foundation Classes, a set of classes used to create graphical user interfaces (GUIs) and add rich graphical features and interactivity to Java applications. The Java Classes Foundation holds Java Swing (JFC). 48
  • 49.
    What are SwingComponents in Java? •A component is independent visual control, and Java Swing Framework contains a large set of these components, providing rich functionalities and allowing high customization. •They all are derived from JComponent class. All these components are lightweight components. •This class offers some standard functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc. •A container holds a group of components. • It delivers a space where a component can be managed and displayed. Containers are of two types: 49
  • 50.
  • 51.
    Jbutton • JButton classto create a push button on the UI. • The button can include some display text or images. • It yields an event when clicked and double-clicked. • Can implement a JButton in the application by calling one of its constructors. Syntax: JButton okBtn = new JButton(“Click”); Display: Top Swing components in Java 51
  • 52.
    JLabel • Use JLabelclass to render a read-only text label or images on the UI. It does not generate any event. Syntax: JLabel textLabel = new JLabel(“This is 1st L...”); • This constructor returns a label with specified text. JLabel imgLabel = new JLabel(carIcon); It returns a label with a car icon. The JLabel Contains four constructors. They are as follows: 1. JLabel() 2. JLabel(String s) 3. JLabel(Icon i) 4. JLabel(String s, Icon i, int horizontalAlignment) 52
  • 53.
    The JTextField rendersan editable single-line text box. Users can input non-formatted text in the box. Can initialize the text field by calling its constructor and passing an optional integer parameter. This parameter sets the box width measured by the number of columns. Also, it does not limit the number of characters that can be input into the box. Syntax: JTextField txtBox = new JTextField(50); It is the most widely used text component. It has three constructors: 1. JTextField(int cols) 2. JTextField(String str, int cols) 3. JTextField(String str) Note: cols represent the number of columns in the text field. JTextField 53
  • 54.
    JCheckBox The JCheckBox rendersa check-box with a label. The check-box has two states, i.e., on and off. On selecting, the state is set to "on," and a small tick is displayed inside the box. Syntax: CheckBox chkBox = new JCheckBox(“Java Swing”, true); • It returns a checkbox with the label Pepperoni pizza. • Notice the second parameter in the constructor. • It is a boolean value that denotes the default state of the check-box. • True means the check-box defaults to the "on" state. 54
  • 55.
    JRadioButton •A radio buttonis a group of related buttons from which can select only one. •Use JRadioButton class to create a radio button in Frames and render a group of radio buttons in the UI. •Users can select one choice from the group. Syntax: JRadioButton jrb = new JRadioButton("Easy"); Display: 55
  • 56.
    JComboBox • The combobox is a combination of text fields and a drop-down list • Use JComboBox component to create a combo box in Swing. Syntax: JcomboBox jcb = new JComboBox(name); JTextArea In Java, the Swing toolkit contains a JTextArea Class. It is under package javax.swing.JTextArea class. It is used for displaying multiple-line text. Declaration: public class JTextArea extends JTextComponent 56
  • 57.
    Syntax: JTextArea textArea_area=new JTextArea("Ninja!please write something in the text area."); The JTextArea Contains four constructors. They are as follows: 1. JTextArea() 2. JTextArea(String s) 3. JTextArea(int row, int column) 4. JTextArea(String s, int row, int column) Display: 57
  • 58.
    JPasswordField • In Java,the Swing toolkit contains a JPasswordField Class. • It is under package javax.swing.JPasswordField class. • It is specifically used for the password, and we can edit them. Declaration: public class JPasswordField extends JTextField Syntax: JPasswordField password = new JPasswordField(); The JPasswordFieldContains 4 constructors. They are as follows: • JPasswordField() • JPasswordField(int columns) • JPasswordField(String text) • JPasswordField(String text, int columns) 58
  • 59.
    JTable • In Java,the Swing toolkit contains a JTable Class. • It is under package javax.swing.JTable class. • It is used to draw a table to display data. Syntax: JTable table = new JTable(table_data, table_column); The JTable contains two constructors. They are as follows: 1. JTable() 2. JTable(Object[][] rows, Object[] columns) 59
  • 60.
    JList • In Java,the Swing toolkit contains a JList Class. • It is under package javax.swing.JList class. • It is used to represent a list of items together. • We can select one or more than one items from the list. Declaration: public class JList extends JComponent implements Scrollable, Accessible Syntax: DefaultListModel<String> list1 = new DefaultListModel<>(); list1.addElement("Apple"); list1.addElement("Orange"); list1.addElement("Banan"); list1.addElement("Grape"); JList<String> list_1 = new JList<>(list1); 60
  • 61.
    The JListContains 3constructors. They are as follows: JList() JList(ary[] listData) JList(ListModel<ary> dataModel) Display: 61
  • 62.
    JOptionPane In Java, theSwing toolkit contains a JOptionPane Class. It is under package javax.swing.JOptionPane class. It is used for creating dialog boxes for displaying a message, confirm box, or input dialog box. Declaration: public class JOptionPane extends JComponent implements Accessible Syntax: JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night."); The JOptionPaneContains 3 constructors. They are as following: 1. JOptionPane() 2. JOptionPane(Object message) 3. JOptionPane(Object message, intmessageType) 62
  • 63.
    JScrollBar • In Java,the Swing toolkit contains a JScrollBar class. • It is under package javax.swing.JScrollBar class. • It is used for adding horizontal and vertical scrollbars. Declaration: public class JScrollBar extends JComponent implements Adjustable, Accessible Syntax: JScrollBar scrollBar = new JScrollBar(); The JScrollBarContains 3 constructors. They are as following: 1. JScrollBar() 2. JScrollBar(int orientation) 3. JScrollBar(int orientation, int value, int extent, int min_, intmax_) 63
  • 64.
    • In Java,the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. • It is under package javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. • The JMenuBar class is used for displaying menubar on the frame. • The JMenu Object is used to pull down the menu bar's components. • The JMenuItem Object is used for adding the labeled menu item. JMenuBar, JMenu and JMenuItem Declarations: public class JMenuBar extends JComponent implements MenuElement, Accessible public class JMenu extends JMenuItem implements MenuElement, Accessible JMenuBar, JMenu and JMenuItem 64
  • 65.
    Syntax: JMenuBar menu_bar =new JMenuBar(); JMenu menu = new JMenu("Menu"); menuItem1 = new JMenuItem("Never"); menuItem2 = new JMenuItem("Stop"); menuItem3 = new JMenuItem("Learing"); menu.add(menuItem1); menu.add(menuItem2); menu.add(menuItem3); 65
  • 66.
    JPopupMenu • In Java,the Swing toolkit contains a JPopupMenu Class. • It is under package javax.swing.JPopupMenu class. • It is used for creating popups dynamically on a specified position. Declaration: public class JPopupMenu extends JComponent implements Accessible, MenuElement Syntax: final JPopupMenu popupmenu1 = new JPopupMenu("Edit"); The JPopupMenuContains 2 constructors. They are as follows: 1. JPopupMenu() 2. JPopupMenu(String label) 66
  • 67.
    JCheckBoxMenuItem • In Java,the Swing toolkit contains a JCheckBoxMenuItem Class. • It is under package javax.swing.JCheckBoxMenuItem class. •It is used to create a checkbox on a menu. Syntax: JCheckBoxMenuItem item = new JCheckBoxMenuItem("Option_1"); The JCheckBoxMenuItem Contains 2 constructors. They are as following: 1. JCheckBoxMenuItem() 2. JCheckBoxMenuItem(Action a) 3. JCheckBoxMenuItem(Icon icon) 4. JCheckBoxMenuItem(String text) 5. JCheckBoxMenuItem(String text, boolean b) 6. JCheckBoxMenuItem(String text, Icon 67
  • 68.
    JSeparator • In Java,the Swing toolkit contains a JSeparator Class. • It is under package javax.swing.JSeparator class. • It is used for creating a separator line between two components. Declaration: public class JSeparator extends JComponent implements SwingConstants, Accessible Syntax: jmenu_Item.addSeparator(); The JSeparatorContains 2 constructors. They are as following: 1. JSeparator() 2. JSeparator(int orientation) 68
  • 69.
    /* Write aprogram to create a frame with the following menus, such that the corresponding geometric object is created when a menu is clicked. (i) circle (ii) Rectangle (iii) Line (iv) Diagonal for the rectangle */ package swing; import javax.swing.*; import java.awt.*; import java.awt.event.*; class shapes extends JFrame implements ActionListener { JMenuBar mb; JMenu menu; JMenuItem rect,line,oval; shapes() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); mb=new JMenuBar(); menu=new JMenu("Shapes"); mb.add(menu); rect=new JMenuItem("Rectangle"); rect.addActionListener(this); menu.add(rect); line=new JMenuItem("Line"); line.addActionListener(this);
  • 70.
    oval=new JMenuItem("Circle"); oval.addActionListener(this); menu.add(oval); line=new JMenuItem("Rectangle_Diagonal"); line.addActionListener(this); menu.add(line); setJMenuBar(mb); } publicvoid actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); Graphics g=getGraphics(); if(str=="Rectangle") g.drawRect(200,200,50,50); if(str=="Line") g.drawLine(300,100,400,200); if(str=="Circle") g.drawOval(200,300,100,100); if(str=="Rectangle_Diagonal") g.drawLine(200,200,250,250); } public static void main(String args[]) { shapes f=new shapes(); f.setTitle("SHAPES DEMO"); f.setSize(500,500); f.setVisible(true); } }
  • 71.
    package swing; import java.awt.*; importjavax.swing.*; import javax.swing.event.*; import java.awt.event.*; public class dialogbox implements ActionListener { JFrame f; public static void main(String[] args) { new dialogbox(); } public dialogbox() { f=new JFrame("Dialox Box Demo"); JButton B=new JButton("Click Me!!"); Container container=f.getContentPane(); container.setLayout(new FlowLayout()); container.add(B); B.addActionListener(this); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300,300); f.setVisible(true); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(f,"Swing Programming is a real fun!!!","MyMessage",JOptionPane.INFORMATION_MESSAGE); } }
  • 72.
    Model-View-Controller • MVC isa blueprint for organizing code which represents one of several design patterns. To understand the need for these patterns, think about good and bad software. • Good software is easy to change and work with, while bad software is difficult to modify. Design patterns help us create the good kind of software. Software evolves over time due to various factors: • A new feature needs to be added. • A bug needs to be fixed. • Software needs to be optimized. •The software design needs to be improved. Indicators of bad software includes: • Rigidity – Software requires a cascade of changes when a change is made in one place. • Fragility – Software breaks in multiple places when a change is made. • Needless complexity – Software is 97
  • 73.
    28-08-2023 Model-View-Controller • Software canbe intentionally designed to handle changes that might occur later on. • The best approach is to create components in the application that are loosely connected to each other. • In a loosely coupled application, you can make a change to one component of an application without making changes to other parts. • There are several principles that enable reducing dependencies between different parts of an application. • Software design patterns represent strategies for applying software design principles. MVC is one of those patterns. In general, a visual component is a composite of three distinct aspects: • The way that the component looks when rendered on the screen • The way that the component reacts to the user • The state information associated with the component • Throughout time, a particular architectural approach has demonstrated remarkable efficiency: namely, the Model-View-Controller, often referred to as MVC. 98
  • 74.
    • The Model-View-Controller(MVC) software design pattern is a method for separating concerns within a software application. • As the name implies, the MVC pattern has three layers: • The Model defines the business layer of the application, • the Controller manages the flow of the application, • the View defines the presentation layer of the application. Model: Handles data and business logic. Represents the business layer of the application View: Presents the data to the user whenever asked for. Defines the presentation of the application Controller: Entertains user requests and fetch necessary resources. Manages the flow of the application Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire application along with complete modularity. 99 Model-View-Controller
  • 75.
    Model : • Modelis where the application’s data objects are stored. It represents knowledge as a structure of objects. • The model doesn’t know anything about views and controllers but it can contain logic to update controller if its data changes. • The model is quite simply the data for our application. • The data is “modelled” in a way it’s easy to store, retrieve, and edit. • The model is how we apply rules to our data, which eventually represents the concepts our application manages. • For any software application, everything is modelled as data that can be handled easily. • What is a user, a book, or a message for an app? Nothing really, only data that must be processed according to specific rules. Like, the date must not be higher than the current date, the email must be in the correct format, the name mustn’t be more than “x” characters long, etc. 28-08-2023 100 Model-View-Controller
  • 76.
    Model: • Whenever auser makes any request from the controller, it contacts the appropriate model which returns a data representation of whatever the user requested. • This model will be the same for a particular work, irrespective of how we wish to display it to the user. • That is why we can choose any available view to render the model data. • Additionally, a model also contains the logic to update the relevant controller whenever there is any change in the model’s data. 101 Model-View-Controller
  • 77.
    VIEW: • The viewdetermines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model. • View can also update the model by sending appropriate messages. Users interact with an application through its View. • As the name suggests, the view is responsible for rendering the data received from the model. There may be pre-designed templates where you can fit the data, and there may even be several different views per model depending on the requirements. • Any web application is structured keeping these three core components in mind. There may be a primary controller that is responsible for receiving all the requests and calling the specific controller for specific actions. 102 Model-View-Controller
  • 78.
    CONTROLLER: • The controllerdetermines how the component reacts to the user. • Example : When the user clicks a check box, the controller reacts by changing the model to reflect the user’s choice (checked or unchecked). • The controller is like housekeeper of the application – it performs coordination between model and view to entertain a user request. The user requests are received as HTTP get or post request – for example, when the user clicks on any GUI elements to perform any action. • The primary function of a controller is to call and coordinate with the model to fetch any necessary resources required to act. • Usually, on receiving a user request, the controller calls the appropriate model for the task at hand. 103 Model-View-Controller
  • 79.
    • A commonproblem faced by application developers these days is the support for different type of devices. • The MVC architecture solves this problem as developers can create different interfaces for different devices, and based on from which device the request is made, the controller will select an appropriate view. • The model sends the same data irrespective of the device being used, which ensures a complete consistency across all devices. • The MVC separation beautifully isolates the view from the business logic. • It also reduces complexities in designing large application by keeping the code and workflow structured. • This makes the overall code much easier to maintain, test, debug, and reuse. 28-08-2023 28-08-2023 104 Dr.Maivizhi AssistanAt Advantages of the MVC Architecture
  • 80.
    • We aregoing to create a Student object acting as a model. • StudentView will be a view class which can print student details on console • StudentController is the controller class responsible for storing data in the Student object and updating StudentView accordingly. • MVCPatternDemo, our demo class, will use StudentController to demonstrate the use of MVC pattern. Model-View-Controller APP Faculties - CINTEL 28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 80
  • 81.
    Model-View-Controller APP Faculties -CINTEL 28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 81 Step 1: Create the Model :
  • 82.
    Model-View-Controller Step 2: Createthe View Dr.Maivizhi AssistanAt 28-08-2023 82
  • 83.
    28-08-2023 APP Faculties- CINTEL 28-08-2023 108 Model-View-Controller Step 3: Create the Controller public class StudentController { private Student model; private StudentView view; public StudentController(Student model, StudentView view) { this.model = model; this.view = view; } public void setStudentName(String name) { model.setName(name); } public String getStudentName(){ return model.getName(); } public void setStudentRollNo(String rollNo) { model.setRollNo(rollNo); } public String getStudentRollNo(){ return model.getRollNo(); } public void updateView() { view.printStudentDetails(model.getName(), model.getRollNo()); } } Dr.Maivizhi Assistant Professor / CINTEL
  • 84.
    28-08-2023 28-08-2023 109 Dr.Maivizhi AssistanAtPPProFafecsuslotires/ Model-View-Controller Step4: Create the main Java file public class MVCPatternDemo { public static void main(String[] args) { //fetch student record based on his roll no from the database Student model = retriveStudentFromDatabase(); //Create a view : to write student details on console StudentView view = new StudentView(); StudentController controller = new StudentController(model, view); controller.updateView(); //update model data controller.setStudentName("John"); controller.updateView(); } private static Student retriveStudentFromDatabase(){ Student student = new Student(); student.setName("Robert"); student.setRollNo("10"); return student; } } • “MVCPatternDemo.java” fetches the student data from the database or a function (in this case we’re using a function to set the values) and pushes it on to the Student model. • Then, it initializes the view we had created earlier. • Further, it also initializes our controller and binds it to the model and the view. • The updateView() method is a part of the controller which updates the student details on the console.
  • 85.
    Model-View-Controller APP Faculties -CINTEL 28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 85 Step 5: Test the Result Student: Name: Robert Roll No: 10 Student: Name: John Roll No: 10
  • 86.
    • Graphical UserInterface (GUI) elements are the visual components that allow users to interact with software applications. • These elements are often referred to as "widgets," which are essentially building blocks that make up the user interface. • Each widget serves a specific purpose and provides a way for users to input information, view data, or trigger actions. Here is a list of controls in the javax.swing package Input Components • Buttons ( JButton, JRadioButtons, JCheckBox) • Text (JTextField, JTextArea) • Menus (JMenuBar, JMenu, JMenuItem) • Sliders (JSlider) • JComboBox (uneditable) (JComboBox) • List (Jlist ) Widgets APP Faculties - CINTEL 28-08-2023 Dr.Maivizhi Assistant Professor / CINTEL 86
  • 87.
    Information Display Components •JLabel • Progress bars (JProgressBar) •Tool tips (using JComponent's setToolTipText(s) method) Choosers • File chooser (JFileChooser) •Color chooser (JColorChooser) More complex displays • Tables (JTable) • Trees (JTree) 28-08-2023 112 Widgets
  • 88.
    java.sql package This packageprovides classes and interfaces to perform most of the JDBC functions like creating and executing SQL queries.
  • 89.
    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. • 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.
  • 90.
    JDBC Connection Steps Thereare 6 basic steps to connect with JDBC.
  • 91.
    Import Packages •First, toimport the existing packages to use it in our Java program. Import will make sure that JDBC API classes are available for the program. We can then use the classes and subclasses of the packages. import java.sql.*; JDBC API 4.0 mainly provides 2 important packages: •java.sql •javax.sql
  • 92.
    javax.sql package •It isa JDBC extension API and provides server-side data access and processing in Java Program.
  • 93.
    Load Driver First, weshould load/register the driver in the program before connecting to the Database. You need to register it only once per database in the program. We can load the driver in the following 2 ways: 1. Class.forName() 2. DriverManager.registerDriver()
  • 94.
    Class.forName() In this way,the driver’s class file loads into the memory at runtime. It implicitly loads the driver. While loading, the driver will register with JDBC automatically.
  • 95.
    DriverManager.registerDriver() DriverManager is aninbuilt class that is available in the java.sql package. It acts as a mediator between Java application and database which you want to connect. Before you connect with the database, you need to register the driver with DriverManager. The main function of DriverManager is to load the driver class of the Database and create a connection with DB. • Public static void registerDriver(driver) – This method will register the driver with the Driver Manager. If the driver is already registered, then it won’t take any action. • It will throw SQLException if the database error occurs. • It will throw NullPointerException if the driver is null. DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()) DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())
  • 96.
    Establish Connection After loadingthe driver, the next step is to create and establish the connection. Once required, packages are imported and drivers are loaded and registered, then we can go for establishing a Database connection. DriverManager class has the getConnection method, we will use this method to get the connection with Database. To call getConnection() method, we need to pass 3 parameters. The 3 parameters are string data type URL, a username, and a password to access the database. • The getConnection() method is an overloaded method. The 2 methods are: • getConnection(URL,username,password); – It has 3 parameters URL, username, password. • getConnection(URL); – It has only one parameter. URL has a username and password also.
  • 97.
    Establish Connection The followingtable lists the JDBC connection strings for the different databases: Example: Connection con = DriverManager.getConnection(jdbc:oracle:thin:@localhost :1521:xe,System,Pass123@) Here in this example, •thin refers to the Driver type. •localhost is where the Oracle database is running. •1521 is the port number to connect to DB. •xe – SID •System – User name to connect to the Oracle Database. •Pass123@ – Password
  • 98.
    Create And ExecuteStatement Once the connection has established, we can interact with the connected Database. First, we need to create the statement to perform the SQL query and then execute the statement. (i) Create Statement Now we will create the statement object that runs the query with the connected database. We use the createStatement method of the Connection class to create the query. There are 3 statement interfaces are available in the java.sql package. These are explained below: a) Statement This interface is used to implement simple SQL statements with no parameter. It returns the ResultSet object. Statement statemnt1 = conn.createStatement();
  • 99.
    Create And ExecuteStatement b) PreparedStatement This PreparedStatement interface extends the Statement interface. So, it has more features than the Statement interface. It is used to implement parameterized and precompiled SQL statements. The performance of the application increases because it compiles the query only once. •It is easy to reuse this interface with a new parameter. It supports the IN parameter. Even we can use this statement without any parameter. String select_query = “Select * from states where state_id = 1”; PreparedStatement prpstmt = conn.prepareStatement(select_query);
  • 100.
    Create And ExecuteStatement c) CallableStatement CallableStatement interface extends the PreparedStatement interface. So, it has more features than the PreparedStatement interface. It is used to implement a parameterized SQL statement that invokes procedure or function in the database. A stored procedure works like a method or function in a class. It supports the IN and OUT parameters. • The CallableStatement instance is created by calling the prepareCall method of the Connection object. CallableStatementcallStmt = con.prepareCall("{call procedures(?,?)}");
  • 101.
    Create And ExecuteStatement (ii) Execute The Query There are 4 important methods to execute the query in Statement interface. These are explained below: • ResultSet executeQuery(String sql) • int executeUpdate(String sql) • boolean execute(String sql) • int []executeBatch() a) ResultSet executeQuery(String sql) The executeQuery() method in Statement interface is used to execute the SQL query and retrieve the values from DB. It returns the ResultSet object. Normally, we will use this method for the SELECT query. b) executeUpdate(String sql) The executeUpdate() method is used to execute value specified queries like INSERT, UPDATE, DELETE (DML statements), or DDL statements that return nothing. Mostly, we will use this method for inserting and updating. c) execute(String sql) The execute() method is used to execute the SQL query. It returns true if it executes the SELECT query. And, it returns false if it executes INSERT or UPDATE query. d) executeBatch() This method is used to execute a batch of SQL queries to the Database and if all the queries get executed successfully, it returns an array of update cA oP uP nFa tc su .lt Wies e- C wIN iT llEL use this method to insert/update the bulk
  • 102.
    Retrieve Results • Whenwe execute the queries using the executeQuery() method, the result will be stored in the ResultSet object. • The returned ResultSet object will never be null even if there is no matching record in the table. ResultSet object is used to access the data retrieved from the Database. ResultSet rs 1= statemnt1.executeQuery(QUERY)); • The executeQuery() method for the SELECT query. When someone tries to execute the insert/update query, it will throw SQLExecption with the message “executeQuery method can not be used for update”. • A ResultSet object points to the current row in the Resultset. To iterate the data in the ResultSet object, call the next() method in a while loop. If there is no more record to read, it will return FALSE. • ResultSet can also be used to update data in DB. We can get the data from ResultSet using getter methods such as getInt(), getString(), getDate(). We need to pass the column index or column name as the parameter to get the values using Getter methods. APP Faculties - CINTEL Dr.Maivizhi Assistant Professor / CINTEL
  • 103.
    Close Connection • Toclose the JDBC connection. need to make sure that we have closed the resource after we have used it. If we don’t close them properly we may end up out of connections. • When we close the connection object, Statement and ResultSet objects will be closed automatically. conn.close(); • From Java 7 onwards, we can close the JDBC connections automatically using a try-catch block. JDBC connection should be opened in the parenthesis of the try block. Inside the try block, you can do the database connections normally as we do. • Once the execution exits the try block, it will automatically close the connection. In this case, we don’t need to close the connection by calling conn.close method in the Java program. try(Connection conn = DriverManager.getConnection(url, user, password)) { //database connection and operation }
  • 104.
    Java JDBC ConnectionExample Implement the 6 basic steps to connect with database using JDBC in Java program. Create Table • Before that, first, create one table and add some entries into it. • Below is the SQL query to create a table. • create table employee_details (empNum INT(10), lastName varchar(50), firstName varchar(50), email varchar(255) , deptNum INT(10), salary INT(10)); Insert Data Into Table • Using the following queries, insert the data into the “employee_details” table. insert into employee_details values (1001, 'Luther', 'Martin', 'ml@gmail.com', 1, 13000); insert into employee_details values (1002, 'Murray', 'Keith', 'km@gmail.com', 2, 25000); insert into employee_details values (1003, 'Branson', 'John', 'jb@gmail.com', 3, 15000); insert into employee_details values (1004, 'Martin', 'Richard', 'rm@gmail.com', 4, 16000); insert into employee_details values (1005, 'Hickman', 'David', 'dh@gmail.com', 5, 17000);
  • 105.
    Java Program -Oracle import java.sql.*; public class Sample_JDBC_Program { public static void main(String[] args) throws ClassNotFoundException, SQLException { // store the SQL statement in a string String QUERY = "select * from employee_details“ //register the oracle driver with DriverManager Class.forName("oracle.jdbc.driver.OracleDriver"); /*Here we have used Java 8 so opening the connection in try statement*/ try(Connection conn = DriverManager.getConnection("jdbc:oracle:thin:system/pass123@ localhost:1521:XE")) { Statement statemnt1 = conn.createStatement(); //Created statement and execute it ResultSet rs1 = statemnt1.executeQuery(QUERY); { //Get the values of the record using while loop while(rs1.next()) { int empNum = rs1.getInt("empNum"); String lastName = rs1.getString("lastName"); String firstName = rs1.getString("firstName"); String email = rs1.getString("email"); String deptNum = rs1.getString("deptNum"); String salary = rs1.getString("salary"); //store the values which are retrieved using ResultSet and print it System.out.println(empNum + "," +lastName+ "," +firstName+ "," +email +","+deptNum +"," +salary); } } } catch (SQLException e) { //If exception occurs catch it and exit the program e.printStackTrace(); } } }
  • 106.
    Java Program -Mysql import java.sql.*; public class javamysql { public static void main(String arg[]) { Connection connection = null; try { // below two lines are used for connectivity. Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://l ocalhost:3306/mydb","mydbuser", "mydbuser"); // mydb is database; mydbuser is name of database ;mydbuser is password of database Statement statement; statement = connection.createStatement(); ResultSet resultSet; resultSet = statement.executeQuery("select * from designation"); int code; String title; while (resultSet.next()) { code = resultSet.getInt("code"); title = resultSet.getString("title").trim(); System.out.println("Code : " + code + " Title : " + title); } resultSet.close(); statement.close(); connection.close(); } } }

Editor's Notes

  • #2 In Java, a thread is a lightweight sub-process, the smallest unit of processing. It's a path of execution within a program. The Java Virtual Machine (JVM) allows an application to have multiple threads running concurrently, each performing different tasks. Concurrency focuses on managing multiple tasks at once, not necessarily implying that they're running simultaneously. Parallelism refers to the simultaneous execution of multiple tasks or distributing different parts of a specific task amongst different processors.
  • #3 Simply described, it's when you are doing more than one thing at the same time. Not to be confused with parallelism, concurrent or concurrency programming is when multiple sequences of operations are run in overlapping periods of time. Concurrent programming is a computer science technique that allows multiple tasks to be executed simultaneously, or during overlapping time periods, instead of sequentially. This allows tasks to overlap, enabling progress on different fronts simultaneously. Concurrent programming can improve performance and responsiveness. Multiple tasks in computer Draw and display images on screen Check keyboard and mouse input Send and receive data on network Perform useful computation (editor, browser, game)
  • #4 Multithreading refers to a programming technique where multiple threads of execution exist within a single application. Multithreading is just one way to achieve concurrency in Java. Concurrency can also be achieved through other means, such as multiprocessing, asynchronous programming, or event-driven programming.
  • #5 For example, when you are reading web page at the same time you can type into using word processor and at the same time you can play your music. So, all the things are going in parallel. So, for everything for playing a music there is a one thread for browsing the information from the internet one thread whenever you are typing something using a word processor application is another Thread and all these things. Now so there are many applications where the multithreaded way the executions are there and to be carried out. 
  • #6  A process is an instance of a program that is being executed or processed. Thread is a segment of a process or a lightweight process that is managed by the scheduler independently. Processes are independent of each other and hence don't share a memory or other resources. Threads are interdependent and share memory.
  • #7 A thread in Java is the direction or path that is taken while a program is being executed. Generally, all the programs have at least one thread, known as the main thread, that is provided by the JVM or Java Virtual Machine at the starting of the program's execution. A multithreaded server is any server that has more than one thread. Because a transport requires its own thread, multithreaded servers also have multiple transports. The number of thread-transport pairs that a server contains defines the number of requests that the server can handle in parallel. When a client sends the request, a thread is generated through which a user can communicate with the server. We need to generate multiple threads to accept multiple requests from multiple clients at the same time. 
  • #8 In process-based multitasking, two or more processes and programs can be run concurrently. In thread-based multitasking, two or more threads can be run concurrently. In process-based multitasking, a process or a program is the smallest unit. In thread-based multitasking, a thread is the smallest unit. The program is a bigger unit. Thread is a smaller unit. Process-based multitasking requires more overhead. Thread-based multitasking requires less overhead. The process requires its own address space. Threads share the same address space. It has a faster data rate for multi-tasking because two or more processes/programs can be run simultaneously. It has a comparatively slower data rate multi-tasking. example: We can listen to music and browse the internet at the same time. The processes in this example are the music player and browser. Example: Using a browser we can navigate through the webpage and at the same time download a file. In this example, navigation is one thread, and downloading is another thread. Also in a word-processing application like MS Word, we can type text in one thread, and spell checker checks for mistakes in another thread. 
  • #9 Synchronization : In java, when two or more threads try to access the same resource simultaneously it causes the java runtime to execute one or more threads slowly, or even suspend their execution. In order to overcome this problem, we have thread synchronization. Synchronization means coordination between multiple processes/threads. Thread scheduling : A component of Java that helps in deciding that which thread to run or execute and which thread to wait is called thread scheduler in Java. A thread is only chosen by a thread scheduler only if it is in a runnable state. Inter thread communication: a method that allows many synchronized threads to communicate or interact with one another. In Java, there are two ways to implement inter-thread communication: using wait() and notify() methods and using the higher-level constructs of the java. Thread is a tiny program running continuously. It is sometimes called as light-weight process. But there lies differences between thread and process. Thread is a light-weight process. Process is a heavy weight process. Threads do not require separate address space for its execution. It runs in the address space of the process to which it belongs to. Each process requires separate address space to execute. Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since you can’t directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, your program will either extend Thread or implement the Runnable interface. The Thread class defines several methods that help manage threads
  • #11 New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the thread is in this state. When a thread lies in the new state, its code is yet to be run and hasn’t started to execute. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might actually be running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to run.  A multi-threaded program allocates a fixed amount of time to each individual thread. Each and every thread runs for a short while and then pauses and relinquishes the CPU to another thread so that other threads can get a chance to run. When this happens, all such threads that are ready to run, waiting for the CPU and the currently running thread lie in a runnable state. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is acquired by the other thread. The thread will move from the blocked state to runnable state when it acquires the lock. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will move to the runnable state when other thread will notify or that thread will be terminated. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread lies in this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a conditional wait, it is moved to a timed waiting state. Terminated State: A thread terminates because of either of the following reasons:  Because it exits normally. This happens when the code of the thread has been entirely executed by the program. Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception. The Life Cycle of a Thread in Java refers to the state transformations of a thread that begins with its birth and ends with its death. When a thread instance is generated and executed by calling the start() method of the Thread class, the thread enters the runnable state. When the sleep() or wait() methods of the Thread class are called, the thread enters a non-runnable mode. Thread returns from non-runnable state to runnable state and starts statement execution. The thread dies when it exits the run() process. In Java, these thread state transformations are referred to as the Thread life cycle.
  • #12 A thread in Java is the direction or path that is taken while a program is being executed. Generally, all the programs have at least one thread, known as the main thread, that is provided by the JVM or Java Virtual Machine at the starting of the program’s execution. At this point, when the main thread is provided, the main() method is invoked by the main thread. A thread is an execution thread in a program. Multiple threads of execution can be run concurrently by an application running on the Java Virtual Machine. The priority of each thread varies. Higher priority threads are executed before lower priority threads. Thread in Java enables concurrent execution, dividing tasks for improved performance. It's essential for handling operations like I/O and network communication efficiently. Understanding threads is crucial for responsive Java applications.
  • #13 Main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is: static Thread currentThread( ) This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread.
  • #14 The Thread class can be used to create a thread. Using the extend keyword your class extends the Thread class for creation of thread. For example if I have a class named A then it can be written as class A extends Thread Constructor of Thread Class : Following are various syntaxes used for writing the constructor of Thread Class. Thread() Thread(String s) Thread(Runnable obj) Thread(Runnable obj, String s);
  • #15 start() The thread can be started and invokes the run method. run() Once thread is started it executes in run method. setName() We can give the name to a thread using this method. getName() The name of the thread can be obtained using this name. join() This method waits for thread to end The start() method initiates the execution of a thread. It calls the run() method defined in your thread class or runnable object. Invoking run() directly will not start a new thread, so it is crucial to use start(). The run() method contains the code that will be executed in the thread. It must be overridden when extending the Thread class or implementing the Runnable interface. we have created two classes. One class named MyThread extends the Thread class. In this class the run method is defined. This run method is called by t.start() in main() method of class ThreadProg. The thread gets created and executes by displaying the message Thread is created
  • #18 we have used interface Runnable.  While using the interface, it is necessary to use implements keyword.  Inside the main method 1. Create the instance of class MyClass. 2. This instance is passed as a parameter to Thread class. 3. Using the instance of class Thread invoke the start method. 4. The start method in-turn calls the run method written in MyClass.  The run method executes and display the message for thread creation
  • #19 //10 sec,b’coz 1000millisec=1 sec.
  • #25 Java Thread Priorities The number of services assigned to a given thread is referred to as its priority. Any thread generated in the JVM is given a priority. The priority scale runs from 1 to 10. 1 is known as the lowest priority. 5 is known as standard priority. 10 represents the highest level of priority. Thread priority is 1 Thread priority is 10
  • #29 The Panel is a simplest container class. It provides space in which an application can attach any other component. It inherits the Container class. It doesn't have title bar.
  • #30 void drawRect(int top,int left,int width,int height) void drawRoundRect(int top,int left,int width,int height,int xdimeter,int ydimeter) void fillRect(int top,int left,int width,int height) void fillRoundRect(int top,int left,int width,int height,int xdimeter,int ydimeter) void drawLine(int x1,int y1,int x2,int y2); void fillOval(int top, int left, int width, int height) void drawArc(int top,int left,int width,int height,int angle1,int angle2) void fillArc(int top,int left,int width,int height,int angle1,int angle2) Color(int R,int G,int B).
  • #31 // importing Java AWT class   import java.awt.*;        // extending Frame class to our class AWTExample1   public class AWTExample1 extends Frame {           // initializing using constructor      AWTExample1() {            // creating a button          Button b = new Button("Click Me!!");            // setting button position on screen         b.setBounds(30,100,80,30);            // adding button into frame           add(b);            // frame size 300 width and 300 height           setSize(300,300);            // setting the title of Frame         setTitle("This is our basic AWT example");                     // no layout manager          setLayout(null);             // now frame will be visible, by default it is not visible           setVisible(true);   }        // main method   public static void main(String args[]) {       // creating instance of Frame class    AWTExample1 f = new AWTExample1();        }      }    
  • #32 Component : This is the super class of all the graphical classes from which variety of graphical classes can be derived. It helps in displaying the graphical object on the screen. It handles the mouse and keyboard events. Container : This is a graphical component derived from the component class. It is responsible for managing the layout and placement of graphical components in the container. Window : The top level window without border and without the menu bar is created using the window class. It decides the layout of the window. Panel : The panel class is derived from the container class. It is just similar to window - without any border and without any menu bar, title bar. Frame : This is a top-level window with a border and menu bar. It supports the common window events such as window open, close, activate and deactivate.
  • #33 All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt package. Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser or an applet viewer. Execution of an applet does not begin at main( ) [In other words, there is no main() method in an Applet]. Output to your applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application. Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that contains the APPLET tag.
  • #35 Initialization state: When applet gets loaded it enters in the initialization state. For this purpose the init() method is used. In this method you can initialize the required variables. This method is called only once initially at the execution of the program. Running state: When the applet enters in the running state, it invokes the start() method of Applet class. This method is called only after the init method. After stopping the applet when we restart the applet at that time also this method is invoked. Display state: Applet enters in the display state when it wants to display some output. This may happen when applet enters in the running state. The paint() method is for displaying or drawing the contents on the screen. Idle state: This is an idle state in which applet becomes idle. The stop() method is invoked when we want to stop the applet .When an applet is running if we go to another page then this method is invoked. Dead state: When applet is said to be dead then it is removed from memory. The method destroy() is invoked when we want to terminate applet completely and want to remove it from the memory.
  • #37 An application is a standalone program that can be invoked from the command line. An applet is a program that runs in the context of a browser session. A servlet is a program that is invoked on demand on a server program and that runs in the context of a web server process.
  • #104 create table employee_details (empNum number(10), lastName varchar(50), firstName varchar(50), email varchar(255) , deptNum number(10), salary number(10));