SlideShare a Scribd company logo
Concurrent
Programming
02
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Essentials Part 1
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Java
• Source Code
• english text - understood by humans
• Compiler
• converts to byte codes - understood by JVM
• Interpreter (Java Virtual Machine)
• convert to machine code - understood by machine
Setting up the Environment
• Download and install Java SDK
• Setup environmental variable
• http://www.tutorialspoint.com/java/java_environment_setup.htm
• Write the program in a text file and save as example.java
• Open CMD and compile using
• javac example.java
• run the program using
• java ExampleProgram
Common Problems
• http://docs.oracle.com/javase/tutorial/getStarted/p
roblems/index.html
Comments
• Commenting is important
• Code Comments
• //comment
• /* comment */
• Doc Comments
• /** */
• To generate documentation for your program
• to enclose lines of text for the javadoc tool to find.
• The javadoc tool locates the doc comments embedded in source files and uses those
comments to generate API documentation.
• http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html
Building Applications
Application Structure and
Elements
• Class
• Properties
• Methods
• Class will store data in a field
• store text in a string field
• Class will store methods to work on the data
• Accessor Methods (Mutator Method)
• Used to control changes to variables in accordance with Encapsulation
• Setter Method - set value of a variable
• Getter Method - get value of a variable
Application Structure and
Elements Cont.d
• Main method
• is essential
• entry point to the program
• code will execute first
• this is the class name passed to java interpreter to run the application
• public
• JVM can call the main method - not protected
• static
• no need to create an instance
• void
• no data returned when run
Application Structure and
Elements Cont.d
• instance of a class
• executable copy of the class
• need to acquire and work on data
• not needed only in the main static method
• static fields and methods of a class can be called by another program
without creating an instance of the class
• can call the static println method in the System class, without creating
an instance of the System class.
• a program must create an instance of a class to access its non-static
fields and methods.
Fields and Methods
• Example2 program alters the first example to store the text string in a static field
called text.
• text field is static so its data can be accessed directly by the static call to out.println
without creating an instance of the Program2 class.
• example3 and example4 programs add a getText method to the program to retrieve
and print the text.
• example3 program accesses the static text field with the non-static getText method.
• Non-static methods and fields are called instance methods and fields.
• This approach requires that an instance of the Program3 class be created in the main
method.
• To keep things interesting, this example includes a static text field and a non-static
instance method (getStaticText) to retrieve it.
Fields and Methods Cont.d
• The example4 program accesses the static text field with the static getText
method.
• Static methods and fields are called class methods and fields.
• This approach allows the program to call the static getText method directly
without creating an instance of the Program4 class.
• class methods can operate only on class fields
• instance methods can operate on class and instance fields.
• there is only one copy of the data stored or set in a class field
• each instance has its own copy of the data stored or set in an instance field.
• http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Constructors
• a special method that is called when a class instance is created.
• class constructor always has the same name as the class and no return
type
• Program5 converts the Program4 to use a constructor to initialize the
text string.
• If you do not write your own constructor, the compiler adds an empty
constructor, which calls the no-arguments constructor of its parent class.
• The empty constructor is called the default constructor.
• The default constructor initializes all non-initialized fields and variables to
zero.
More on this…
• http://docs.oracle.com/javase/tutorial/java/javaOO
/classvars.html
Building Applets
Application to Applet
• Like applications, applets are created from classes.
• applets do not have a main method as an entry point
• have several methods to control specific aspects of applet
execution.
• example6 code is the applet equivalent to the Program5
application
• The SimpleApplet class is declared public so the program
that runs the applet (a browser or appletviewer), which is
not local to the program can access it.
Run the Applet
• HTML file with the Applet tag
• easiest way to run the applet is with appletviewer
where simpleApplet.html is a file that contains the
above HTML code:
• appletviewer simpleApplet.html
• https://www.ailis.de/~k/archives/63-how-to-use-java-
applets-in-modern-browsers.html
Applet Structures & Elements
• The Java API Applet class provides what you need to design the
appearance and manage the behavior of an applet.
• This class provides a GUI component called a Panel and a
number of methods.
• To create an applet, you extend (or subclass) the Applet class and
implement the appearance and behavior you want.
• The applet's appearance is created by drawing onto the Panel or
by attaching other GUI components such as push buttons,
scrollbars, or text areas to the Panel.
• The applet's behavior is defined by implementing the methods.
Extending a Class
• to write a new class that can use the fields and
methods defined in the class being extended.
• The class being extended is the parent class, and
the class doing the extending is the child class.
• Another way to say this is the child class inherits the
fields and methods of its parent or chain of parents.
• Child classes either call or override inherited
methods. This is called single inheritance.
Extending a Class Cont.d
• The SimpleApplet class extends Applet class, which extends the Panel class, which
extends the Container class.
• The Container class extends Object, which is the parent of all Java API classes.
• The Applet class provides the init, start, stop, destroy, and paint methods you saw in
the example applet.
• The SimpleApplet class overrides these methods to do what the SimpleApplet class
needs them to do.
• The Applet class provides no functionality for these methods.
• However, the Applet class does provide functionality for the setBackground
method,which is called in the init method.
• The call to setBackground is an example of calling a method inherited from a parent
class in contrast to overriding a method inherited from a parent class.
Extending a Class Cont.d
• Why the Java language provides methods without
implementations?
• It is to provide conventions for everyone to use for consistency
across Java APIs.
• If everyone wrote their own method to start an applet, for
example, but gave it a different name such as begin or go, the
applet code would not be interoperable with other programs
and browsers, or portable across multiple platforms.
• For example, Netscape and Internet Explorer know how to look
for the init and start methods.
Behavior
• An applet is controlled by the software that runs it.
• Usually, the underlying software is a browser, but it can also be
appletviewer as you saw in the example.
• The underlying software controls the applet by calling the methods the
applet inherits from the Applet class.
• The init Method: The init method is called when the applet is first created
and loaded by the underlying software.
• This method performs one-time operations the applet needs for its
operation such as creating the user interface or setting the font.
• In the example, the init method initializes the text string and sets the
background color.
Behavior Cont.d
• The start Method: The start method is called when the applet is visited
such as when the end user goes to a web page with an applet on it.
• The example prints a string to the console to tell you the applet is starting.
• In a more complex applet, the start method would do things required at the
start of the applet such as begin animation or play sounds.
• After the start method executes, the event thread calls the paint method to
draw to the applet's Panel.
• A thread is a single sequential flow of control within the applet, and every
applet can run in multiple threads.
• Applet drawing methods are always called from a dedicated drawing and
event-handling thread.
Behavior Cont.d
• The stop and destroy Methods: The stop method stops the applet
when the applet is no longer on the screen such as when the end
user goes to another web page.
• The example prints a string to the console to tell you the applet is
stopping.
• In a more complex applet, this method should do things like stop
animation or sounds.
• The destroy method is called when the browser exits.
• Your applet should implement this method to do final cleanup
such as stop live threads.
Appearance
• The Panel provided in the Applet class inherits a paint method from
its parent Container class.
• To draw something onto the Applet's Panel, you implement the paint
method to do the drawing.
• The Graphics object passed to the paint method defines a graphics
context for drawing on the Panel.
• The Graphics object has methods for graphical operations such as
setting drawing colors, and drawing graphics, images, and text.
• The paint method for the SimpleApplet draws the text string in red
inside a blue rectangle.
Packages
• The applet code also has three import statements at the top.
• Applications of any size and all applets use import statements to access ready-
made Java API classes in packages.
• This is true whether the Java API classes come in the Java platform download,
from a third-party, or are classes you write yourself and store in a directory
separate from the program.
• At compile time, a program uses import statements to locate and reference
compiled Java API classes stored in packages elsewhere on the local or
networked system.
• A compiled class in one package can have the same name as a compiled class
in another package.
• The package name differentiates the two classes.
Packages Cont.d
• The examples in examples 1 and 2 did not need
a package declaration to call the
System.out.println Java API class because the
System class is in the java.lang package that is
included by default.
• You never need an import java.lang.* statement
to use the compiled classes in that package.
More on this…
• http://docs.oracle.com/javase/tutorial/
Building a User
Interface
Project Swing APIs
• This expands the basic application from earlier to give it a user interface using the
Java Foundation Classes (JFC) Project Swing APIs that handle user events.
• the applet - user interface attached to a panel object nested in a top-level browser
• the Project Swing application - user interface attached to a panel object nested in a
top-level frame object.
• A frame object is a top-level window that provides a title, banner, and methods to
manage the appearance and behavior of the window.
• The Project Swing code that follows builds this simple application.
• The window on the left appears when you start the application, and the window on
the right appears when you click the button.
• Click again and you are back to the original window on the left.
Import Statements
• Here is the SwingUI.java code.
• At the top, you have four lines of import statements.
• The lines indicate exactly which Java API classes the
program uses.
• You could replace four of these lines with this one line:
import java.awt.*;, to import the entire awt package,
• but doing that increases compilation overhead than
importing exactly the classes you need and no others.
Class Declaration
• The class declaration comes next and indicates the top-level frame for the application's user
interface is a JFrame that implements the ActionListener interface.
• The JFrame class extends the Frame class that is part of the Abstract Window Toolkit
(AWT) APIs.
• Project Swing extends the AWT with a full set of GUI components and services, pluggable
look and feel capabilities, and assistive technology support.
• The Java APIs provide classes and interfaces for you to use.
• An interface defines a set of methods, but does not implement them.
• The rest of the SwingUI class declaration indicates that this class will implement the
ActionListener interface.
• This means the SwingUI class must implement all methods defined in the ActionListener
interface.
• Fortunately, there is only one, actionPerformed.
Instance Variables
• These next lines declare the Project Swing component
classes the SwingUI class uses.
• These are instance variables that can be accessed by any
method in the instantiated class.
• In this example, they are built in the SwingUI constructor
and accessed in the actionPerformed method
implementation.
• The private boolean instance variable is visible only to the
SwingUI class and is used in the actionPerformedmethod
to find out whether or not the button has been clicked.
Constructor
• The constructor creates the user interface components and JPanel object,
adds the components to the JPanel object, adds the panel to the frame, and
makes the JButton components event listeners.
• The JFrame object is created in the main method when the program starts.
• When the JPanel object is created, the layout manager and background
color are specified.
• The layout manager in use determines how user interface components are
arranged on the display area.
• The code uses the BorderLayout layout manager, which arranges user
interface components in the five areas shown at left.
• To add a component, specify the area (north, south, east, west, or center).
Constructor Cont.d
• The call to the getContentPane method of the JFrame
class is for adding the Panel to the JFrame.
• Components are not added directly to a JFrame, but to its
content pane.
• Because the layout manager controls the layout of
components, it is set on the content pane where the
components reside.
• A content pane provides functionality that allows different
types of components to work together in Project Swing.
Action Listening
• In addition to implementing the ActionListener interface, you have to add the event listener to
the JButton components.
• An action listener is the SwingUI object because it implements the ActionListener interface.
• In this example, when the end user clicks the button, the underlying Java platform services
pass the action (or event) to the actionPerformed method.
• In your code, you implement the actionPerformed method to take the appropriate action
based on which button is clicked..
• The component classes have the appropriate add methods to add action listeners to them.
• In the code the JButton class has an addActionListener method.
• The parameter passed to addActionListener is this, which means the SwingUI action listener
is added to the button so button-generated actions are passed to the actionPerformed method
in the SwingUI object.
Event Handling
• The actionPerformed method is passed an event
object that represents the action event that
occurred.
• Next, it uses an if statement to find out which
component had the event, and takes action
according to its findings.
Main Method
• The main method creates the top-level frame, sets the title, and includes code that
lets the end user close the window using the frame menu.
• The code for closing the window shows an easy way to add event handling
functionality to a program.
• If the event listener interface you need provides more functionality than the program
actually uses, use an adapter class.
• The Java APIs provide adapter classes for all listener interfaces with more than one
method.
• This way, you can use the adapter class instead of the listener interface and
implement only the methods you need.
• In the example, the WindowListener interface has 7 methods and this program needs
only the windowClosing method so it makes sense to use the WindowAdapter class
instead.
Main Method Cont.d
• This code extends the WindowAdapter class and overrides the windowClosing
method.
• The new keyword creates an anonymous instance of the extended inner class.
• It is anonymous because you are not assigning a name to the class and you
cannot create another instance of the class without executing the code again.
• It is an inner class because the extended class definition is nested within the
SwingUI class.
• This approach takes only a few lines of code, while implementing the
WindowListener interface would require 6 empty method implementations.
• Be sure to add the WindowAdapter object to the frame object so the frame
object will listen for window events.
Writing Servlets
Servelets
• A servlet is an extension to a server that enhances the server's functionality.
• The most common use for a servlet is to extend a web server by providing
dynamic web content.
• Web servers display documents written in HyperText Markup Language
(HTML) and respond to user requests using the HyperText Transfer Protocol
(HTTP).
• HTTP is the protocol for moving hypertext files across the internet.
• HTML documents contain text that has been marked up for interpretation by
an HTML browser such as Netscape.
• Servlets are easy to write. All you need is Tomcat, which is the combined
Java Server Pages 1.1 and Servlets 2.2 reference implementation.
About the Example
• A browser accepts end user input through an HTML
form.
• The simple form used in this lesson has one text input
field for the end user to enter text and a Submit button.
• When the end user clicks the Submit button, the simple
servlet is invoked to process the end user input.
• In this example, the simple servlet returns an HTML
page that displays the text entered by the end user.
HTML Form
• The HTML form is embedded in this HTML file.
• The HTML file and form are similar to the simple application and
applet examples so you can compare the code and learn how
servlets, applets, and applications handle end user inputs.
• When the user clicks the Click Me button, the servlet gets the
entered text, and returns an HTML page with the text.
• Note: To run the example, you have to put the servlet and HTML files
in the correct directories for the Web server you are using.
• For example, with Java WebServer 1.1.1, you place the servlet in the
~/JavaWebServer1.1.1/servlets and the HTML file in the
~/JavaWebServer1.1.1/public_html directory.
Servlet Backend
• ExampServlet.java builds an HTML page to return to the end user.
• This means the servlet code does not use any Project Swing or Abstract
Window Toolkit (AWT) components or have event handling code.
• For this simple servlet, you only need to import these packages:
• java.io for system input and output. The HttpServlet class uses the
IOException class in this package to signal that an input or output exception
of some kind has occurred.
• javax.servlet, which contains generic (protocol-independent) servlet classes.
The HttpServlet class uses the ServletException class in this package to
indicate a servlet problem.
• javax.servlet.http, which contains HTTP servlet classes. The HttpServlet class
is in this package.
Class and Method
Declarations
• All servlet classes extend the HttpServlet abstract class.
• HttpServlet simplifies writing HTTP servlets by providing a framework for handling the
HTTP protocol.
• Because HttpServlet is abstract, your servlet class must extend it and override at
least one of its methods.
• An abstract class is a class that contains unimplemented methods and cannot be
instantiated itself.
• The ExampServlet class is declared public so the web server that runs the servlet,
which is not local to the servlet, can access it.
• The ExampServlet class defines a doPost method with the same name, return type,
and parameter list as the doPost method in the HttpServlet class.
• By doing this, the ExampServlet class overrides and implements the doPost method
in the HttpServlet class.
Class and Method
Declarations Cont.d
• The doPost method performs the HTTP POST operation, which is the type of operation specified in the
HTML form used for this example.
• The other possibility is the HTTP GET operation, in which case you would implement the doGet method
instead.
• In short, POST requests are for sending any amount of data directly over the connection without
changing the URL, and GET requests are for getting limited amounts of information appended to the
URL.
• POST requests cannot be bookmarked or emailed and do not change the Uniform Resource Locators
(URL) of the response.
• GET requests can be bookmarked and emailed and add information to the URL of the response.
• The parameter list for the doPost method takes a request and a response object.
• The browser sends a request to the servlet and the servlet sends a response back to the browser.
• The doPost method implementation accesses information in the request object to find out who made the
request, what form the request data is in, and which HTTP headers were sent, and uses the response
object to create an HTML page in response to the browser's request.
Method Implementation
• The first part of the doPost method uses the response object to create an HTML
page.
• It first sets the response content type to be text/html, then gets a PrintWriter object
for formatted text output.
• The next line uses the request object to get the data from the text field on the form
and store it in the DATA variable.
• The getparameter method gets the named parameter, returns null if the parameter
was not set, and an empty string if the parameter was sent without a value.
• The next part of the doPost method gets the data out of the DATA parameter and
passes it to the response object to add to the HTML response page.
• The last part of the doPost method creates a link to take the end user from the
HTML response page back to the original form, and closes the response.
References
• http://www.oracle.com/technetwork/java/index-138747.html
• http://www.oracle.com/technetwork/topics/newtojava/gettingstarted-jsp-138588.html
• http://www.oracle.com/technetwork/topics/newtojava/new2java-141543.html
• https://netbeans.org/kb/index.html
• http://www.oracle.com/technetwork/java/index-jsp-135888.html
• https://docs.oracle.com/javase/tutorial/java/nutsandbolts/
• http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
• http://docs.oracle.com/javase/tutorial/
• http://www.oracle.com/technetwork/java/javase/tech/articles-jsp-139072.html
• http://docs.oracle.com/javase/tutorial/uiswing/
• http://www.oracle.com/technetwork/articles/javase/swingmenus-137771.html
• https://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java
• http://www.oracle.com/technetwork/java/index-jsp-138231.html
Next Up…
• Essentials Part 2
• File Access and Permissions
• Database Access and Permissions
• Remote Method Invocation
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg
Thank you.
Sachintha Gunasena MBCS
http://lk.linkedin.com/in/sachinthadtg

