Advanced Programming Exit Exam Tutorial With Questions
Advanced Programming Exit Exam Tutorial With Questions
Advanced Programming Exit Exam Tutorial With Questions
COURSE TUTORIAL
By
Zaheredin S.
i
Contents
Chapter One: Overview of Java Programming ....................................................................... 1
ii
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)
iii
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
● Java is simple in that it retains much familiar syntax of C++.
● 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++.
● Java is completely object-oriented.
● Java is multi-threaded, allowing a program to do more than one thing at a time.
● Network-Savvy: an extensive library of routines for coping with TCP/IP
protocols like HTTP and FTP.
● Secure and Robust: Java is intended for writing programs that are reliable and
secure in a variety of ways.
● Portable and architecture neutral.
Declaring Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
1
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
a = c;
}else
a = d;
d. if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
else
statement;
3
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
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];
5
Figure 1.1: Hierarchy of Java Exception classes
a) Errors: Errors represent irrecoverable conditions such as JVM running out of memory,
memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer and we should not try to handle them.
b) Exception: Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object. This object is called the exception object.
It contains information about the exception such as the name and description of the
exception and the state of the program when the exception occurred.
6
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) {
7
// 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 { OUTPUT
public static void divideByZero() { Trying to divide by 0
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.
8
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);
}
}
9
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.
10
Figure 2.1 - Multithreaded Server
11
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.
12
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread thread1 =new Thread(m1);
thread1.start();
}
}
13
● Synchronization Rule: When a synchronized block is encountered in a thread of
execution, the associated lock will be checked.
14
1. What is multithreaded programming?
A. It’s a process in which two different processes run simultaneously
B. It’s a process in which two or more parts of same process run simultaneously
C. It’s a process in which many different process are able to access same information
D. It’s a process in which a single process can access information from many sources
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
15
Chapter Three: Java GUI Development (SWING)
3.1 Graphical 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 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.
16
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.
Object
JLable
Component JList
JTable
Container
JComboBox
JComponen
Window Panel JSlider
JMenu
Frame Dialog Applet
AbstractButton
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)
● Inherited by Component and Container of AWT.
● They are heavyweight & other containers cannot hold it.
Lightweight Container (JPanel)
● They inherit JComponent class and used as general purpose container.
● Used to keep and organize related components together.
17
i. JFrame
● A JFrame is a subclass of Window. It has a border, menu bar, title bar.
● JFrame class has its default layout as BorderLayout.
● 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
● JDialog is a subclass of Window. JDialog class has border and title.
● 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.
● It is generic container for holding the components.
● It can have other components like button, textfield etc.
● An instance of Panel class creates a container, in which we can add components.
● Panel has FlowLayout as its default layout.
The JFrame class has the following two constructors:
● 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.
18
● 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.
import javax.swing.JFrame;
public class Simple{
public static void main(String[] args) {
JFrame f=new JFrame("EmptyFrame");
f.setSize(300,200);
f.setTitle("First JFrame");
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
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
● Buttons (JButton, JRadioButtons, JCheckBox)
● Text (JTextField, JTextArea)
● Menus (JMenuBar, JMenu, JMenuItem)
● Sliders (JSlider)
● JComboBox (uneditable) (JComboBox)
● List (JList)
Choosers
● File chooser (JFileChooser)
● Color chooser (JColorChooser)
19
Information Display Components
● Label (JLabel)
● Progress bars (JProgressBar)
● Tool tips (using JComponent's setToolTipText(s) method)
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
20
The following two steps are required to perform event handling:
a) Register a listener object with a source object
eventSourceListener.addEventListener(eventListenerObject);
b) Create the listener object. Create a class that implements that interface
class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//code to run
}
}
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.
import javax.swing.*;
class LabelExample{
public static void main(String args[]){
JFrame f= new JFrame("Label Example");
JLabel l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
21
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.
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.
22
import javax.swing.*;
class TextFieldExample{
public static void main(String args[]){
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to IT Class.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.
import javax.swing.*;
public class TextAreaExample{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea a=new JTextArea("Welcome to IT Class");
a.setBounds(10,30, 200,200);
f.add(a);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new TextAreaExample();
}
}
23
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.
24
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.
25
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
26
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.
2) Protocol
● A protocol is an organized set of communication rules that determine how data
is transmitted between devices on the same network.
● For example: TCP, FTP, Telnet, SMTP, POP etc.
3) Port Number
● The port number uniquely identifies a particular process or service on a system.
27
● It acts as a communication endpoint between applications.
● To communicate between two applications, the port number is used along with
an IP Address.
In connection-less protocol
● Acknowledgement is not sent by the receiver.
● It is not reliable but fast.
● Example of connection-less protocol is UDP.
6) Socket
● A socket is an endpoint between two way communications and it used to identify
both a machine and a service within the machine.
● It is tied to a port number so that TCP layer can recognize the application to
which data is intended to be sent.
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.
28
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
29
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.
30
● When the result is received from DB, it is sent to ODBC API and then to JDBC API.
● This Driver is platform-dependent because it uses ODBC which depends on the
native library of the OS.
● In this Type, JDBC–ODBC driver should be installed in each client system & the DB
must support ODBC driver.
31
Java
Applicatio
n
Vendor
Native API Databas
JDBC
Driver e DB
API
Library
Client Machine
Java
Applicatio
n
Network Middleware
JDBC Protocol DB
API
Driver Server Side
Client Machine
Figure 5.3 - Network Protocol Driver
32
Advantage:
o No client side library is required because of application server.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
33
Disadvantage:
o Drivers depend on the Database.
34
● 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
● This interface is used to implement simple SQL statements with no parameter.
● It returns the ResultSet object.
Statement st = conn.createStatement();
b. PreparedStatement
● This interface extends the Statement interface. So, it has more features than the
Statement interface.
● It is used to implement parameterized and precompiled SQL statements.
● Example – String s_query = “Select * from states where sid = 1”;
PreparedStatement pst = conn.prepareStatement(s_query);
c. CallableStatement
● This 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.
● Example - CallableStatement cs = con.prepareCall("{call procedures(?,?)}");
35
● The executeQuery() method in Statement interface is used to execute the SQL query
and retrieve the values from DB.
● It returns the ResultSet object, that can be used to get all the records of a table.
● 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 counts.
● We will use this method to insert/update the bulk of records.
36
● 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.
37
38
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
39