Advanced Programming Course Tutorial
Advanced Programming Course Tutorial
COURSE TUTORIAL
i
Contents
Chapter One: Overview of Java Programming ..........................................................................1
ii
iii
Course Objectives
Upon completion of this course, students should be able to:
Use Java technology data types and expressions
Use Java technology flow control constructs
Use arrays and other data collections
Error-handling techniques using exception handling
GUI using Java technology GUI components: panels, buttons, labels, text fields,
and text areas
Multithreaded programs
Java Database Connectivity (JDBC)
iv
Chapter One: Overview of Java Programming
1.1 Creation of Java
In 1991, Sun Microsystems develop a new language. It was named Java in 1995. Java is a
platform-independent language (architecture neutral). The platform-independent language
could be used to produce code that would run on a variety of CPUs under differing
environments. Programs are inbuilt with the internet for active programs.
Java Characteristics
● It is strongly typed. This means that everything must have a data type.
● Java performs its own memory management avoiding the memory leaks that
plague programs written in languages like C and C++.
● Secure and Robust: Java is intended for writing programs that are reliable and
secure in a variety of ways.
● Primitive (Basic/Simple) types: These consist of int, float, char, and Boolean.
Declaring Variable
1
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
The type is one of Java’s atomic types or the name of a class or interface. The identifier is
the name of the variable. You can initialize the variable by specifying an equal sign and a
value is called a constant variable. For Example:
2
if(j < 20) a = b;
if(k > 100)
c = d;
else
a = c;
}else
a = d;
d. if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
3
II. Loop Statement
Java’s iteration statements are for, while, and do-while. A loop repeatedly executes the same
set of instructions until a termination condition is met.
a. While Loop
Syntax: while (condition){
// body of the loop
Statement(s);
}
The body of the loop will be executed as long as the conditional expression is true. When the
condition becomes false, control passes to the next line of code immediately following the
loop.
b. do…while Loop: This loop always execute its body at least once, because its
conditional expression is at the bottom of the loop.
Syntax: do{
// body of the loop
} while (condition);
4
methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
For Example void test ()
void test (int a)
void test (int a, int b)
double test (double a)
II. Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an
array is accessed by its index.
a. One-dimensional array
Syntax: type var-name []; // Eg. double myList [];
The value of myList is set to null, which represents an array with no value. To link myList
with an actual, physical array of integers, you must allocate one using new and assign it to
myList. new is a special operator that allocates memory.
array-var = new type [size];
myList = new double [10];
b. Multidimensional array
In Java, multidimensional arrays are arrays of arrays. To declare a multidimensional array
variable, specify each additional index using another set of square brackets. It is used to
represent a table or matrix.
For example: int twoD[][] = new int [4][5];
● Device failure
5
● Code errors etc.
6
Figure 1.1: Hierarchy of Java Exception classes
7
What is“Java Exception Handling”?
The problem with the exception is, it terminates the program and skips the rest of the
execution, i.e if a program has 10 lines of code and at line 6 an exception occurs then the
program will terminate immediately by skipping the execution of the rest of 4 lines of code.
To handle a such problem, we use exception handling that avoids program termination and
continues the execution by skipping the exception code.
2. finally block
The finally block is optional. And, for each try block, there can be only one finally block. A
finally block of code is always executed whether an exception has occurred or not. It appears
at the end of the catch block.
try {
// code
} catch (ExceptionType1 e1) {
8
// code
} finally {}
3. throw and throws keyword
a) throw keyword
Used to throw a single exception explicitly. The only object of the Throwable class or its sub-
classes can be thrown. When we throw an exception, the flow of the program moves from
the try block to the catch block. Program execution stops on encountering a throw statement,
and the closest catch statement is checked for a matching type of exception.
Syntax: throw ThrowableInstance
We allow using a new operator to create an instance of the class Throwable
new ArithmeticException (“divideByZero");
This constructs an instance of ArithmeticException with the name divideByZero. In the
following example, the divideByZero () method throw an instance of ArithmeticException,
which is successfully handled using the catch statement, and thus, the program prints the
output "Trying to divide by 0".
Example: Exception handling using Java throw
class Main {
public static void divideByZero() {
try {
throw new ArithmeticException("divideByZero");
} catch(ArithmeticException e) {
System.out.println("Trying to divide by 0”);
}
}
public static void main(String[] args) {
divideByZero();
}
}
b) throws keyword
throws keyword used to declare the list of exceptions that a method may throw during the
execution of the program. Any method that is capable of causing exceptions must list all the
exceptions possible during its execution so that anyone calling that method gets prior
knowledge about which exceptions are to be handled.
9
Syntax: type method_name (parameters) throws exception_list {
// definition of the method
}
// Declaring the type of exception
public static void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
}catch (IOException e) {
System.out.println(e);
}
}
10
Chapter Two: Multithreading in Java
2.1 Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of the CPU. Java Multithreading is mostly used in games,
animation, etc. A multithreading program contains two or more parts of a program that can
run concurrently. Each part of a program is called a thread. So, a thread is a lightweight
smallest part of a process that can run concurrently with other threads of the same process.
Threads are independent because they all have a separate path of execution that’s the reason
if an exception occurs in one thread, it doesn’t affect the execution of other threads. Every
Java program has at least one thread – called the main thread. All threads of a process share a
common memory. JVM manages those threads and schedules them for execution.
● Runnable (ready): In this stage, the instance of the thread is invoked with a
start method.
● Running: When the thread gets the CPU, it moves from the runnable to the
running state.
iii. Waiting (Non-Runnable/Blocked)
A thread enters this state when it is temporarily in inactive state. i.e., it is still alive but is not
eligible to run. It can be in a waiting, sleeping, or blocked state.
iv. Dead (terminated)
12
A thread is terminated due to the following reasons: Either its run() method exists normally,
i.e., the thread’s code has executed the program. Or due to some unusual errors like
segmentation fault or an unhandled exception.
13
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread thread1 =new Thread(m1);
thread1.start();
}
}
○ MIN_PRIORITY (default is 1)
○ NORM_PRIORITY (default is 5)
In any Thread the default priority is NORM_PRIORITY.
14
Synchronization is a programming technique that involves 3 elements:
15
4. One Major disadvantage of the java synchronized keyword is that it doesn't allow
concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock.
5. Java synchronized keyword incurs a performance cost.
6. You cannot apply java synchronized keywords with variables.
3. What will happen if two thread of the same priority are called to be processed
simultaneously?
A. Anyone will be executed first lexographically
B. Both of them will be executed simultaneously
C. None of them will be executed
D. It is dependent on the operating system
16
A. run() method calls start() method and runs the code
B. run() method creates new thread
C. run() method can be called directly without start() method being called
D. start() method creates new thread and calls code written in run() method
17
Chapter Three: Java GUI Development (SWING)
3.1Graphical User Interface (GUI)
GUI refers to an interface that allows one to interact with electronic devices like computers
and tablets through graphic elements. GUI uses icons, menus and other graphical
representations to display information, as opposed to text-based commands. GUIs are built
from GUI components. These are sometimes called controls or widgets. A GUI component is
an object with which the user interacts via the mouse, the keyboard or another form of input,
such as voice recognition. It plays an important role to build easy interfaces for Java
applications.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS. It is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc. In addition, AWT is adequate for many
applications but it is difficult to build an attractive GUI.
B. Swing
It is designed to solve AWT’s problems (since Java 2). The components of the Swing library
are easier to work with and are much better implemented. It is 99% java; It is lightweight
components as drawing of components is done in java. It is a part of Java Foundation Classes
(JFC) that is used to create window-based applications. JFC are a set of GUI components
which simplify the development of desktop applications. Swing GUI components allow you
18
to specify a uniform look-and-feel for your application across all platforms. It also lays out
consistently on all OSs. Some Swing components need classes from the AWT library.
It has much bigger set of built-in components and uses AWT event handling. Swing classes
are located in Swing is built “on top of” AWT, so you need to import AWT and use a few
things from it.
Swing is bigger and slower.
Swing is more flexible and better looking.
Swing and AWT are incompatible. Thus, you can use either, but you can’t mix them.
package javax.swing.
As seen from the above hierarchy we have Container classes – Frame, Dialog, Panel, Applet,
etc. There are also Component classes derived from the JComponent class of Swing API.
Some of the classes that inherit from JComponent are JLabel, JList, JTextBox, etc.
1. Containers
In Java, Containers are divided into two types
Top-level Container (JFrame, JDialog, JApplet)
19
● They inherit JComponent class and used as general purpose container.
i. JFrame
● It can hold all other components like button, text field, checkboxes, scrollbar etc.
● JFrame is the most commonly used container while developing Swing application.
ii. JDialog
● To create a dialog object, an instance of the associated JFrame class is always needed.
iii. JPanel
● The JPanel is the container that doesn't contain title bar, border or menu bar.
● JFrame(): This constructor constructs a new frame with no title and it is initially
invisible.
● JFrame (String title): This constructor constructs a new, initially invisible frame
with specified title.
● void setSize(int width, int height): to specify the size of the frame.
● void setLocation(int x, int y): to specify the upper left corner location of the frame.
20
JFrame.HIDE_ON_CLOSE: Hide the frame, but keep the application
running.
JFrame.DO_NOTHING_ON_CLOSE: Ignore the click.
● void setVisible(boolean b): to show or hide the frame depending on the value of
parameter b.
● void setBounds(int x, int y, int width, int height): to specifies the size of the frame
and the location of the upper left corner.
● void setTitle(String title): to set the title for the frame by the specified string.
2. JComponent
The JComponent class is the base class of all Swing components except top-level containers.
Swing components whose names begin with "J" are descendants of the JComponent class.
For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don't inherit
JComponent class because they are the child of top-level containers.
Here is a list of controls in the javax.swing package.
Input Components
● Sliders (JSlider)
21
● JComboBox (uneditable) (JComboBox)
● List (JList)
Choosers
● Label (JLabel)
● Tables (JTable)
● Trees (JTree)
● It has two major requirements. First, it must have been registered with one or
more sources to receive notifications about specific types of events.
● The methods that receive and process events are defined in a set of interfaces
found in java.awt.event.
22
The java.awt.event package provides many event classes and Listener interfaces for event
handling.
Some Java Event classes and Listener interfaces
ActionEvent ActionListener
TextEvent TextListener
3. JLabel
A label is a display area for a short text (a non-editable), an image, or both.
A JLabel component can be created using one of the following constructors:
o JLabel(): Creates a default label with no text and icon.
o JLabel(String text): Creates a label with text.
o JLabel(Icon icon): Creates a label with an icon.
o JLabel(String text, int horizontalAlignment): Creates a label with a text and the
specified horizontal alignment.
o JLabel(Icon icon, int horizontalAlignment): Creates a label with an icon and the
specified horizontal alignment.
o JLabel(String text, Icon icon, int horizontalAlignment): Creates a label with text,
an icon, and the specified horizontal alignment.
23
4. JButton
A button is a component that triggers an action event when clicked.
A Jbutton component can be created using one of the following constructors.
o JButton(): Creates a default button with no text and icon.
o JButton(Icon icon): Creates a button with an icon.
o JButton(String text): Creates a button with text.
o JButton(String text, Icon icon): Creates a button with text and an icon.
5. JTextField
A text field is a box that contains a line of text. The user can type text into the box and the
program can get it and then use it as data. The program can write the results of a calculation
to a text field. Text fields are useful in that they enable the user to enter in variable data (such
as a name or a description). JTextField is swing class for an editable text display.
24
6. JTextArea
JTextArea class, enables the user to enter multiple lines of text.
JTextArea components can be created using one of the following constructors:
o JTextArea(int rows, int columns): creates a text area with the specified number
of rows and columns.
o JTextArea(String s, int rows, int columns): creates a text area with the initial
text and the number of rows and columns specified.
25
3.2 Layout Management
Layouts tell Java where to put components in containers (JPanel, content pane, etc.). Layout
manager is created using LayoutManager class. Every layout manager class implements the
LayoutManager class. Each layout manager has a different style of positioning components.
If you don't specify otherwise, the container will use a default layout manager. Every panel
(and other container) has a default layout, but it's better to set the layout explicitly for clarity.
Layout managers are set in containers using the setLayout(LayoutManager) method.
● If we are going to add controls inside this container and if we are interested on the
flowlayout, we can set as follow.
26
B. Java FlowLayout
FlowLayout is the Simplest and the default layout manager for every JPanel. It simply lays
out components in a single row one after the other.
C. Java GridLayout
The GridLayout manager divides the container up into a given number of rows and columns.
All sections of the grid are equally sized and as large as possible.
27
1. Give the abbreviation of AWT?
A. Applet Windowing Toolkit C. Absolute Windowing Toolkit
B. Abstract Windowing Toolkit D. None of the above
3. Implement the Listener interface and overrides its methods is required to perform in
event handling.
A. True B. False
4. Which is the container that doesn't contain title bar and MenuBars but it can have other
components like button, textfield etc.
A. Window B. Frame C. Panel D. Container
5. The Java Foundation Classes (JFC) is a set of GUI components which simplify the
development of desktop applications.
A. True B. False
6. Which are passive controls that do not support any interaction with the user?
A. Choice B. List C. Labels D. Checkbox
7. Which package provides many event classes and Listener interfaces for event handling?
A. java.awt B. java.awt.Graphics C. java.awt.event D. None
28
Chapter Four: Java Networking
4.1 Java Networking
Java Networking is a concept of connecting two or more computing devices together to share
the resources. Java socket programming provides facility to share data between different
computing devices. Java Program communicates over the network at the application layer.
java.net package is useful for all the Java networking classes and
interfaces. java.net package encapsulate large number of classes and interface that provides
an easy-to use means to access network resources.
● Sharing resources
2) Protocol
29
3) Port Number
● To communicate between two applications, the port number is used along with
an IP Address.
● A network node can have multiple Network Interface Controller(NIC) but each
with unique MAC address.
In connection-less protocol
6) Socket
● It is tied to a port number so that TCP layer can recognize the application to
which data is intended to be sent.
30
In Socket Programming, Socket and ServerSocket classes are used for connection-oriented,
and DatagramSocket and DatagramPacket classes are used for connection-less socket
programming. ServerSocket class is for servers and Socket class is for the client.
The client in socket programming must know two information: IP Address of Server, and
Port number.
1. Which of the following protocol follows connection less service?
A. TCP B. TCP/IP C. UDP D. HTTP
2. Which of the following statement is NOT true?
A. TCP is a reliable but slow.
B. UDP is not reliable but fast.
C. File Transfer Protocol (FTP) is a standard Internet protocol for transmitting files
between computers on the Internet over TCP/IP connections.
D. In HTTP, all communication between two computers are encrypted
4. Which class is used to create servers that listen for either local client or remote client
programs?
A. ServerSocketsB. httpServer C. httpResponse D. None
5. Which classes are used for connection-less socket programming?
A. DatagramSocket B. DatagramPacket C. Both A & B D. None
31
Chapter Five: Java Database Connectivity (JDBC)
5.1 Java Database Connectivity (JDBC)
In most Java applications, there is always a need to interact with databases to retrieve,
manipulate, and process the data. For this purpose, Java JDBC has been introduced. So that,
JDBC is an API (Application programming interface) used for interacting with databases in
Java programming. By using JDBC, we can interact with different types of Relational
Databases such as Oracle, MySQL, MS Access, Sybase etc.
Before JDBC, ODBC API was introduced to connect and perform operations with the
database. ODBC uses an ODBC driver which is platform-dependent because it was written in
the C programming language. But, JDBC API that written in Java language, is platform-
independent, and makes Java platform-independent itself.
JDBC API uses JDBC drivers to connect with the database, and it acts as an interface
between the Java program and Database.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database.
The java.sql package contains classes and interfaces for JDBC API.
● In this type of Driver, JDBC–ODBC Bridge act as an interface between client and
database (DB) server.
● When a user uses Java application to send requests to the database using JDBC–
ODBC Bridge, it first converts the JDBC API to ODBC API and then sends it to the
database.
32
● When the result is received from DB, it is sent to ODBC API and then to JDBC API.
● In this Type, JDBC–ODBC driver should be installed in each client system & the
DB must support ODBC driver.
● It is similar to Type I Driver. Here, the ODBC part is replaced with native code in
Type II Driver. This native code part is targeted at a specific database product.
● This Driver converts the JDBC method calls to native C/C++ method calls of the
database native API.
● When the database gets the requests from the user, the requests are processed and
sent back with the results in the native format which are to be converted to JDBC
format and give it to the Java application.
● This type of driver gives faster response and performance than the Type I driver.
33
34
Figure 5.2 - Native API Driver
Advantage:
o Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
● The type III driver is fully written in Java. It is like a 3-tier approach to access the
database.
● It sends the JDBC method calls to an intermediate server. On behalf of the JDBC,
the intermediate server communicates with the database.
● The Application server (intermediate or middle – tier) converts the JDBC calls
either directly or indirectly to the vendor-specific Database protocol.
● Thin driver is directly implemented that converts JDBC calls directly into vendor-
specific Database protocol.
● Today, most of the JDBC Drivers are type IV drivers. It is written fully in Java and
thus it is platform-independent.
● It is installed inside the JVM (Java Virtual Machine) of the client, so you don’t have
to install any software on the client or server-side.
● This driver architecture has all the logic to communicate directly with the DB in a
single driver.
● It provides better performance than the other type of drivers. It allows for easy
deployment.
36
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
● Irrespective of the JDBC Driver, add the following import statement in the Java
program. import java.sql.*;
● This package provides classes and interfaces to perform most of the JDBC
functions like creating and executing SQL queries.
37
Step 4 - Create Statement and Execute SQL queries
● 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.
ii. Create Statement
In order to send the SQL commands to database from our java program, we need Statement
object. We can get the Statement object by calling the createStatement() method
on connection.
There are 3 Statement interfaces are available in the java.sql package.
a. Statement
b. PreparedStatement
● This interface extends the Statement interface. So, it has more features than the
Statement interface.
c. CallableStatement
38
There are 4 important methods to execute the query in Statement interface.
a. ResultSet executeQuery(String sql)
● It returns the ResultSet object, that can be used to get all the records of a table.
b. executeUpdate(String sql)
c. execute(String sql)
● 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 counts.
● 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 = st.executeQuery(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”.
39
● 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.
● 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.
● Finally, we need to make sure that we have closed the resource after we have used it.
● When we close the Connection object, Statement and ResultSet objects will be
closed automatically.
conn.close();
40
41
1. What is JDBC?
A. JDBC is a java based protocol.
B. JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
C. JDBC is a specification to tell how to connect to a database.
D. Joint Driver for Basic Connection
3. Which of the following type of JDBC driver, is also called Type 2 JDBC driver?
A. JDBC-ODBC Bridge plus ODBC driver
B. Native-API, partly Java driver
C. JDBC-Net, pure Java driver
D. Native-protocol, pure Java driver
4. Which of the following holds data retrieved from a database after you execute an SQL
query using Statement objects.
A. ResultSet B. JDBC driver C. Connection D. Statement
5. Which of the following type of JDBC driver, uses database native protocol?
A. JDBC-ODBC Bridge plus ODBC driver C. JDBC-Net, pure Java driver
B. Native-API, partly Java driver D. Native-protocol, pure Java driver
6. Which driver converts JDBC calls directly into the vendor-specific database protocol?
A. Native - API driver C. Thin driver
B. Network Protocol driver D. Both B & C
42