More Related Content

PPTX
Concurrency Programming in Java - 03 - Essentials of Java Part 2
PDF
Mini project in java swing
DOC
Mahesh_Mathapati
PPTX
Presentation5
PPTX
Java project
PPT
Online quiz
PPTX
Introduction to Core Java Programming
Concurrency Programming in Java - 03 - Essentials of Java Part 2
Mini project in java swing
Mahesh_Mathapati
Presentation5
Java project
Online quiz
Introduction to Core Java Programming

What's hot (20)

PPTX
Core java
PPTX
Web automation with Selenium for software engineers
PDF
Design Patterns : The Ultimate Blueprint for Software
PDF
Design patterns 1july
PDF
SQL INJECTIONS EVERY TESTER NEEDS TO KNOW
PPTX
JAVA Training Syllabus Course
PDF
prasad_kamble_cv
PPTX
Career in java
PDF
Core java course syllabus
PPTX
Online examination system
PPTX
Abstract #236765 advanced essbase java api tips and tricks
PDF
Android course session 1 ( intoduction to java )
PPTX
Automation
PPTX
Object Oriented Programming in Java
PDF
Introduction to Enterprise Applications and Tools
PPTX
Quiz managment system
PPTX
Sahi Principles and Architecture
PPTX
quiz half ppt
DOCX
Lecture1 oopj
PPT
Agile Software Development by Sencha
Core java
Web automation with Selenium for software engineers
Design Patterns : The Ultimate Blueprint for Software
Design patterns 1july
SQL INJECTIONS EVERY TESTER NEEDS TO KNOW
JAVA Training Syllabus Course
prasad_kamble_cv
Career in java
Core java course syllabus
Online examination system
Abstract #236765 advanced essbase java api tips and tricks
Android course session 1 ( intoduction to java )
Automation
Object Oriented Programming in Java
Introduction to Enterprise Applications and Tools
Quiz managment system
Sahi Principles and Architecture
quiz half ppt
Lecture1 oopj
Agile Software Development by Sencha
Ad

Similar to Concurrency Programming in Java - 02 - Essentials of Java Part 1 (20)

PPTX
PPTX
Multi Threading- in Java WPS Office.pptx
PDF
Java basics notes
PPTX
Applets
PPTX
PROGRAMMING IN JAVA- unit 4-part I
PDF
Java basics notes
PDF
Java basics notes
PDF
Java programming basics notes for beginners(java programming tutorials)
PPTX
introduction to c #
PPT
Advanced Programming, Java Programming, Applets.ppt
PPT
Java introduction
PDF
Session 3 - Object oriented programming with Objective-C (part 1)
PPTX
Design p atterns
PPT
ASP.NET Session 3
DOC
MC0078 SMU 2013 Fall session
PPTX
Java applet
PDF
Week 7 Java Programming Methods For I.T students.pdf
PPTX
Object Oriented Programming C#
PPTX
Csharp introduction
PDF
Building iOS App Project & Architecture
Multi Threading- in Java WPS Office.pptx
Java basics notes
Applets
PROGRAMMING IN JAVA- unit 4-part I
Java basics notes
Java basics notes
Java programming basics notes for beginners(java programming tutorials)
introduction to c #
Advanced Programming, Java Programming, Applets.ppt
Java introduction
Session 3 - Object oriented programming with Objective-C (part 1)
Design p atterns
ASP.NET Session 3
MC0078 SMU 2013 Fall session
Java applet
Week 7 Java Programming Methods For I.T students.pdf
Object Oriented Programming C#
Csharp introduction
Building iOS App Project & Architecture
Ad

More from Sachintha Gunasena (18)

PPTX
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
PPTX
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
PPTX
Entrepreneurship & Commerce in IT - 12 - Web Payments
PPTX
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
PPTX
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
PPTX
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
PPTX
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
PPTX
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
PPTX
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
PPTX
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
PPTX
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
PPT
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
PPT
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
PPT
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
PPT
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
PPT
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
PPT
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...
Entrepreneurship and Commerce in IT - 14 - Web Marketing Communications
Entrepreneurship and Commerce in IT - 13 - The Internet Audience, consumer be...
Entrepreneurship & Commerce in IT - 12 - Web Payments
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Entrepreneurship & Commerce in IT - 11 - Security & Encryption
Entrepreneurship & Commerce in IT - 08 - E-Commerce business models and concepts
Entrepreneurship & Commerce in IT - 10 - The Internet today and How to build ...
Entrepreneurship & Commerce in IT - 09 - The internet and the world wide web
Entrepreneurship and Commerce in IT - 07 - Introduction to E-Commerce I - e-c...
Entrepreneurship and Commerce in IT - 06 - Funding, Expanding, and Exit Strat...
Entrepreneurship and Commerce in IT - 05 - Marketing, Technology and Marketin...
Entrepreneurship & Commerce in IT - 01 - Introduction in to Entrepreneurship,...
Entrepreneurship & Commerce in IT - 02 - Basic Concepts of Entrepreneurship, ...
Entrepreneurship & Commerce in IT - 04 - Marketing Plan, Marketing 7 P's, STP...
Entrepreneurship & Commerce in IT - 03 - Writing a Business Plan, Creating a ...

Recently uploaded (20)

PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPT
Introduction Database Management System for Course Database
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
history of c programming in notes for students .pptx
PDF
System and Network Administraation Chapter 3
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
top salesforce developer skills in 2025.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
System and Network Administration Chapter 2
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
CHAPTER 2 - PM Management and IT Context
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Introduction Database Management System for Course Database
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
history of c programming in notes for students .pptx
System and Network Administraation Chapter 3
How to Migrate SBCGlobal Email to Yahoo Easily
Wondershare Filmora 15 Crack With Activation Key [2025
Upgrade and Innovation Strategies for SAP ERP Customers
Operating system designcfffgfgggggggvggggggggg
Design an Analysis of Algorithms II-SECS-1021-03
top salesforce developer skills in 2025.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Digital Systems & Binary Numbers (comprehensive )
System and Network Administration Chapter 2
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Lecture 3: Operating Systems Introduction to Computer Hardware Systems

Concurrency Programming in Java - 02 - Essentials of Java Part 1

  • 2. Essentials Part 1 Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg
  • 3. Java • Source Code • english text - understood by humans • Compiler • converts to byte codes - understood by JVM • Interpreter (Java Virtual Machine) • convert to machine code - understood by machine
  • 4. Setting up the Environment • Download and install Java SDK • Setup environmental variable • http://www.tutorialspoint.com/java/java_environment_setup.htm • Write the program in a text file and save as example.java • Open CMD and compile using • javac example.java • run the program using • java ExampleProgram
  • 6. Comments • Commenting is important • Code Comments • //comment • /* comment */ • Doc Comments • /** */ • To generate documentation for your program • to enclose lines of text for the javadoc tool to find. • The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation. • http://www.oracle.com/technetwork/java/javase/documentation/index-jsp-135444.html
  • 8. Application Structure and Elements • Class • Properties • Methods • Class will store data in a field • store text in a string field • Class will store methods to work on the data • Accessor Methods (Mutator Method) • Used to control changes to variables in accordance with Encapsulation • Setter Method - set value of a variable • Getter Method - get value of a variable
  • 9. Application Structure and Elements Cont.d • Main method • is essential • entry point to the program • code will execute first • this is the class name passed to java interpreter to run the application • public • JVM can call the main method - not protected • static • no need to create an instance • void • no data returned when run
  • 10. Application Structure and Elements Cont.d • instance of a class • executable copy of the class • need to acquire and work on data • not needed only in the main static method • static fields and methods of a class can be called by another program without creating an instance of the class • can call the static println method in the System class, without creating an instance of the System class. • a program must create an instance of a class to access its non-static fields and methods.
  • 11. Fields and Methods • Example2 program alters the first example to store the text string in a static field called text. • text field is static so its data can be accessed directly by the static call to out.println without creating an instance of the Program2 class. • example3 and example4 programs add a getText method to the program to retrieve and print the text. • example3 program accesses the static text field with the non-static getText method. • Non-static methods and fields are called instance methods and fields. • This approach requires that an instance of the Program3 class be created in the main method. • To keep things interesting, this example includes a static text field and a non-static instance method (getStaticText) to retrieve it.
  • 12. Fields and Methods Cont.d • The example4 program accesses the static text field with the static getText method. • Static methods and fields are called class methods and fields. • This approach allows the program to call the static getText method directly without creating an instance of the Program4 class. • class methods can operate only on class fields • instance methods can operate on class and instance fields. • there is only one copy of the data stored or set in a class field • each instance has its own copy of the data stored or set in an instance field. • http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
  • 13. Constructors • a special method that is called when a class instance is created. • class constructor always has the same name as the class and no return type • Program5 converts the Program4 to use a constructor to initialize the text string. • If you do not write your own constructor, the compiler adds an empty constructor, which calls the no-arguments constructor of its parent class. • The empty constructor is called the default constructor. • The default constructor initializes all non-initialized fields and variables to zero.
  • 14. More on this… • http://docs.oracle.com/javase/tutorial/java/javaOO /classvars.html
  • 16. Application to Applet • Like applications, applets are created from classes. • applets do not have a main method as an entry point • have several methods to control specific aspects of applet execution. • example6 code is the applet equivalent to the Program5 application • The SimpleApplet class is declared public so the program that runs the applet (a browser or appletviewer), which is not local to the program can access it.
  • 17. Run the Applet • HTML file with the Applet tag • easiest way to run the applet is with appletviewer where simpleApplet.html is a file that contains the above HTML code: • appletviewer simpleApplet.html • https://www.ailis.de/~k/archives/63-how-to-use-java- applets-in-modern-browsers.html
  • 18. Applet Structures & Elements • The Java API Applet class provides what you need to design the appearance and manage the behavior of an applet. • This class provides a GUI component called a Panel and a number of methods. • To create an applet, you extend (or subclass) the Applet class and implement the appearance and behavior you want. • The applet's appearance is created by drawing onto the Panel or by attaching other GUI components such as push buttons, scrollbars, or text areas to the Panel. • The applet's behavior is defined by implementing the methods.
  • 19. Extending a Class • to write a new class that can use the fields and methods defined in the class being extended. • The class being extended is the parent class, and the class doing the extending is the child class. • Another way to say this is the child class inherits the fields and methods of its parent or chain of parents. • Child classes either call or override inherited methods. This is called single inheritance.
  • 20. Extending a Class Cont.d • The SimpleApplet class extends Applet class, which extends the Panel class, which extends the Container class. • The Container class extends Object, which is the parent of all Java API classes. • The Applet class provides the init, start, stop, destroy, and paint methods you saw in the example applet. • The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. • The Applet class provides no functionality for these methods. • However, the Applet class does provide functionality for the setBackground method,which is called in the init method. • The call to setBackground is an example of calling a method inherited from a parent class in contrast to overriding a method inherited from a parent class.
  • 21. Extending a Class Cont.d • Why the Java language provides methods without implementations? • It is to provide conventions for everyone to use for consistency across Java APIs. • If everyone wrote their own method to start an applet, for example, but gave it a different name such as begin or go, the applet code would not be interoperable with other programs and browsers, or portable across multiple platforms. • For example, Netscape and Internet Explorer know how to look for the init and start methods.
  • 22. Behavior • An applet is controlled by the software that runs it. • Usually, the underlying software is a browser, but it can also be appletviewer as you saw in the example. • The underlying software controls the applet by calling the methods the applet inherits from the Applet class. • The init Method: The init method is called when the applet is first created and loaded by the underlying software. • This method performs one-time operations the applet needs for its operation such as creating the user interface or setting the font. • In the example, the init method initializes the text string and sets the background color.
  • 23. Behavior Cont.d • The start Method: The start method is called when the applet is visited such as when the end user goes to a web page with an applet on it. • The example prints a string to the console to tell you the applet is starting. • In a more complex applet, the start method would do things required at the start of the applet such as begin animation or play sounds. • After the start method executes, the event thread calls the paint method to draw to the applet's Panel. • A thread is a single sequential flow of control within the applet, and every applet can run in multiple threads. • Applet drawing methods are always called from a dedicated drawing and event-handling thread.
  • 24. Behavior Cont.d • The stop and destroy Methods: The stop method stops the applet when the applet is no longer on the screen such as when the end user goes to another web page. • The example prints a string to the console to tell you the applet is stopping. • In a more complex applet, this method should do things like stop animation or sounds. • The destroy method is called when the browser exits. • Your applet should implement this method to do final cleanup such as stop live threads.
  • 25. Appearance • The Panel provided in the Applet class inherits a paint method from its parent Container class. • To draw something onto the Applet's Panel, you implement the paint method to do the drawing. • The Graphics object passed to the paint method defines a graphics context for drawing on the Panel. • The Graphics object has methods for graphical operations such as setting drawing colors, and drawing graphics, images, and text. • The paint method for the SimpleApplet draws the text string in red inside a blue rectangle.
  • 26. Packages • The applet code also has three import statements at the top. • Applications of any size and all applets use import statements to access ready- made Java API classes in packages. • This is true whether the Java API classes come in the Java platform download, from a third-party, or are classes you write yourself and store in a directory separate from the program. • At compile time, a program uses import statements to locate and reference compiled Java API classes stored in packages elsewhere on the local or networked system. • A compiled class in one package can have the same name as a compiled class in another package. • The package name differentiates the two classes.
  • 27. Packages Cont.d • The examples in examples 1 and 2 did not need a package declaration to call the System.out.println Java API class because the System class is in the java.lang package that is included by default. • You never need an import java.lang.* statement to use the compiled classes in that package.
  • 28. More on this… • http://docs.oracle.com/javase/tutorial/
  • 30. Project Swing APIs • This expands the basic application from earlier to give it a user interface using the Java Foundation Classes (JFC) Project Swing APIs that handle user events. • the applet - user interface attached to a panel object nested in a top-level browser • the Project Swing application - user interface attached to a panel object nested in a top-level frame object. • A frame object is a top-level window that provides a title, banner, and methods to manage the appearance and behavior of the window. • The Project Swing code that follows builds this simple application. • The window on the left appears when you start the application, and the window on the right appears when you click the button. • Click again and you are back to the original window on the left.
  • 31. Import Statements • Here is the SwingUI.java code. • At the top, you have four lines of import statements. • The lines indicate exactly which Java API classes the program uses. • You could replace four of these lines with this one line: import java.awt.*;, to import the entire awt package, • but doing that increases compilation overhead than importing exactly the classes you need and no others.
  • 32. Class Declaration • The class declaration comes next and indicates the top-level frame for the application's user interface is a JFrame that implements the ActionListener interface. • The JFrame class extends the Frame class that is part of the Abstract Window Toolkit (AWT) APIs. • Project Swing extends the AWT with a full set of GUI components and services, pluggable look and feel capabilities, and assistive technology support. • The Java APIs provide classes and interfaces for you to use. • An interface defines a set of methods, but does not implement them. • The rest of the SwingUI class declaration indicates that this class will implement the ActionListener interface. • This means the SwingUI class must implement all methods defined in the ActionListener interface. • Fortunately, there is only one, actionPerformed.
  • 33. Instance Variables • These next lines declare the Project Swing component classes the SwingUI class uses. • These are instance variables that can be accessed by any method in the instantiated class. • In this example, they are built in the SwingUI constructor and accessed in the actionPerformed method implementation. • The private boolean instance variable is visible only to the SwingUI class and is used in the actionPerformedmethod to find out whether or not the button has been clicked.
  • 34. Constructor • The constructor creates the user interface components and JPanel object, adds the components to the JPanel object, adds the panel to the frame, and makes the JButton components event listeners. • The JFrame object is created in the main method when the program starts. • When the JPanel object is created, the layout manager and background color are specified. • The layout manager in use determines how user interface components are arranged on the display area. • The code uses the BorderLayout layout manager, which arranges user interface components in the five areas shown at left. • To add a component, specify the area (north, south, east, west, or center).
  • 35. Constructor Cont.d • The call to the getContentPane method of the JFrame class is for adding the Panel to the JFrame. • Components are not added directly to a JFrame, but to its content pane. • Because the layout manager controls the layout of components, it is set on the content pane where the components reside. • A content pane provides functionality that allows different types of components to work together in Project Swing.
  • 36. Action Listening • In addition to implementing the ActionListener interface, you have to add the event listener to the JButton components. • An action listener is the SwingUI object because it implements the ActionListener interface. • In this example, when the end user clicks the button, the underlying Java platform services pass the action (or event) to the actionPerformed method. • In your code, you implement the actionPerformed method to take the appropriate action based on which button is clicked.. • The component classes have the appropriate add methods to add action listeners to them. • In the code the JButton class has an addActionListener method. • The parameter passed to addActionListener is this, which means the SwingUI action listener is added to the button so button-generated actions are passed to the actionPerformed method in the SwingUI object.
  • 37. Event Handling • The actionPerformed method is passed an event object that represents the action event that occurred. • Next, it uses an if statement to find out which component had the event, and takes action according to its findings.
  • 38. Main Method • The main method creates the top-level frame, sets the title, and includes code that lets the end user close the window using the frame menu. • The code for closing the window shows an easy way to add event handling functionality to a program. • If the event listener interface you need provides more functionality than the program actually uses, use an adapter class. • The Java APIs provide adapter classes for all listener interfaces with more than one method. • This way, you can use the adapter class instead of the listener interface and implement only the methods you need. • In the example, the WindowListener interface has 7 methods and this program needs only the windowClosing method so it makes sense to use the WindowAdapter class instead.
  • 39. Main Method Cont.d • This code extends the WindowAdapter class and overrides the windowClosing method. • The new keyword creates an anonymous instance of the extended inner class. • It is anonymous because you are not assigning a name to the class and you cannot create another instance of the class without executing the code again. • It is an inner class because the extended class definition is nested within the SwingUI class. • This approach takes only a few lines of code, while implementing the WindowListener interface would require 6 empty method implementations. • Be sure to add the WindowAdapter object to the frame object so the frame object will listen for window events.
  • 41. Servelets • A servlet is an extension to a server that enhances the server's functionality. • The most common use for a servlet is to extend a web server by providing dynamic web content. • Web servers display documents written in HyperText Markup Language (HTML) and respond to user requests using the HyperText Transfer Protocol (HTTP). • HTTP is the protocol for moving hypertext files across the internet. • HTML documents contain text that has been marked up for interpretation by an HTML browser such as Netscape. • Servlets are easy to write. All you need is Tomcat, which is the combined Java Server Pages 1.1 and Servlets 2.2 reference implementation.
  • 42. About the Example • A browser accepts end user input through an HTML form. • The simple form used in this lesson has one text input field for the end user to enter text and a Submit button. • When the end user clicks the Submit button, the simple servlet is invoked to process the end user input. • In this example, the simple servlet returns an HTML page that displays the text entered by the end user.
  • 43. HTML Form • The HTML form is embedded in this HTML file. • The HTML file and form are similar to the simple application and applet examples so you can compare the code and learn how servlets, applets, and applications handle end user inputs. • When the user clicks the Click Me button, the servlet gets the entered text, and returns an HTML page with the text. • Note: To run the example, you have to put the servlet and HTML files in the correct directories for the Web server you are using. • For example, with Java WebServer 1.1.1, you place the servlet in the ~/JavaWebServer1.1.1/servlets and the HTML file in the ~/JavaWebServer1.1.1/public_html directory.
  • 44. Servlet Backend • ExampServlet.java builds an HTML page to return to the end user. • This means the servlet code does not use any Project Swing or Abstract Window Toolkit (AWT) components or have event handling code. • For this simple servlet, you only need to import these packages: • java.io for system input and output. The HttpServlet class uses the IOException class in this package to signal that an input or output exception of some kind has occurred. • javax.servlet, which contains generic (protocol-independent) servlet classes. The HttpServlet class uses the ServletException class in this package to indicate a servlet problem. • javax.servlet.http, which contains HTTP servlet classes. The HttpServlet class is in this package.
  • 45. Class and Method Declarations • All servlet classes extend the HttpServlet abstract class. • HttpServlet simplifies writing HTTP servlets by providing a framework for handling the HTTP protocol. • Because HttpServlet is abstract, your servlet class must extend it and override at least one of its methods. • An abstract class is a class that contains unimplemented methods and cannot be instantiated itself. • The ExampServlet class is declared public so the web server that runs the servlet, which is not local to the servlet, can access it. • The ExampServlet class defines a doPost method with the same name, return type, and parameter list as the doPost method in the HttpServlet class. • By doing this, the ExampServlet class overrides and implements the doPost method in the HttpServlet class.
  • 46. Class and Method Declarations Cont.d • The doPost method performs the HTTP POST operation, which is the type of operation specified in the HTML form used for this example. • The other possibility is the HTTP GET operation, in which case you would implement the doGet method instead. • In short, POST requests are for sending any amount of data directly over the connection without changing the URL, and GET requests are for getting limited amounts of information appended to the URL. • POST requests cannot be bookmarked or emailed and do not change the Uniform Resource Locators (URL) of the response. • GET requests can be bookmarked and emailed and add information to the URL of the response. • The parameter list for the doPost method takes a request and a response object. • The browser sends a request to the servlet and the servlet sends a response back to the browser. • The doPost method implementation accesses information in the request object to find out who made the request, what form the request data is in, and which HTTP headers were sent, and uses the response object to create an HTML page in response to the browser's request.
  • 47. Method Implementation • The first part of the doPost method uses the response object to create an HTML page. • It first sets the response content type to be text/html, then gets a PrintWriter object for formatted text output. • The next line uses the request object to get the data from the text field on the form and store it in the DATA variable. • The getparameter method gets the named parameter, returns null if the parameter was not set, and an empty string if the parameter was sent without a value. • The next part of the doPost method gets the data out of the DATA parameter and passes it to the response object to add to the HTML response page. • The last part of the doPost method creates a link to take the end user from the HTML response page back to the original form, and closes the response.
  • 48. References • http://www.oracle.com/technetwork/java/index-138747.html • http://www.oracle.com/technetwork/topics/newtojava/gettingstarted-jsp-138588.html • http://www.oracle.com/technetwork/topics/newtojava/new2java-141543.html • https://netbeans.org/kb/index.html • http://www.oracle.com/technetwork/java/index-jsp-135888.html • https://docs.oracle.com/javase/tutorial/java/nutsandbolts/ • http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html • http://docs.oracle.com/javase/tutorial/ • http://www.oracle.com/technetwork/java/javase/tech/articles-jsp-139072.html • http://docs.oracle.com/javase/tutorial/uiswing/ • http://www.oracle.com/technetwork/articles/javase/swingmenus-137771.html • https://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java • http://www.oracle.com/technetwork/java/index-jsp-138231.html
  • 49. Next Up… • Essentials Part 2 • File Access and Permissions • Database Access and Permissions • Remote Method Invocation Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg
  • 50. Thank you. Sachintha Gunasena MBCS http://lk.linkedin.com/in/sachinthadtg