AJ unit I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 198

Unit:1

1. BASICS OF JAVA

1.1 Review of Java Fundamentals

Java programming language was originally developed by Sun Microsystems which


was initiated by James Gosling and released in 1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.

Java is −

• Object Oriented − In Java, everything is an Object. Java can be easily


extended since it is based on the Object model.
• Platform Independent − Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into platform
specific machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
• Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
• Secure − With Java's secure feature it enables to develop virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
• Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
• Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.
• Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
• Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
• Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.
• High Performance − With the use of Just-In-Time compilers, Java enables
high performance.
• Distributed − Java is designed for the distributed environment of the internet.
• Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.

Hello World using Java Programming.


Just to give you a little excitement about Java programming, I'm going to give you a
small conventional C Programming Hello World program, You can try it using Demo
link.

publicclassMyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

publicstaticvoidmain(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called 'Oak' after an oak tree that stood
outside Gosling's office, also went by the name 'Green' and ended up later being
renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.

Tools You Will Need


For performing the examples discussed in this tutorial, you will need a Pentium 200-
MHz computer with a minimum of 64 MB of RAM (128 MB of RAM
recommended).

You will also need the following softwares −

• Linux 7.1 or Windows xp/7/8 operating system


• Java JDK 8
• Microsoft Notepad or any other text editor

This tutorial will provide the necessary skills to create GUI, networking, and web
applications using Java.

What is Next?
The next chapter will guide you to how you can obtain Java and its documentation.
Finally, it instructs you on how to install Java and prepare an environment to develop
Java applications.

Java - Environment Setup


Live Demo Option Online
We have set up the Java Programming environment online, so that you can compile
and execute all the available examples online. It gives you confidence in what you are
reading and enables you to verify the programs with different options. Feel free to
modify any example and execute it online.
Try the following example using Live Demo option available at the top right corner of
the below sample code box −

publicclassMyFirstJavaProgram {
publicstaticvoidmain(String []args) {
System.out.println("Hello World");
}
}

For most of the examples given in this tutorial, you will find a Try it option in our
website code sections at the top right corner that will take you to the online compiler.
So just make use of it and enjoy your learning.

Local Environment Setup


If you want to set up your own environment for Java programming language, then this
section guides you through the whole process. Please follow the steps given below to
set up your Java environment.

Java SE is available for download for free. To download click here, please download a
version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your
machine. Once you have installed Java on your machine, you would need to set
environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP


Assuming you have installed Java in c:\Program Files\java\jdk directory −

• Right-click on 'My Computer' and select 'Properties'.


• Click on the 'Environment variables' button under the 'Advanced' tab.
• Now, edit the 'Path' variable and add the path to the Java executable directory at
the end of it. For example, if the path is currently set
to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME


Assuming you have installed Java in c:\Program Files\java\jdk directory −
• Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD


Environment variable PATH should be set to point to where the Java binaries have
been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at
the end of your .bashrc −

export PATH=/path/to/java:$PATH'

Popular Java Editors


To write Java programs, you need a text editor. There are even more sophisticated
IDEs available in the market. The most popular ones are briefly described below −

• Notepad − On Windows machine, you can use any simple text editor like
Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free
text editor which enhanced facilities.
• Netbeans − It is a Java IDE that is open-source and free which can be
downloaded from www.netbeans.org/index.html.
• Eclipse − It is also a Java IDE developed by the Eclipse open-source
community and can be downloaded from www.eclipse.org.

IDE or Integrated Development Environment, provides all common tools and


facilities to aid in programming, such as source code editor, build tools and debuggers
etc.

1.2 What is an Event Handling and describe


the components in Event Handling in Java?
The GUI in Java processes the interactions with users via mouse, keyboard and various user
controls such as button, checkbox, text field, etc. as the events. These events are to be handled
properly to implement Java as an Event-Driven Programming.
Components in Event Handling
• Events
• Event Sources
• Event Listeners/Handlers

Events
• The events are defined as an object that describes a change in the state of a source object.
• The Java defines a number of such Event Classes inside java.awt.event package
• Some of the events are ActionEvent, MouseEvent, KeyEvent, FocusEvent,
ItemEvent and etc.

Event Sources
• A source is an object that generates an event.
• An event generation occurs when an internal state of that object changes in some way.
• A source must register listeners in order for the listeners to receive the notifications about a
specific type of event.
• Some of the event sources are Button, CheckBox, List, Choice, Window and etc.

Event Listeners
• A listener is an object that is notified when an event occurs.
• A Listener has two major requirements, it should be registered to one more source object
to receiving event notification and it must implement methods to receive and process
those notifications.
• Java has defined a set of interfaces for receiving and processing the events under
the java.awt.event package.
• Some of the listeners
are ActionListener, MouseListener, ItemListener, KeyListener, WindowListener and
etc.

Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclassEventListenerTestextendsJFrameimplementsActionListener{
JButton button;
publicstaticvoid main(String args[]){
EventListenerTestobject=newEventListenerTest();
object.createGUI();
}
void createGUI(){
button=newJButton(" Click Me !");
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(button);
button.addActionListener(this);
}
publicvoid actionPerformed(ActionEvent ae){
if(ae.getSource()== button){
JOptionPane.showMessageDialog(null,"Generates an Action Event");
}
}
}

Output

1.3 Thread Concept in Java


Before introducing the thread concept, we were unable to run more than one task in parallel. It
was a drawback, and to remove that drawback, Thread Concept was introduced.
A Thread is a very light-weighted process, or we can say the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used the Thread concept in Java.
All the tasks are executed without affecting the main program. In a program or process, all the
threads have their own separate path for execution, so each thread of a process is independent.

Another benefit of using thread is that if a thread gets an exception or an error at the time of its
execution, it doesn't affect the execution of the other threads. All the threads share a common
memory and have their own stack, local variables and program counter. When multiple threads
are executed in parallel at the same time, this process is known as Multithreading.

In a simple way, a Thread is a:

o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Thread Model
Just like a process, a thread exists in several states. These states are as follows:
1) New (Ready to run)

A thread is in New when it gets CPU time.

2) Running

A thread is in a Running state when it is under execution.

3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under execution.

4) Blocked

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution immediately.

Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by
extending the Thread class. These are the only two ways through which we can create a thread.

Let's dive into details of both these way of creating a thread:

Thread Class
A Thread class has several methods and constructors which allow us to perform various
operations on a thread. The Thread class extends the Object class. The Object class implements
the Runnable interface. The thread class has the following constructors that are used to perform
various operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)


The Runnable interface is required to be implemented by that class whose instances are intended
to be executed by a thread. The runnable interface gives us the run() method to perform an
action for the thread.

start() method
The method is used for starting a thread that we have newly created. It starts a new thread with a
new callstack. After executing the start() method, the thread changes the state from New to
Runnable. It executes the run() method when the thread gets the correct time to execute it.

Let's take an example to understand how we can create a Java thread by extending the Thread
class:

ThreadExample1.java

1. // Implementing runnable interface by extending Thread class


2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.
4. public void run()
5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. System.out.println("Thread started running..");
10. System.out.println("Sum of two numbers is: "+ result);
11. }
12. public static void main( String args[] )
13. {
14. // Creating instance of the class extend Thread class
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. t1.start();
18. }
19. }

Output:

Creating thread by implementing the runnable interface


In Java, we can also create a thread by implementing the runnable interface. The runnable
interface provides us both the run() method and the start() method.

Let's takes an example to understand how we can create, start and run the thread using the
runnable interface.

ThreadExample2.java

1. class NewThread implements Runnable {


2. String name;
3. Thread thread;
4. NewThread (String name){
5. this.name = name;
6. thread = new Thread(this, name);
7. System.out.println( "A New thread: " + thread+ "is created\n" );
8. thread.start();
9. }
10. public void run() {
11. try {
12. for(int j = 5; j > 0; j--) {
13. System.out.println(name + ": " + j);
14. Thread.sleep(1000);
15. }
16. }catch (InterruptedException e) {
17. System.out.println(name + " thread Interrupted");
18. }
19. System.out.println(name + " thread exiting.");
20. }
21. }
22. class ThreadExample2 {
23. public static void main(String args[]) {
24. new NewThread("1st");
25. new NewThread("2nd");
26. new NewThread("3rd");
27. try {
28. Thread.sleep(8000);
29. } catch (InterruptedException excetion) {
30. System.out.println("Inturruption occurs in Main Thread");
31. }
32. System.out.println("We are exiting from Main Thread");
33. }
34. }

Output:
1.4 Java Networking
Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.
Java socket programming provides facility to share data between different computing devices.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management
Do You Know ?
o How to perform connection-oriented Socket Programming in networking ?
o How to display the data of any online web page ?
o How to get the IP address of any host name e.g. www.google.com ?
o How to perform connection-less socket programming in networking ?
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the
sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes
Java Networking Terminology
The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed
of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication
endpoint between applications.
The port number is associated with the IP address for communication between two applications.

4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.

6) Socket
A socket is an endpoint between two way communications.

Visit next page for Java socket programming.

java.net package
The java.net package can be divided into two sections:

1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers,
Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network
interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the
resource pointed by URLs.

The java.net package provides many classes to deal with networking applications in Java. A list
of these classes is given below:

o Authenticator
o CacheRequest
o CacheResponse
o ContentHandler
o CookieHandler
o CookieManager
o DatagramPacket
o DatagramSocket
o DatagramSocketImpl
o InterfaceAddress
o JarURLConnection
o MulticastSocket
o InetSocketAddress
o InetAddress
o Inet4Address
o Inet6Address
o IDN
o HttpURLConnection
o HttpCookie
o NetPermission
o NetworkInterface
o PasswordAuthentication
o Proxy
o ProxySelector
o ResponseCache
o SecureCacheResponse
o ServerSocket
o Socket
o SocketAddress
o SocketImpl
o SocketPermission
o StandardSocketOptions
o URI
o URL
o URLClassLoader
o URLConnection
o URLDecoder
o URLEncoder
o URLStreamHandler

List of interfaces available in java.net package:

o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily

What we will learn in Networking Tutorial


o Networking and Networking Terminology
o Socket Programming (Connection-oriented)
o URL class
o Displaying data of a webpage by URLConnection class
o InetAddress class
o DatagramSocket and DatagramPacket (Connection-less)

1.5 Media with JavaFX


Modern world's rich internet applications must be capable to play and edit the media files when
required. JavaFX provides the media-rich API that can play audio and video on the user's
demand.

JavaFX Media API enables the users to incorporate audio and video into the rich internet
applications (RIAs). JavaFX media API can distribute the media content across the different
range of devices like TV, Mobile, Tablets and many more.

In this part of the tutorial, we will discuss the capability of JavaFX to deal with the media files in
an interactive way. For this purpose, JavaFX provides the package javafx.scene.media that
contains all the necessary classes. javafx.scene.media contains the following classes.

1. javafx.scene.media.Media
2. javafx.scene.media.MediaPlayer
3. javafx.scene.media.MediaStatus
4. javafx.scene.media.MediaView
Media Events
The JavaFX team have designed media API to be event driven. The callback behaviour attached
with the media functions are used to handle media events. Instead of typing code for a button via
a EventHandler, a code is implemented that responds to the triggering of the media player's
OnXXXX events where XXXX is the event name.

java.lang.Runnable functional interfaces are used as the callbacks which are invoked when an
event is encountered. When playing the media content in javafx, we would create the Lambda
expressions (java.lang.Runnable interfaces) to be set on the onReady event. Consider the
following example.

1. Media media = new Media(url);


2. MediaPlayer mediaPlayer = new MediaPlayer(media);
3. Runnable playMusic = () -> mediaPlayer.play();
4. mediaPlayer.setOnReady(playMusic);

The playMusic variable is assigned to a lambda expression. This get passed into the Media
player's setOnReady() method. The Lambda expression will get invoked when the onReady
event is encountered.

Possible media and media-player events are discussed in the following table.

Class Set On Method Description

Media setOnError() This method is invoked when an error occurs. It is the part of the class
Media.

MediaPlayer setOnEndOfMedia() The method is invoked when end of the media play is reached.

MediaPlayer setOnError() This method is invoked when an error occurs.

MediaPlayer setOnHalted() This method is invoked when the status of media changes to halted.

MediaPlayer setOnMarker() This method is invoked when the Marker event is triggered.

MediaPlayer setOnPaused() This method is invoked when a pause event occurs.

MediaPlayer setOnPlaying() This method is invoked when the play event occurs.

MediaPlayer setOnReady() This method is invoked when the media is in ready state.

MediaPlayer setOnRepeat() This method is invoked when the repeat property is set.
MediaPlayer setOnStalled() This method is invoked when the media player is stalled.

MediaPlayer setOnStopped() This method is invoked when the media player has stopped.

MediaView setOnError() This method is invoked when an error occurs in the media view.

We must notice that MediaPlayer class contains the most number of events triggered while
MediaView and Media classes contains one event each.

javafx.scene.media.Media class
The properties of the class are described in the following table. All the properties are the read
only except onError.

Property Description

duration The duration of the source media in seconds. This property is of object type of the class
Duration.

error This is a property set to media exception value when an error occurs. This property is of the
type object of the class MediaException.

height The height of the source media in pixels. This is an integer type property.

onError The event handler which is called when the error occurs. The method setOnError() is used
to set this property.

width The width of the source media in pixels. This is an integer type property

Constructors
There is a single constructor in the table.

public Media(java.lang.String source): it instantiate the class Media with the specified source
file.

JavaFX.scene.media.MediaPlayer class
The properties of the class along with the setter methods are described in the following table.

Property Property Setter Methods


audioSpectrumInterval This is a double type property. setAudioSpectrumInterval (double value)
It indicates the interval between
the spectrum updates in
seconds.

audioSpectrumListener This is an object type property setAudioSpectrumListener(AudioSpectrumListen


of the class listener)
AudioSpectrumListener. It
indicates the
audiospectrumlistener for an
audio spectrum.

audioSpectrumNumBands This is an integer type property. setAudioSpectrumNumBands(int value)


It indicates the number of bands
between the audio spectrum.

audioSpectrumThreshold This is an integer type property. setAudioSpectrumThreshold(int value)


It indicates the sensitivity
threshold

autoPlay This is the boolean type setAutoPlay(Boolean value)


property. The true value
indicates the playing will be
started as soon as possible.

balance This is a double type property. setBalance(double value)


It indicates the balance of the
audio output.

bufferProgressTime This is an object type property Can not be set as it is read only property.
of the class Duration. It
indicates the duration of the
media which can be played
without stalling the media-
player.

currentCount This is read only integer type Can not be set as it is read only property.
property. It indicates the
number of completed playback
cycles.

currentRate This is a double type property. Can not be set as it is read only property.
It indicates the current rate of
the playback. It is read only
property.
currentTime This is an object type property Can not be set as it is read only property.
of the class Duration. It
indicates the current media
playback time.

cycleCount It is the integer type property. It setCycleCount(int value)


indicates the number of times,
the media will be played.

cycleDuration It is the ready only property. It Can not be set as it is read only property.
is of the type object of the class
Duration. It indicates the
amount of time between the
start time and stop time of the
media.

error It is a read only property. It is Can not be set as it is read only property.
an object type property of the
class MediaException. It is set
to a Media-Exception if an error
occurs.

mute It is a boolean type property. It SetMute(boolean value)


indicates whether the audio is
muted or not.

onEndOfMedia It is an object type property of setOnEndOfMedia(java.lang.Runnable value)


the interface Runnable. It is set
to an Event Handler which will
be invoked when the end of the
media file is reached.

onError It is an object type property of setOnHalted(java.lang.Runnable value)


the interface Runnable. It
indicates the Event Handler
which will be invoked when the
status changes to halted.

onMarker It is an object type property of setOnMarker(EventHandler<MediaMarkerEvent>


the class MediaMarkerEvent. It onMarker )
indicates the EventHandler
which will be invoked when the
current time reaches the media
marker.

onPaused It is an object type property of setOnPaused(java.lang.Runnable value)


the interface Runnable. It
indicates the EventHandler
which will be invoked when the
status changed to paused.

onPlaying It is an object type property of setOnPlaying(java.lang.Runnable value)


the interface Runnable. It
indicates the EventHandler
which will be invoked when the
status changed to playing.

onReady It is an object type property of setOnReady(java.lang.Runnable value)


the interface Runnable. It
indicates the EventHandler
which will be invoked when the
status changed to Ready.

onRepeat It is an object type property of setOnRepeat(java.lang.Runnable value)


the class MediaMarkerEvent. It
indicates the EventHandler
which will be invoked when the
current time reaches the stop
time and will be repeating.

onStalled It is an object type property of setOnStalled(java.lang.Runnable value)


the interface Runnable. It
indicates the Event Handler
which will be invoked when the
status changed to Stalled.

onStopped It is an object type property of setOnStopped(java.lang.Runnable value)


the interface Runnable. It
indicates the EventHandler
which will be invoked when the
status changed to Stopped.

rate It is the double type property. It setRate(double value)


indicates the rate at which the
media should be played.

startTime This property is of the type setStartTime(Duration value)


object of the class Duration. It
indicates the time where media
should start playing.
status This is the read only property. It Can not be set as it is read only property.
indicates the current state of the
Media player.

stopTime This property is an object type setStopTime(double value)


of the class Duration. It
indicates the time offset where
the media should stop playing.

totalDuration It is an object type property of Can not be set as it is read only property.
the class Duration. It indicates
the total time during which the
media should be played.

volume It is a double type property. It setVolume(double value)


indicates the volume at which
the media should be playing.

Constructors
The class contains only a single constructor which is given below.

1. public MediaPlayer (Media media)

UNIT 1
5 mark
1. Components and event handling
2. Media techniques
10 mark
1. Threading concepts
2. Networking features

Advance Java MCQs

UNIT 1
1.
Among the following options choose the one which shows the advantage of using the JDBC connection pool.
Using less memory
Better performance
Slower performance
Using more memory
Hide
Wrong Answer
Answer: B) The advantage of using a JDBC connection pool is better performance.
2.
Among the following which contains date information.
java.sql timestamp
java.io time
java.io.timestamp
java.sql.time
Hide
Wrong Answer
Answer: A) java.sql timestamp contains date information.
3.
Identify the method of the JDBC process among the following options.
remove()
deletebatch()
setbatch()
addbacth()
Hide
Wrong Answer
Answer: D) addbatch() Is the method of JDBC.
4.
The total JDBC product components in Java software provides is ___________
2
3
4
5
Hide
Wrong Answer
Answer: B)The total JDBC product components in Java software provides is 3.
5.
Total JDBC drivers available is _____________
2
3
4
5
Hide
Wrong Answer
Answer: C) Total JDBC drivers available is 4.
6.
Where can BLOB, CLOB, ARRAY, and REF type columns be updated?
JDBC 1.0
JDBC 2.0
JDBC 3.0
JDBC 4.0
Hide
Wrong Answer
Answer: C) BLOB, CLOB, ARRAY, and REF type columns be updated in JDBC 3.0
7.
Which driver is known as the thin driver in JDBC?
Type 1 driver
Type 2 driver
Type 3 driver
Type 4 driver
Hide
Wrong Answer
Answer: D) Type 4 driver is known as the thin driver in JDBC.
Start Your Coding Journey With Tracks
Master Data Structures and Algorithms with our Learning Tracks

Topic Buckets

Mock Assessments

Reading Material
8.
TCP, FTP, SMTP, Telnet are examples of?
IP address
Protocol
Socket
MAC address
Hide
Wrong Answer
Answer: B) TCP FTP Telnet, SMTP are examples of protocols.
9.
Identify the class used for connection-less socket programming.
Datagram packet
Datagram socket
Both A and B
None of the above
Hide
Wrong Answer
Answer: C) Both datagram packet and datagram socket is used for connection-less socket programming
10.
Total TCP/IP ports reserved for specific protocol is._______
1024
2048
512
32
Hide
Wrong Answer
Answer: A) Total TCP/IP ports reserved for specific protocol is 1024.
11.
What is the total number of bits in a single IP address?
4
8
16
32
Hide
Wrong Answer
Answer: D) The total number of bits in a single IP address is 32.
12.
Which of the following option leads to the portability and security of Java?
Dynamic binding between objects
Use of exception handling
Bytecode is executed by JVM
The applet makes the Java code secure and portable
Hide
Wrong Answer
Answer: C) Bytecode is executed by JVM is the correct answer.

Discover your path to a Successful Tech Career For FREE!


Answer 4 simple questions & get a career plan tailored for you

Interview Process

CTC & Designation

Projects on the Job


13.
What are the major components of the JDBC?
DriverManager, Statement, and ResultSet
DriverManager, Driver, Connection, Statement, and ResultSet
DriverManager, Connection, Statement, and ResultSet
DriverManager, Driver, Connection, and Statement
Hide
Wrong Answer
Answer: B)The major components of JDBC are - DriverManager, Driver, Connection, Statement, and ResultSet.
14.
Which is responsible for getting a connection to the database?
Connection
Statement
ResultSet
Driver
Hide
Wrong Answer
Answer: D) Driver is responsible for getting a connection to the database.
15.
In which file database table configuration is stored?
.sql
.ora
.hbm
.dbm
Hide
Wrong Answer
Answer: C) Database table configuration file is stored in .hbm
16.
How constructor can be used for a servlet?
Initialization and Constructor function
Setup() method
Initialization
Constructor function
Hide
Wrong Answer
Answer: A) Constructor can be used for a servlet by Initialization and a Constructor function.
17.
Identify the method which is used to start a server thread.
start thread()
run()
runthread()
start()
Hide
Wrong Answer
Answer: B) run() is used to start a server thread.
18.
Identify the method which is used to find the URL from the cache of httpd.
getfromcache()
findfromcache()
findcache()
servefromcache()
Hide
Wrong Answer
Answer: D) servefromcache() is used to find the URL from the cache of httpd.
19.
Choose the instance variable of class httpd among the following.
Cache
Port
Log
All of the above
Hide
Wrong Answer
Answer: D) All of the above are instances variable of class httpd.
20.
Among the following which method is used to know the host of an URL?
findhost()
gethost()
locatehost()
host()
Hide
Wrong Answer
Answer: B) gethost() is used to know the host of an URL.
21.
Which of the following ways is used to communicate from an applet to servlet?
HTTP communication
Socket communication
RMI communication
All of the above
Hide
Wrong Answer
Answer: D) All of the above is used to communicate from an applet to the servlet.
22.
Which tag is used to execute Java source code in JSP?
Expression tag
Scriptlet tag
Declaration tag
None of the above
Hide
Wrong Answer
Answer: B) Scriptlet tag is used to execute Java source code in JSP.
23.
Which of the following access modifiers provides the widest scope of visibility for a class member in Java?
private
protected
default
public
Hide
Wrong Answer
Answer: D) public
24.
What is the purpose of the finally block in a Java try-catch-finally construct?
To catch and handle exceptions thrown in the try block
To execute code regardless of whether an exception is thrown or not
To define the conditions for handling exceptions
To provide an alternate code path when an exception occurs
Hide
Wrong Answer
Answer: B) To execute code regardless of whether an exception is thrown or not.
25.
Total ways to perform exception handling in JSP is ________
2
3
4
5
Hide
Wrong Answer
Answer: A) There are 2 Ways to perform exception handling in JSP.
26.
Which of the following tags does the JSP page contain?
JSP tags
HTML tags
Both A and C
None of the above
Hide
Wrong Answer
Answer: C) JSP page contains both JSP tags and HTML tags.
27.
Full form of JDBC is __________
Java database Communications
Java database concept
Java database connectivity
None of the above
Hide
Wrong Answer
Answer: C) JDBC stands for Java database connectivity
28.
Which of the following requires fewer resources?
Process
Thread
Both Thread and Process
Neither read nor process
Hide
Wrong Answer
Answer: B) Thread requires fewer resources.
29.
What decides the priority of the thread?
Thread
Process scheduler
Process
Thread scheduler
Hide
Wrong Answer
Answer: B) Thread scheduler will decide the priority of the thread.
30.
Among the following which is a type of multitasking?
Thread based
Process-based
Both A and B
None of the above
Hide
Wrong Answer
Answer: C) Both A and B are types of multitasking.
31.
What is the RMI server responsible for?
Exporting remote object
Creating an instance of the remote of
Binding an instance of the remote object building to the RMI registry.
All of the above
Hide
Wrong Answer
Answer: D) RMI service is responsible for all of the given options.
32.
RMI stands for __________
Remote Memory Interface
Remote Method Invocation
Random Method Invocation
None of the above
Hide
Wrong Answer
Answer: B) RMI stands for Remote Method Invocation.
33.
What is built on top of socket programming?
RMI
EJB
Both A and B
None of the above
Hide
Wrong Answer
Answer: A) RMI is built on top of socket programming.
34.
Identify among the following which follows the connectionless service.
HTTP
TCP/IP
TCP
UDP
Hide
Wrong Answer
Answer: D) UDP follows the connectionless service.
35.
Among the following protocols are used for splitting and sending packets to an address across a network.
SMTP
TCP/IP
UDP
FTP
Hide
Wrong Answer
Answer: B) TCP/IP .is used for splitting and sending packets to an address across a network.
36.
What is the total number of ResultSet available with the JDBC 2.0 core API?
2
3
4
5
Hide
Wrong Answer
Answer: B) The total number of ResultSet available with the JDBC 2.0 core API is 3.
37.
Choose whether true or false: The ResultsSet.next method is used to move the next row of the ResultSet,
making the current row
True
False
Hide
Wrong Answer
Answer: A) The above statement is true.
38.
Choose whether true or false: JDBC is a Java API that is used to connect and execute queries to the
database.
True
False
Hide
Wrong Answer
Answer: A) The above statement is true.
39.
Among the following identify the packages which represent interfaces and classes for servlet API.
javax.servelet.http
javax.servelet
Both A and B
None of the above
Hide
Wrong Answer
Answer: C) Both a and b are correct.
40.
Identify the HTTP request method which is non-idempotent.
POST
GET
Both A and B
None of the above
Hide
Wrong Answer
Answer: C) Both POST and GET are non-idempotent.
41.
Which of the following examples of application servers?
JBoss
Tomcat
Apache
WebLogic
Hide
Wrong Answer
Answer: A) JBoss is an example of an application server
42.
The total number of techniques used in session tracking is ________
3
4
5
6
Hide
Wrong Answer
Answer: B) Total 4 techniques used in session tracking.
43.
Identify the Microsoft solution for providing dynamic web content.
ASP
JSP
Both A and B
None of the above
Hide
Wrong Answer
Answer: A) JSP is used for providing dynamic web content.
44.
What is the difference between servlet and JSP?
Compilation
Translation
Syntax
Both A and B
Hide
Wrong Answer
Answer: C) The major difference between servlet and JSP is syntax.
45.
Among the following which is not a directive?
Page
Include
Tag
Export
Hide
Wrong Answer
Answer: D) Export is not the directive
46.
Choose whether true or false: The JDBC API is what allows access to a data source from a java middle
tier.
True
False
Hide
Wrong Answer
Answer: A) The above statement is true.
47.
For resolving Facelet views, which of the following is configured.
View_Resolver
View-resolver
ViewResolver
ViewFacelets
Hide
Wrong Answer
Answer: C) ViewResolver is configured for resolving Facelet views.
48.
Among the following methods which of the following returns proxy object.
getDatabase()
get()
load()
loadDatabase()
Hide
Wrong Answer
Answer: C) load() Is the method that returns a proxy object.
49.
Among the following which attribute is used to specify the class name of the bean.
id
class
name
constructor-args
Hide
Wrong Answer
Answer: B) class is used to specify the class name of the pin.
50.
Choose whether true or false: The web server is used for loading the init() method of the servlet.
True
False
Hide
Wrong Answer
Answer: A) The above statement is true.
Unit:2

1. REMOTE METHOD INVOCATION

1.1 RMI (Remote Method Invocation)


2. Remote Method Invocation (RMI)
3. Understanding stub and skeleton
1. stub
2. skeleton
4. Requirements for the distributed applications
5. Steps to write the RMI program
6. RMI Example

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.

The RMI provides remote communication between the applications using two
objects stub and skeleton.

Understanding stub and skeleton


RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's understand
the stub and skeleton objects:

stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons

Understanding requirements for the distributed applications


If any application performs these tasks, it can be distributed application.

1. The application need to locate the remote method


2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

Java RMI Example


The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application,
both client and server interacts with the remote interface. The client application invokes methods
on the proxy object, RMI sends the request to the remote JVM. The return value is sent back to
the proxy object and then to the client application.

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that
extends the Remote interface. There is only one method named add() and it declares
RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing the implementation of
the Remote interface, we need to

o Either extend the UnicastRemoteObject class,


o or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

3) create the stub and skeleton objects using the rmic tool.

Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.

1. rmic AdderRemote

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't specify the port number,
it uses a default port number. In this example, we are using the port number 5000.

1. rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object. The Naming class provides 5 methods.

public static java.rmi.Remote lookup(java.lang.String) throws It returns the reference of the


java.rmi.NotBoundException, java.net.MalformedURLException, remote object.
java.rmi.RemoteException;

public static void bind(java.lang.String, java.rmi.Remote) throws It binds the remote object with the
java.rmi.AlreadyBoundException, java.net.MalformedURLException, given name.
java.rmi.RemoteException;

public static void unbind(java.lang.String) throws java.rmi.RemoteException, It destroys the remote object
java.rmi.NotBoundException, java.net.MalformedURLException; which is bound with the given
name.

public static void rebind(java.lang.String, java.rmi.Remote) throws It binds the remote object to the
java.rmi.RemoteException, java.net.MalformedURLException; new name.

public static java.lang.String[] list(java.lang.String) throws It returns an array of the names of


java.rmi.RemoteException, java.net.MalformedURLException; the remote objects bound in the
registry.

In this example, we are binding the remote object by the name sonoo.

1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
6) Create and run the client application
At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the remote
object from another machine, change the localhost to the host name (or IP address) where the
remote object is located.

1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }

download this example of rmi

1. For running this rmi example,


2.
3. 1) compile all the java files
4.
5. javac *.java
6.
7. 2)create stub and skeleton object by rmic tool
8.
9. rmic AdderRemote
10.
11. 3)start rmi registry in one command prompt
12.
13. rmiregistry 5000
14.
15. 4)start the server in another command prompt
16.
17. java MyServer
18.
19. 5)start the client application in another command prompt
20.
21. java MyClient

Output of this RMI example


Meaningful example of RMI application with database
Consider a scenario, there are two applications running in different machines. Let's say
MachineA and MachineB, machineA is located in United States and MachineB in India.
MachineB want to get list of all the customers of MachineA application.

Let's develop the RMI application by following the steps.

1) Create the table

First of all, we need to create the table in the database. Here, we are using Oracle10 database.
2) Create Customer class and Remote interface
File: Customer.java

1. package com.javatpoint;
2. public class Customer implements java.io.Serializable{
3. private int acc_no;
4. private String firstname,lastname,email;
5. private float amount;
6. //getters and setters
7. }

Note: Customer class must be Serializable.


File: Bank.java

1. package com.javatpoint;
2. import java.rmi.*;
3. import java.util.*;
4. interface Bank extends Remote{
5. public List<Customer> getCustomers()throws RemoteException;
6. }

3) Create the class that provides the implementation of Remote interface


File: BankImpl.java

1. package com.javatpoint;
2. import java.rmi.*;
3. import java.rmi.server.*;
4. import java.sql.*;
5. import java.util.*;
6. class BankImpl extends UnicastRemoteObject implements Bank{
7. BankImpl()throws RemoteException{}
8.
9. public List<Customer> getCustomers(){
10. List<Customer> list=new ArrayList<Customer>();
11. try{
12. Class.forName("oracle.jdbc.driver.OracleDriver");
13. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle")
;
14. PreparedStatement ps=con.prepareStatement("select * from customer400");
15. ResultSet rs=ps.executeQuery();
16.
17. while(rs.next()){
18. Customer c=new Customer();
19. c.setAcc_no(rs.getInt(1));
20. c.setFirstname(rs.getString(2));
21. c.setLastname(rs.getString(3));
22. c.setEmail(rs.getString(4));
23. c.setAmount(rs.getFloat(5));
24. list.add(c);
25. }
26.
27. con.close();
28. }catch(Exception e){System.out.println(e);}
29. return list;
30. }//end of getCustomers()
31. }

4) Compile the class rmic tool and start the registry service by rmiregistry tool
5) Create and run the Server
File: MyServer.java

1. package com.javatpoint;
2. import java.rmi.*;
3. public class MyServer{
4. public static void main(String args[])throws Exception{
5. Remote r=new BankImpl();
6. Naming.rebind("rmi://localhost:6666/javatpoint",r);
7. }}

6) Create and run the Client


File: MyClient.java

1. package com.javatpoint;
2. import java.util.*;
3. import java.rmi.*;
4. public class MyClient{
5. public static void main(String args[])throws Exception{
6. Bank b=(Bank)Naming.lookup("rmi://localhost:6666/javatpoint");
7.
8. List<Customer> list=b.getCustomers();
9. for(Customer c:list){
10. System.out.println(c.getAcc_no()+" "+c.getFirstname()+" "+c.getLastname()
11. +" "+c.getEmail()+" "+c.getAmount());
12. }
13.
14. }}

2.2 Distributed Architecture


In distributed architecture, components are presented on different platforms and
several components can cooperate with one another over a communication network in
order to achieve a specific objective or goal.

• In this architecture, information processing is not confined to a single machine


rather it is distributed over several independent computers.
• A distributed system can be demonstrated by the client-server architecture
which forms the base for multi-tier architectures; alternatives are the broker
architecture such as CORBA, and the Service-Oriented Architecture (SOA).
• There are several technology frameworks to support distributed architectures,
including .NET, J2EE, CORBA, .NET Web services, AXIS Java Web services,
and Globus Grid services.
• Middleware is an infrastructure that appropriately supports the development
and execution of distributed applications. It provides a buffer between the
applications and the network.
• It sits in the middle of system and manages or supports the different
components of a distributed system. Examples are transaction processing
monitors, data convertors and communication controllers etc.
Middleware as an infrastructure for distributed system

The basis of a distributed architecture is its transparency, reliability, and availability.

The following table lists the different forms of transparency in a distributed system −

Sr.No. Transparency & Description

Access
1 Hides the way in which resources are accessed and the differences in data
platform.

Location
2
Hides where resources are located.

Technology
3 Hides different technologies such as programming language and OS from
user.

Migration / Relocation
4
Hide resources that may be moved to another location which are in use.

Replication
5
Hide resources that may be copied at several location.

Concurrency
6
Hide resources that may be shared with other users.

Failure
7
Hides failure and recovery of resources from user.
Persistence
8
Hides whether a resource ( software ) is in memory or disk.

Advantages
• Resource sharing − Sharing of hardware and software resources.
• Openness − Flexibility of using hardware and software of different vendors.
• Concurrency − Concurrent processing to enhance performance.
• Scalability − Increased throughput by adding new resources.
• Fault tolerance − The ability to continue in operation after a fault has
occurred.

Disadvantages
• Complexity − They are more complex than centralized systems.
• Security − More susceptible to external attack.
• Manageability − More effort required for system management.
• Unpredictability − Unpredictable responses depending on the system
organization and network load.

Centralized System vs. Distributed System

Criteria Centralized system Distributed System

Economics Low High

Availability Low High

Complexity Low High

Consistency Simple High

Scalability Poor Good

Technology Homogeneous Heterogeneous

Security High Low

Client-Server Architecture
The client-server architecture is the most common distributed system architecture
which decomposes the system into two major subsystems or logical processes −
• Client − This is the first process that issues a request to the second process i.e.
the server.
• Server − This is the second process that receives the request, carries it out, and
sends a reply to the client.

In this architecture, the application is modelled as a set of services that are provided
by servers and a set of clients that use these services. The servers need not know about
clients, but the clients must know the identity of servers, and the mapping of
processors to processes is not necessarily 1 : 1

Client-server Architecture can be classified into two models based on the functionality
of the client −

Thin-client model
In thin-client model, all the application processing and data management is carried by
the server. The client is simply responsible for running the presentation software.

• Used when legacy systems are migrated to client server architectures in which
legacy system acts as a server in its own right with a graphical interface
implemented on a client
• A major disadvantage is that it places a heavy processing load on both the
server and the network.

Thick/Fat-client model
In thick-client model, the server is only in charge for data management. The software
on the client implements the application logic and the interactions with the system
user.

• Most appropriate for new C/S systems where the capabilities of the client
system are known in advance
• More complex than a thin client model especially for management. New
versions of the application have to be installed on all clients.

Advantages
• Separation of responsibilities such as user interface presentation and business
logic processing.
• Reusability of server components and potential for concurrency
• Simplifies the design and the development of distributed applications
• It makes it easy to migrate or integrate existing applications into a distributed
environment.
• It also makes effective use of resources when a large number of clients are
accessing a high-performance server.

Disadvantages
• Lack of heterogeneous infrastructure to deal with the requirement changes.
• Security complications.
• Limited server availability and reliability.
• Limited testability and scalability.
• Fat clients with presentation and business logic together.

Multi-Tier Architecture (n-tier Architecture)


Multi-tier architecture is a client–server architecture in which the functions such as
presentation, application processing, and data management are physically separated.
By separating an application into tiers, developers obtain the option of changing or
adding a specific layer, instead of reworking the entire application. It provides a
model by which developers can create flexible and reusable applications.

The most general use of multi-tier architecture is the three-tier architecture. A three-
tier architecture is typically composed of a presentation tier, an application tier, and a
data storage tier and may execute on a separate processor.

Presentation Tier
Presentation layer is the topmost level of the application by which users can access
directly such as webpage or Operating System GUI (Graphical User interface). The
primary function of this layer is to translate the tasks and results to something that
user can understand. It communicates with other tiers so that it places the results to the
browser/client tier and all other tiers in the network.

Application Tier (Business Logic, Logic Tier, or Middle Tier)


Application tier coordinates the application, processes the commands, makes logical
decisions, evaluation, and performs calculations. It controls an application’s
functionality by performing detailed processing. It also moves and processes data
between the two surrounding layers.

Data Tier
In this layer, information is stored and retrieved from the database or file system. The
information is then passed back for processing and then back to the user. It includes
the data persistence mechanisms (database servers, file shares, etc.) and provides API
(Application Programming Interface) to the application tier which provides methods
of managing the stored data.

Advantages

• Better performance than a thin-client approach and is simpler to manage than a


thick-client approach.
• Enhances the reusability and scalability − as demands increase, extra servers
can be added.
• Provides multi-threading support and also reduces network traffic.
• Provides maintainability and flexibility

Disadvantages

• Unsatisfactory Testability due to lack of testing tools.


• More critical server reliability and availability.
Broker Architectural Style
Broker Architectural Style is a middleware architecture used in distributed computing
to coordinate and enable the communication between registered servers and clients.
Here, object communication takes place through a middleware system called an object
request broker (software bus).

• Client and the server do not interact with each other directly. Client and server
have a direct connection to its proxy which communicates with the mediator-
broker.
• A server provides services by registering and publishing their interfaces with
the broker and clients can request the services from the broker statically or
dynamically by look-up.
• CORBA (Common Object Request Broker Architecture) is a good
implementation example of the broker architecture.

Components of Broker Architectural Style


The components of broker architectural style are discussed through following heads −

Broker

Broker is responsible for coordinating communication, such as forwarding and


dispatching the results and exceptions. It can be either an invocation-oriented service,
a document or message - oriented broker to which clients send a message.

• It is responsible for brokering the service requests, locating a proper server,


transmitting requests, and sending responses back to clients.
• It retains the servers’ registration information including their functionality and
services as well as location information.
• It provides APIs for clients to request, servers to respond, registering or
unregistering server components, transferring messages, and locating servers.

Stub

Stubs are generated at the static compilation time and then deployed to the client side
which is used as a proxy for the client. Client-side proxy acts as a mediator between
the client and the broker and provides additional transparency between them and the
client; a remote object appears like a local one.

The proxy hides the IPC (inter-process communication) at protocol level and performs
marshaling of parameter values and un-marshaling of results from the server.
Skeleton

Skeleton is generated by the service interface compilation and then deployed to the
server side, which is used as a proxy for the server. Server-side proxy encapsulates
low-level system-specific networking functions and provides high-level APIs to
mediate between the server and the broker.

It receives the requests, unpacks the requests, unmarshals the method arguments, calls
the suitable service, and also marshals the result before sending it back to the client.

Bridge

A bridge can connect two different networks based on different communication


protocols. It mediates different brokers including DCOM, .NET remote, and Java
CORBA brokers.

Bridges are optional component, which hides the implementation details when two
brokers interoperate and take requests and parameters in one format and translate
them to another format.

Broker implementation in CORBA

CORBA is an international standard for an Object Request Broker – a middleware to


manage communications among distributed objects defined by OMG (object
management group).
Service-Oriented Architecture (SOA)
A service is a component of business functionality that is well-defined, self-contained,
independent, published, and available to be used via a standard programming
interface. The connections between services are conducted by common and universal
message-oriented protocols such as the SOAP Web service protocol, which can
deliver requests and responses between services loosely.

Service-oriented architecture is a client/server design which support business-driven


IT approach in which an application consists of software services and software service
consumers (also known as clients or service requesters).

Features of SOA
A service-oriented architecture provides the following features −

• Distributed Deployment − Expose enterprise data and business logic as


loosely, coupled, discoverable, structured, standard-based, coarse-grained,
stateless units of functionality called services.
• Composability − Assemble new processes from existing services that are
exposed at a desired granularity through well defined, published, and standard
complaint interfaces.
• Interoperability − Share capabilities and reuse shared services across a
network irrespective of underlying protocols or implementation technology.
• Reusability − Choose a service provider and access to existing resources
exposed as services.

SOA Operation
The following figure illustrates how does SOA operate −

Advantages

• Loose coupling of service–orientation provides great flexibility for enterprises


to make use of all available service recourses irrespective of platform and
technology restrictions.
• Each service component is independent from other services due to the stateless
service feature.
• The implementation of a service will not affect the application of the service as
long as the exposed interface is not changed.
• A client or any service can access other services regardless of their platform,
technology, vendors, or language implementations.
• Reusability of assets and services since clients of a service only need to know
its public interfaces, service composition.
• SOA based business application development are much more efficient in terms
of time and cost.
• Enhances the scalability and provide standard connection between systems.
• Efficient and effective usage of ‘Business Services’.
• Integration becomes much easier and improved intrinsic interoperability.
• Abstract complexity for developers and energize business processes closer to
end users.

Defining Remote objects


RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication


between Java programs. It is provided in the package java.rmi.

Architecture of an RMI Application


In an RMI application, we write two programs, a server program (resides on the
server) and a client program (resides on the client).

• Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
• The client program requests the remote objects on the server and tries to invoke
its methods.

The following diagram shows the architecture of an RMI application.


Let us now discuss the components of this architecture.

• Transport Layer − This layer connects the client and the server. It manages
the existing connection and also sets up new connections.
• Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
• Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the remote object.
• RRL(Remote Reference Layer) − It is the layer which manages the references
made by the client to the remote object.

Working of an RMI Application


The following points summarize how an RMI application works −

• When the client makes a call to the remote object, it is received by the stub
which eventually passes this request to the RRL.
• When the client-side RRL receives the request, it invokes a method
called invoke() of the object remoteRef. It passes the request to the RRL on
the server side.
• The RRL on the server side passes the request to the Skeleton (proxy on the
server) which finally invokes the required object on the server.
• The result is passed all the way back to the client.

Marshalling and Unmarshalling


Whenever a client invokes a method that accepts parameters on a remote object, the
parameters are bundled into a message before being sent over the network. These
parameters may be of primitive type or objects. In case of primitive type, the
parameters are put together and a header is attached to it. In case the parameters are
objects, then they are serialized. This process is known as marshalling.

At the server side, the packed parameters are unbundled and then the required method
is invoked. This process is known as unmarshalling.

RMI Registry
RMI registry is a namespace on which all server objects are placed. Each time the
server creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods). These are registered using a unique name known
as bind name.

To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name
(using lookup() method).

The following illustration explains the entire process −

Goals of RMI
Following are the goals of RMI −
• To minimize the complexity of the application.
• To preserve type safety.
• Distributed garbage collection.
• Minimize the difference between working with local and remote objects.

Serialization and Deserialization in Java


1. Serialization
2. Serializable Interface
3. Example of Serialization
4. Example of Deserialization
5. Serialization with Inheritance
6. Externalizable interface
7. Serialization and static data member

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is


mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted


into an object. The serialization and deserialization process is platform-independent, it means
you can serialize an object on one platform and deserialize it on a different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and
for deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface by
default.

Let's see the example given below:

Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream. The main class implementation of is showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.

Constructor

1) public ObjectOutputStream(OutputStream out) throws It creates an ObjectOutputStream that writes to the


IOException {} specified OutputStream.

Important Methods

Method Description

1) public final void writeObject(Object obj) throws It writes the specified object to the
IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} It flushes the current output stream.

3) public void close() throws IOException {} It closes the current output stream.

ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that reads from the
IOException {} specified InputStream.

Important Methods

Method Description

1) public final Object readObject() throws IOException, It reads an object from the input
ClassNotFoundException{} stream.
2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above code. The
writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object. We are saving the state of the object in the file named f.txt.

Persist.java

1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

Output:

success
download this example of serialization

Example of Java Deserialization


Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object.
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object.

Depersist.java

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Output:

211 ravi
Building distributed applications is difficult because you must take into account several issues, such as partial
failure, increased latency, distributed persistence, and language compatibility.

The JavaSpaces technology is a simple and powerful high-level tool for building distributed and collaborative
applications. Based on the concept of shared network-based space that serves as both object storage and
exchange area, it provides a simple API that is easy to learn and yet expressive for building sophisticated
distributed applications.

This article provides a fast-track tutorial to the JavaSpaces technology, including

• An introduction to distributed computing


• An introduction to the JavaSpaces technology
• A comparison of JavaSpaces technology and databases
• A description of JavaSpaces services and operations
• The JavaSpaces technology application model
• The JavaSpaces technology programming model
• A flavor of the effort involved in developing applications using JavaSpaces technology
Distributed Computing
Distributed computing is about building network-based applications as a set of processes that are distributed
across a network of computing nodes (or hosts) that work together to solve a problem. The advantages of
building applications using this approach are many, including performance, resource sharing, scalability, and
fault tolerance. But using distributed technologies does not guarantee these advantages. The developer must
take special care in the design and implementation or distributed applications in order to achieve such benefits.

The network environment on top of which you build distributed applications introduce complexities that are
not of concern when you write stand-alone applications. The most obvious complexity is the varied
architecture of machines. However, Java technology's platform independence and its virtual machine allow for
applications that you write once and run anywhere. Other issues that have significant impact on designing and
implementing distributed applications include latency, synchronization, and partial failure.

Several technologies can be used to build distributed applications, including low-level sockets, message
passing, and remote method invocation (RMI). The JavaSpaces technology model is different in that it
provides persistent object exchange areas (or spaces) through which remote Java technology processes
coordinate actions and exchange data. Such an approach can simplify the design and implementation of
sophisticated distributed applications, and it enables you to deal with the challenges of designing and
implementing distributed applications.

The JavaSpaces Technology


The JavaSpaces technology is a high-level tool for building distributed applications, and it can also be used as
a coordination tool. A marked departure from classic distributed models that rely on message passing or RMI,
the JavaSpaces model views a distributed application as a collection of processes that cooperate through the
flow of objects into and out of one or more spaces. This programming model has its roots in Linda, a
coordination language developed by Dr. David Gelernter at Yale University. However, no knowledge of Linda
is required to understand and use JavaSpaces technology.

The JavaSpaces service specification lists the following design goals for the JavaSpaces technology:

• It should provide a platform that simplifies the design and implementation of distributed computing
systems.
• The client side should have few classes, both to keep the client simple and to speed the downloading of
client classes.
• The client side should have a small footprint because it will run on computers with limited local memory.
• A variety of implementations should be possible.
• It should be possible to create a replicated JavaSpaces service.
JavaSpaces Technology vs. Databases
As mentioned earlier, a space is a shared network-accessible repository for objects: The data you can store
there is persistent and later searchable. But a JavaSpaces service is not a relational or object database.
JavaSpaces services are not used primarily as data repositories. They are designed for a different purpose than
either relational or object databases.
Although a JavaSpaces service functions somewhat like a file system and somewhat like a database, it is
neither. The key differences between JavaSpaces technology and databases are the following:

• Relational databases understand the data they store and manipulate it directly through query languages such
as SQL. JavaSpaces services, on the other hand, store entries that they understand only by type and the
serialized form of each field. As a result, there are no general queries in the JavaSpaces application design,
only "exact match" or "don't care" for a given field.
• Object databases provide an object-oriented image of stored data that can be modified and used, almost as
if it were transient memory. JavaSpaces systems do not provide a nearly transparent persistent or transient
layer, and they work only on copies of entries.
JavaSpaces Services and Operations
Application components (or processes) use the persistent storage of a space to store objects and to
communicate. The components coordinate actions by exchanging objects through spaces; the objects do not
communicate directly. Processes interact with a space through a simple set of operations.

You can invoke four primary operations on a JavaSpaces service:

• write(): Writes new objects into a space


• take(): Retrieves objects from a space
• read(): Makes a copy of objects in a space
• notify: Notifies a specified object when entries that match the given template are written into a space
Both the read() and take() methods have variants: readIfExists() and takeIfExists(). If they are called with a zero
timeout, then they are equivalent to their counterpart. The timeout parameter comes into effect only when a
transaction is used.
Each operation has parameters that are entries. Some are templates, which are a kind of entry.
The write() operation is a store operation. The read() and take() operations are a combination of search and
fetch operations. The notify method sets up repeated search operations as entries are written to the space. If
a take() or read() operation doesn't find an object, the process can wait until an object arrives.
Unlike conventional object stores, objects are passive data. Therefore, processes do not modify objects in the
space or invoke their methods directly. In order to modify an object, a process must explicitly remove, update,
and reinsert it into the space.

How can we build sophisticated distributed applications with only a handful of operations? The space itself
provides a set of key features.

The JavaSpaces Technology Application Model


A JavaSpaces service holds entries, each of which is a typed group of objects expressed in a class that
implements the interface net.jini.core.entry.Entry. Once an entry is written into a JavaSpaces service, it can be
used in future look-up operations. Looking up entries is performed using templates, which are entry objects
that have some or all of their fields set to specified values that must be matched exactly. All remaining fields,
which are not used in the lookup, are left as wildcards.
There are two look-up operations: read() and take(). The read() method returns either an entry that matches the
template or an indication that no match was found. The take() method operates like read(), but if a match is
found, the entry is removed from the space. Distributed events can be used by requesting a JavaSpaces service
to notify you when an entry that matches the specified template is written into the space. Note that each entry
in the space can be taken at most once, but two or more entries may have the exact same values.
Using JavaSpaces technology, distributed applications are modeled as a flow of objects between participants,
which is different from classic distributed models such as RMIs. Figure 1 indicates what a JavaSpaces
technology-based application looks like.
Figure 1: A Typical JavaSpaces Technology Application
As you can see, a client can interact with as many JavaSpaces services as needed. Clients perform operations
that map entries to templates onto JavaSpaces services. Such operations can be singleton or contained in a
transaction so that all or none of the operations take place. Notifications go to event catches, which can be
either clients or proxies for clients.

To get a flavor of how to implement distributed applications using a handful of JavaSpaces operations,
consider a multiuser chat system. All the messages that make up the discussion are written to a space that acts
as a chat area. Participants write message objects into the space, while other members wait for new message
objects to appear, then read them out and display their contents. The list of participants can be kept in the space
and updated whenever someone joins or leaves the discussion. Because the space is persistent, a new member
can read and view the entire discussion.

You can implement such a multiuser chat system in RMI by creating remote interfaces for the interactions
discussed. But by using JavaSpaces technology, you need only one interface.

The JavaSpaces Technology Programming Model


All operations are invoked on an object that implements the net.jini.space.JavaSpace interface. A space stores
entries, each of which is a collection of typed objects that implements the Entry interface. Code Sample 1
shows a MessageEntry that contains one field: content, which is null by default. Information on how to compile
and run the sample application appears later in this article.
Code Sample 1: MessageEntry.java
Copy

Copied to Clipboard

Error: Could not Copy

import net.jini.core.entry.*;
public class MessageEntry implements Entry {
public String content;

public MessageEntry() {
}

public MessageEntry(String content) {


this.content = content;
}

public String toString() {


return "MessageContent: " + content;
}
}
MessageEntryspace
Copy

Copied to Clipboard

Error: Could not Copy

JavaSpace space = getSpace();


MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
space.write(msg, null, Lease.FOREVER);
nullTransaction
The write() operation places a copy of an entry into the given JavaSpace service, and the Entry passed is not
affected by the operation. Each write() operation places a new Entry into the space even if the
same Entry object is used in more than one write().
Entries written in a space are governed by a renewable lease. If you like, you can change the lease (when
the write() operation is invoked) to one hour as follows: >
space.write(msg, null, 60 * 60 * 1000);

write()Lease
Once the entry exists in the space, any process with access to the space can perform a read() on it. To read an
entry, a template is used, which is an entry that may have one or more of its fields set to null. An entry matches
a template if (a) the entry has the same type as or is a subtype of the template and (b) if for every specified
non- null field in the template, their fields match exactly. The null fields act as wildcards and match any value.
The following code segment shows how to create a template and perform a read() on the space:
Copy

Copied to Clipboard

Error: Could not Copy

MessageEntry template = new MessageEntry();


MessageEntry output = (MessageEntry) space.read(template, null, Long.MAX_VALUE);
null MessageEntry Long.MAX_VALUE read() take() readIfExists()
Code Sample 2 shows the client that discovers the JavaSpace service, writes a message into the space, and then
reads it. Instructions on how to compile and run this sample application appear later in this article.

Code Sample 2: SpaceClient.java


Copy
Copied to Clipboard

Error: Could not Copy

import net.jini.space.JavaSpace;

public class SpaceClient {


public static void main(String argv[]) {
try {
MessageEntry msg = new MessageEntry();
msg.content = "Hello there";
System.out.println("Searching for a JavaSpace...");

Lookup finder = new Lookup(JavaSpace.class);


JavaSpace space = (JavaSpace) finder.getService();
System.out.println("A JavaSpace has been discovered.");
System.out.println("Writing a message into the space...");
space.write(msg, null, 60*60*1000);
MessageEntry template = new MessageEntry();
System.out.println("Reading a message from the space...");
MessageEntry result = (MessageEntry) space.read(template, null, Long.MAX_VALUE);
System.out.println("The message read is: "+result.content);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Transactions
The JavaSpaces API uses the package net.jini.core.transaction to provide basic atomic transactions that group
multiple operations across multiple JavaSpaces services into a bundle that acts as a single atomic operation.
Either all modifications within the transactions will be applied or none will, regardless of whether the
transaction spans one or more operations or one or more JavaSpaces services. Note that transactions can span
multiple spaces and participants in general.
A read(), write(), or take() operation that has a null transaction acts as if it were in a committed transaction that
contained that operation. As an example, a take() with a null transaction parameter performs as if a transaction
was created, the take() was performed under that transaction, and then the transaction was committed.
The Jini Outrigger JavaSpaces Service
The Jini Technology Starter Kit comes with the package com.sun.jini.outrigger, which provides an
implementation of a JavaSpaces technology-enabled service. You can run it two ways:
• As a transient space that loses its state between executions:
Use com.sun.jini.outrigger.TransientOutriggerImpl.
• As a persistent space that maintains state between executions:
Use com.sun.jini.outrigger.PersistentOutriggerImpl.
TransientOutriggerImplPersistentOutriggerImpl
Compiling and Running the SpaceClient Application
To compile and run the sample application in this article, do the following:

1. Compile the code in Code Sample 1 ( MessageEntry.java) using javac as follows:


prompt> javac -classpath <pathToJiniInstallation\lib\jini-ext.jar> MessageEntry.java
Note that you need to include the JAR file jini-ext.jar in your classpath. This JAR file comes with the starter kit
and is in the lib directory of your installation.
2. Compile the code in Code Sample 2 ( SpaceClient.java). Note that this code makes use of a utility class called
Lookup to locate or discover a JavaSpace space. Therefore, before you compile SpaceClient.java, you should
download Lookup.java and then compile both classes using javac as shown in step 2. Note that you should
include the directory that contains MessageEntry.class in your classpath when compiling SpaceClient.java.
3. Run Launch-All, which is in the installverify directory of your Jini installation directory. This will start a
service browser (as shown in Figure 2) and six contributed Jini network technology services, one of which is
the JavaSpace service.

Figure 2: Jini Network Technology Service Browser


4. Finally, run the SpaceClient application using the java command as follows. Here I assume that your Jini
installation directory is C:\Jini2_1beta and that the classes you compiled earlier are at C:\Jini2_1beta\myclasses.
5. C:\Jini2_1beta\myclasses> java -classpath .\;
..\lib\jini-ext.jar;..\lib\reggie.jar;..\lib\outrigger.jar SpaceClient
If all goes well, you will see the output shown in Figure 3.

Figure 3: SpaceClient Sample Output


Conclusion
The JavaSpaces technology provides services and tools for building sophisticated distributed applications. This
technology is designed to work with applications that can model themselves as flow objects through one or
more servers. If your application can be modeled this way, JavaSpaces technology will provide you with many
benefits, such as a reliable distributed storage system for the objects. In addition, JavaSpaces technology
handles concurrent access, storing and retrieving entries atomically.
UNIT 2
5 mark
1. Explain Distributed Application Architecture
2. Explain Java Spaces
10 mark
3. Explain Remote Method Invocation
4. Explain Object Serialization
Unit 2
Java Questions & Answers – Remote Method Invocation (RMI)
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Remote Method Invocation (RMI)”.
1. What is Remote method invocation (RMI)?
a) RMI allows us to invoke a method of java object that executes on another machine
b) RMI allows us to invoke a method of java object that executes on another Thread in multithreaded programming
c) RMI allows us to invoke a method of java object that executes parallely in same machine
d) None of the mentioned
View Answer
Answer: a
Explanation: Remote method invocation RMI allows us to invoke a method of java object that executes on another
machine.
2. Which of these package is used for remote method invocation?
a) java.applet
b) java.rmi
c) java.lang.rmi
d) java.lang.reflect
View Answer
Answer: b
Explanation: None.
3. Which of these methods are member of Remote class?
a) checkIP()
b) addLocation()
c) AddServer()
d) None of the mentioned
View Answer
Answer: d
Explanation: Remote class does not define any methods, its purpose is simply to indicate that an interface uses
remote methods.
advertisement
4. Which of these Exceptions is thrown by remote method?
a) RemoteException
b) InputOutputException
c) RemoteAccessException
d) RemoteInputOutputException
View Answer
Answer: a
Explanation: All remote methods throw RemoteException.
5. Which of these class is used for creating a client for a server-client operations?
a) serverClientjava
b) Client.java
c) AddClient.java
d) ServerClient.java
View Answer
Answer: c
Explanation: None.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
6. Which of these package is used for all the text related modifications?
a) java.text
b) java.awt
c) java.lang.text
d) java.text.modify
View Answer
Answer: a
Explanation: java.text provides capabilities for formatting, searching and manipulating text.
7. What will be the output of the following Java code?
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
9. Constructor constructors[] = c.getConstructors();
10. for (int i = 0; i < constructors.length; i++)
11. System.out.println(constructors[i]);
12. }
13. catch (Exception e)
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the possible constructors of class ‘Class’
c) Program prints “Exception”
d) Runtime Error
View Answer
Answer: a
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public java.awt.Dimension(java.awt.Dimension)
public java.awt.Dimension()
public java.awt.Dimension(int,int)
8. What will be the output of the following Java code?
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
9. Field fields[] = c.getFields();
10. for (int i = 0; i < fields.length; i++)
11. System.out.println(fields[i]);
12. }
13. catch (Exception e)
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
View Answer
Answer: c
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public int java.awt.Dimension.width
public int java.awt.Dimension.height
9. What is the length of the application box made in the following Java program?
1. import java.awt.*;
2. import java.applet.*;
3. public class myapplet extends Applet
4. {
5. Graphic g;
6. g.drawString("A Simple Applet",20,20);
7. }
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: To implement the method drawString we need first need to define abstract method of AWT that is
paint() method. Without paint() method we cannot define and use drawString or any Graphic class methods.
10. What will be the output of the following Java program?
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
9. Method methods[] = c.getMethods();
10. for (int i = 0; i < methods.length; i++)
11. System.out.println(methods[i]);
12. }
13. catch (Exception e)
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
View Answer
Answer: b
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public int java.awt.Dimension.hashCode()
public boolean java.awt.Dimension.equals(java.lang.Object)
public java.lang.String java.awt.Dimension.toString()
public java.awt.Dimension java.awt.Dimension.getSize()
public void java.awt.Dimension.setSize(double,double)
public void java.awt.Dimension.setSize(int,int)
public void java.awt.Dimension.setSize(java.awt.Dimension)
public double java.awt.Dimension.getHeight()
public double java.awt.Dimension.getWidth()
public java.lang.Object java.awt.geom.Dimension2D.clone()
public void java.awt.geom.Dimension2D.setSize(java.awt.geom.Dimension2D)
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public final native void java.lang.Object.wait(long)
public final void java.lang.Object.wait(long,int)
public final void java.lang.Object.wait()
Java Questions & Answers – Serialization & Deserialization
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization & Deserialization”.
1. Which of these is a process of extracting/removing the state of an object from a stream?
a) Serialization
b) Externalization
c) File Filtering
d) Deserialization
View Answer
Answer: d
Explanation: Deserialization is a process by which the data written in the stream can be extracted out from the
stream.
2. Which of these process occur automatically by java run time system?
a) Serialization
b) Memory allocation
c) Deserialization
d) All of the mentioned
View Answer
Answer: d
Explanation: Serialization, deserialization and Memory allocation occur automatically by java run time system.
3. Which of these interface extends DataInput interface?
a) Serializable
b) Externalization
c) ObjectOutput
d) ObjectInput
View Answer
Answer: d
Explanation: ObjectInput interface extends the DataInput interface and supports object serialization.
4. Which of these is a method of ObjectInput interface used to deserialize an object from a stream?
a) int read()
b) void close()
c) Object readObject()
d) Object WriteObject()
View Answer
Answer: c
Explanation: None.
5. Which of these class extend InputStream class?
a) ObjectStream
b) ObjectInputStream
c) ObjectOutput
d) ObjectInput
View Answer
Answer: b
Explanation: ObjectInputStream class extends the InputStream class and implements the ObjectInput interface.
Subscribe Now: Java Newsletter | Important Subjects Newsletters
6. What will be the output of the following Java code?
1. import java.io.*;
2. class streams
3. {
4. public static void main(String[] args)
5. {
6. try
7. {
8. FileOutputStream fos = new FileOutputStream("serial");
9. ObjectOutputStream oos = new ObjectOutputStream(fos);
10. oos.writeInt(5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
16. System.out.println("Serialization" + e);
17. System.exit(0);
18. }
19. try
20. {
21. int z;
22. FileInputStream fis = new FileInputStream("serial");
23. ObjectInputStream ois = new ObjectInputStream(fis);
24. z = ois.readInt();
25. ois.close();
26. System.out.println(x);
27. }
28. catch (Exception e)
29. {
30. System.out.print("deserialization");
31. System.exit(0);
32. }
33. }
34. }
a) 5
b) void
c) serialization
d) deserialization
View Answer
Answer: a
Explanation: oos.writeInt(5); writes integer 5 in the Output stream which is extracted by z = ois.readInt(); and stored
in z hence z contains 5.
Output:
$ javac streams.java
$ java streams
5
7. What will be the output of the following Java code?
1. import java.io.*;
2. class serialization
3. {
4. public static void main(String[] args)
5. {
6. try
7. {
8. Myclass object1 = new Myclass("Hello", -7, 2.1e10);
9. FileOutputStream fos = new FileOutputStream("serial");
10. ObjectOutputStream oos = new ObjectOutputStream(fos);
11. oos.writeObject(object1);
12. oos.flush();
13. oos.close();
14. }
15. catch(Exception e)
16. {
17. System.out.println("Serialization" + e);
18. System.exit(0);
19. }
20. try
21. {
22. int x;
23. FileInputStream fis = new FileInputStream("serial");
24. ObjectInputStream ois = new ObjectInputStream(fis);
25. x = ois.readInt();
26. ois.close();
27. System.out.println(x);
28. }
29. catch (Exception e)
30. {
31. System.out.print("deserialization");
32. System.exit(0);
33. }
34. }
35. }
36. class Myclass implements Serializable
37. {
38. String s;
39. int i;
40. double d;
41. Myclass(String s, int i, double d)
42. {
43. this.d = d;
44. this.i = i;
45. this.s = s;
46. }
47. }
a) -7
b) Hello
c) 2.1E10
d) deserialization
View Answer
Answer: d
Explanation: x = ois.readInt(); will try to read an integer value from the stream ‘serial’ created before, since stream
contains an object of Myclass hence error will occur and it will be catched by catch printing deserialization.
Output:
$ javac serialization.java
$ java serialization
deserialization
8. What will be the output of the following Java program?
1. import java.io.*;
2. class streams
3. {
4. public static void main(String[] args)
5. {
6. try
7. {
8. FileOutputStream fos = new FileOutputStream("serial");
9. ObjectOutputStream oos = new ObjectOutputStream(fos);
10. oos.writeFloat(3.5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
16. System.out.println("Serialization" + e);
17. System.exit(0);
18. }
19. try
20. {
21. FileInputStream fis = new FileInputStream("serial");
22. ObjectInputStream ois = new ObjectInputStream(fis);
23. ois.close();
24. System.out.println(ois.available());
25. }
26. catch (Exception e)
27. {
28. System.out.print("deserialization");
29. System.exit(0);
30. }
31. }
32. }
a) 1
b) 2
c) 3
d) 0
View Answer
Answer: d
Explanation: New input stream is linked to steal ‘serials’, an object ‘ois’ of ObjectInputStream is used to access this
newly created stream, ois.close(); closes the stream hence we can’t access the stream and ois.available() returns 0.
Output:
$ javac streams.java
$ java streams
0
9. What will be the output of the following Java program?
1. import java.io.*;
2. class streams
3. {
4. public static void main(String[] args)
5. {
6. try
7. {
8. FileOutputStream fos = new FileOutputStream("serial");
9. ObjectOutputStream oos = new ObjectOutputStream(fos);
10. oos.writeFloat(3.5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
16. System.out.println("Serialization" + e);
17. System.exit(0);
18. }
19. try
20. {
21. FileInputStream fis = new FileInputStream("serial");
22. ObjectInputStream ois = new ObjectInputStream(fis);
23. System.out.println(ois.available());
24. }
25. catch (Exception e)
26. {
27. System.out.print("deserialization");
28. System.exit(0);
29. }
30. }
31. }
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: d
Explanation: oos.writeFloat(3.5); writes 3.5 in output stream. A new input stream is linked to stream ‘serials’, an
object ‘ois’ of ObjectInputStream is used to access this newly created stream, ois.available() gives the total number
of byte in the input stream since a float was written in the stream thus the stream contains 4 byte, hence 4 is returned
and printed.
Output:
$ javac streams.java
$ java streams
4
10. What will be the output of the following Java program?
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. FileOutputStream fout=new FileOutputStream("D:\\sanfoundry.txt");
9. String s="Welcome to Sanfoundry.";
10. byte b[]=s.getBytes();//converting string into byte array
11. fout.write(b);
12. fout.close();
13. System.out.println("Success");
14. } catch(Exception e){System.out.println(e);}
15. }
16.}
a) “Success” to the output and “Welcome to Sanfoundry” to the file
b) only “Welcome to Sanfoundry” to the file
c) compile time error
d) No Output
View Answer
Answer: a
Explanation: First, it will print “Success” and besides that it will write “Welcome to Sanfoundry” to the file
sanfoundry.txt.
Java Questions & Answers – Serialization – 2
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization – 2”.
1. How an object can become serializable?
a) If a class implements java.io.Serializable class
b) If a class or any superclass implements java.io.Serializable interface
c) Any object is serializable
d) No object is serializable
View Answer
Answer: b
Explanation: A Java object is serializable if class or any its superclass implements java.io.Serializable or its
subinterface java.io.Externalizable.
2. What is serialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory
View Answer
Answer: a
Explanation: Serialization in Java is the process of turning object in memory into stream of bytes.
3. What is deserialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory
View Answer
Answer: b
Explanation: Deserialization is the reverse process of serialization which is turning stream of bytes into an object in
memory.
4. How many methods Serializable has?
a) 1
b) 2
c) 3
d) 0
View Answer
Answer: d
Explanation: Serializable interface does not have any method. It is also called a marker interface.
5. What type of members are not serialized?
a) Private
b) Protected
c) Static
d) Throwable
View Answer
Answer: c
Explanation: All static and transient variables are not serialized.
Subscribe Now: Java Newsletter | Important Subjects Newsletters
6. If member does not implement serialization, which exception would be thrown?
a) RuntimeException
b) SerializableException
c) NotSerializableException
d) UnSerializedException
View Answer
Answer: c
Explanation: If member of a class does not implement serialization, NotSerializationException will be thrown.
7. Default Serialization process cannot be overridden.
a) True
b) False
View Answer
Answer: b
Explanation: Default serialization process can be overridden.
8. Which of the following methods is used to avoid serialization of new class whose super class already implements
Serialization?
a) writeObject()
b) readWriteObject()
c) writeReadObject()
d) unSerializaedObject()
View Answer
Answer: a
Explanation: writeObject() and readObject() methods should be implemented to avoid Java serialization.
9. Which of the following methods is not used while Serialization and DeSerialization?
a) readObject()
b) readExternal()
c) readWriteObject()
d) writeObject()
View Answer
Answer: c
Explanation: Using readObject(), writeObject(), readExternal() and writeExternal() methods Serialization and
DeSerialization are implemented.
10. Serializaed object can be transferred via network.
a) True
b) False
View Answer
Answer: a
Explanation: Serialized object can be transferred via network because Java serialized object remains in form of bytes
which can be transmitted over network.
Unit:3

3. DATABASE

3.1 JDBC - Introduction

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.

• Making a connection to a database.


• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that


allows for portable access to an underlying database. Java can be used to write
different types of executables, such as −

• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database,
and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.

Pre-Requisite
Before moving further, you need to have a good understanding of the following two
subjects −
• Core JAVA Programming
• SQL or MySQL Database

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −

• JDBC API − This provides the application-to-JDBC Manager connection.


• JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application −

Common JDBC Components


The JDBC API provides the following interfaces and classes −
• DriverManager − This class manages a list of database drivers. Matches
connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
• Driver − This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the
details associated with working with Driver objects.
• Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
• Statement − You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
• ResultSet − These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to allow
you to move through its data.
• SQLException − This class handles any errors that occur in a database
application.

The JDBC 4.0 Packages


The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest
JDBC version at the time of writing this tutorial. It offers the main classes for
interacting with your data sources.

The new features in these packages include changes in the following areas −

• Automatic database driver loading.


• Exception handling improvements.
• Enhanced BLOB/CLOB functionality.
• Connection and statement interface enhancements.
• National character set support.
• SQL ROWID access.
• SQL 2003 XML data type support.
• Annotations.

3.2 database access


JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC (
Open Database Connectivity ). JDBC is a standard API specification developed in order
to move data from the front end to the back end. This API consists of classes and
interfaces written in Java. It basically acts as an interface (not the one we use in Java) or
channel between your Java program and databases i.e it establishes a link between the
two so that a programmer can send data from Java code and store it in the database for
future use.
Illustration: Working of JDBC co-relating with real-time

Why JDBC Come into Existence?


As previously told JDBC is an advancement for ODBC, ODBC being platform-
dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, and Core
Java and as we know above languages (except Java and some part of Python )are
platform-dependent. Therefore to remove dependence, JDBC was developed by a
database vendor which consisted of classes and interfaces written in Java.
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step 1– Import the Packages
Step 2– Load the drivers using the forName() method
Step 3– Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5– Create a statement
Step 6– Execute the query
Step 7 – Close the connections
Java Database Connectivity
Let us discuss these steps in brief before implementing by writing suitable code to
illustrate connectivity steps for JDBC.
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in
the program. Registration is to be done once in your program. You can register a driver
in one of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new
or create objects. The following example uses Class.forName() to load the Oracle driver
as shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)

• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before
calling the function. Use of this can be referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces define the
methods that enable you to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();

Note: Here, con is a reference to Connection interface used in previous step .


Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as
follows:
• The query for updating/inserting a table in a database.
• The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that
can be used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute
queries of updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String:
• Java
// This code is for establishing connection with MySQL
// database and retrieving data
// from db Java Database connectivity

/*
*1. import --->java.sql
*2. load and register the driver ---> com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/

importjava.io.*;
importjava.sql.*;

classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSet rs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db

System.out.println(name); // Print result on console


st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
}
}
Output:

Step 6: Closing the connections


So finally we have sent the data to the specified location and now we are on the verge
of completing our task. By closing the connection, objects of Statement and ResultSet
will be closed automatically. The close() method of the Connection interface is used to
close the connection. It is shown below as follows:
con.close();

Example:
• Java
// Java Program to Establish Connection in JDBC

// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;

// Main class
classMain {

// Main driver method


publicstaticvoidmain(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Username and password to access DB


// Custom initialization
String user = "system";
String pass = "12345";
// Entering the data
Scanner k = newScanner(System.in);

System.out.println("enter name");
String name = k.next();

System.out.println("enter roll no");


introll = k.nextInt();

System.out.println("enter class");
String cls = k.next();

// Inserting data using SQL query


String sql = "insert into student1 values('"+ name
+ "',"+ roll + ",'"+ cls + "')";

// Connection class object


Connection con = null;

// Try block to check for exceptions


try{

// Registering drivers
DriverManager.registerDriver(
neworacle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,
pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
intm = st.executeUpdate(sql);
if(m == 1)
System.out.println(
"inserted successfully : "+ sql);
else
System.out.println("insertion failed");

// Closing the connections


con.close();
}

// Catch block to handle exceptions


catch(Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

Output after importing data in the database:

database search
In order to deal with JDBC standard 7 steps are supposed to be followed:
1. Import the database
2. Load and register drivers
3. Create a connection
4. Create a statement
5. Execute the query
6. Process the results
7. Close the connection
Procedure:
1. Import the database-syntax for importing the sql database in java is-
import java.sql.* ;
2. Load and register drivers-syntax for registering drivers after the loading of driver
class is
forName(com.mysql.jdbc.xyz) ;
3. Creating a database irrespective of SQL or NoSQL. Creating a database
using sqlyog and creating some tables in it and fill data inside it in order to search
for the contents of a table. For example, the database is named as “hotelman” and
table names are “cuslogin” and “adminlogin”.
4. Create a connection: Open any IDE where the java executable file can be
generated following the standard methods. Creating a package further creating the
class. Inside the package, open a new java file and type the below code for JDBC
connectivity and save the filename with connection.java.
5. Searching content in a table, let’s suppose my “cuslogin” table has columns namely
“id”, “name”, “email”, “password” and we want to search the customer whose id is
1.
6. Initialize a string with the SQL query as follows
String sql="select * from cuslogin where id=1";
If we want to search for any id in general, then the SQL query becomes
String sql="select * from cuslogin where id="+Integer.parseInt(textfield.getText());
The textfield is the area(in Jframe form) where the user types the id he wants to search
in the “cuslogin” table.
4.1: Initialize the below objects of Connection class, PreparedStatement class, and
ResultSet class(needed for JDBC) and connect with the database as follows
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
con = connection.connectDB();
4.2: Now, add the SQL query of step 3.1 inside prepareStatement and execute it as
follows:
p =con.prepareStatement(sql);
rs =p.executeQuery();
4.3: We check if rs.next() is not null, then we display the details of that particular
customer present in “cuslogin” table
4.4: Open a new java file (here, its result.java) inside the same package and type the full
code (shown below) for searching the details of the customer whose id is 1, from table
“cuslogin”.
Note: both the file viz result.java and connection.java should be inside the same
package, else the program won’t give desired output!!
Implementation:
Example 1
Connection class of JDBC by making an object to be invoked in main(App) java
program below in 1B
• Java

// Java program to search the contents of


// a table in JDBC Connection class for JDBC
// Connection class of JDBC

// Importing required classes


importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.SQLException;

publicclassconnectionDB {

finalString DB_URL
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";

// Database credentials

// We need two parameters to access the database


// Root and password

// 1. Root
finalString USER = "root";
// 2. Password to fetch database
finalString PASS = "Imei@123";

// Connection class for our database connectivity


publicConnection connectDB()
{
// Initially setting NULL
// to connection class object
Connection con = null;

// Try block to check exceptions


try{

// Loading DB(SQL) drivers


Class.forName("com.mysql.cj.jdbc.Driver");

// Registering SQL drivers


con = DriverManager.getConnection(DB_URL, USER,
PASS);
}

// Catch block to handle database exceptions


catch(SQLException e) {

// Print the line number where exception occurs


e.printStackTrace();
}

// Catch block to handle exception


// if class not found
catch(ClassNotFoundException e) {

// Function prints the line number


// where exception occurs
e.printStackTrace();
}

// Returning Connection class object to


// be used in (App/Main) GFG class
returncon;
}
}

App/Main Class where the program is compiled and run calling the above connection
class object
• Java

// Java program to Search the


// contents of a table in JDBC

// Main Java program (App Class) of JDBC

// Step 1: Importing database files


// Importing SQL libraries
importjava.sql.*;

// Main class
// It's connection class is shown above
publicclassGFG {

// Main driver method


publicstaticvoidmain(String[] args)
{
// Step 2: Establishing a connection
connectionDB connection = newconnectionDB();

// Assigning NULL to object of Connection class


// as shown returned by above program
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;

// Step 3: Loading and registereding drivers


// Loaded and registered in Connection class
// shown in above program
con = connection.connectDB();

// Try block to check exceptions


try{

// Step 4: Write a statement


String sql
= "select * from cuslogin where id=1";

// Step 5: Execute the query


p = con.prepareStatement(sql);
rs = p.executeQuery();

// Step 6: Process the results


System.out.println(
"id\t\tname\t\temail\t\tpassword");

// Condition check using next() method


// Holds true till there is single element remaining
// in the object
if(rs.next()) {

intid = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("password");

// Print and display name, emailID and password


System.out.println(id + "\t\t"+ name
+ "\t\t"+ email + "\t\t"
+ password);
}
}

// Catch block to handle exceptions


catch(SQLException e) {

// Print the exception


System.out.println(e);
}
}
}

Output: Based on the values stored inside the “cuslogin” table.

3.3 Multimedia Databases

The multimedia databases are used to store multimedia data such as images, animation, audio, video
along with text. This data is stored in the form of multiple file types like .txt(text), .jpg(images),
.swf(videos), .mp3(audio) etc.
Contents of the Multimedia Database
The multimedia database stored the multimedia data and information related to it. This is given in
detail as follows −

Media data

This is the multimedia data that is stored in the database such as images, videos, audios, animation
etc.

Media format data

The Media format data contains the formatting information related to the media data such as
sampling rate, frame rate, encoding scheme etc.

Media keyword data

This contains the keyword data related to the media in the database. For an image the keyword data
can be date and time of the image, description of the image etc.

Media feature data

Th Media feature data describes the features of the media data. For an image, feature data can be
colours of the image, textures in the image etc.
Challenges of Multimedia Database
There are many challenges to implement a multimedia database. Some of these are:

• Multimedia databases contains data in a large type of formats such as .txt(text), .jpg(images),
.swf(videos), .mp3(audio) etc. It is difficult to convert one type of data format to another.
• The multimedia database requires a large size as the multimedia data is quite large and needs
to be stored successfully in the database.
• It takes a lot of time to process multimedia data so multimedia database is slow.

3.4 The Role of Database in


Web Application Development
Data is very important in Web App Development. With the help of a database, you can store
data safely and can access the data that is stored in the database.

Written by RamotionAug 9, 202221 min read


Last updated: Aug 22, 2023

Table of Contents
1. Role of Database in Web Application
2. Why Do Web App Developers Need a Database?
3. Types of Databases in Web Application
4. List of Popular Web App Databases
5. How to Connect Database to Web Application
6. Conclusion
Database plays a critical role in web app development. It is one of the most important aspects of
building an application. It is necessary that you have a piece of good knowledge of databases
before using them in your application. Database design plays a key role in the operation of your
website and provides you with information regarding transactions, data integrity, and security
issues. In this article, you will learn the role of databases in web application development. You
will also learn about the most popular web app databases and how to connect databases to the
web applications.

What is Database?
The term "database" was coined by Peter Naur in 1960 to describe his approach to developing
software systems. Naur produced a definition that stated, "A file may be regarded as a logical
record of facts or ideas, whereas a database contains information organized so that it can be
used readily and flexibly."

In the early days of computing, databases were synonymous with files on disk. The term is still
commonly used this way for example when people refer to their hard drive as their "main
database".

Data is the foundation of a web application. It is used to store user information, session data, and
other application data. The database is the central repository for all of this data. Web
applications use a variety of databases to store data such as flat files, relational databases, object-
relational databases, and NoSQL databases. Each type of database has its own advantages and
disadvantages when it comes to storing and retrieving data.

A database is a collection of data and information that is stored in an organized manner for easy
retrieval. The primary purpose of a database is to store, retrieve, and update information. A
database can be used to store data related to any aspect of business operations.

Databases can be very large, containing millions of records, or very small, containing just a few
records or even a single record. They may be stored on hard disks or other media, or they may
exist only in memory. In the early days of computing, databases were stored on tape drives or
punch cards. Today they're stored on hard drives, flash memory cards, and other media.

Databases are designed to ensure that the data they contain is organized and easily retrievable. A
database management system (DBMS) is the software used to create and maintain a database.

Role of Database in Web Application


Web application development agency, developers, and designers use databases to store and
organize the data that their applications need. The role of databases in web application
development has increased over time. As a result, a number of developers create applications
that use databases. You can't fully understand web application development without
understanding the role of databases. A database is nothing but an organized collection of data
that helps us, whether creating or modifying any program. Some examples of this kind of
organization are the bookshelf, the NAS storage, and even databases on your desktop
computers!

The role of databases in a web application is very important. The web application interacts with
the database to store data and retrieve data from it. The database is used to store all the
information that the user needs to store. For example, if you are developing a shopping cart
website then it will contain product details, customer details, order details, etc. In this case, you
need to store this information in a database so that we can use them later on.

Why Do Web App Developers Need a


Database?
The first thing one should know when it comes to databases is the need. There are huge
numbers of businesses out there, whose revenue depends on the success and future of their
database. You see, a database is extremely important for online companies and businesses as
well. These days databases are used for various purposes like managing financial records,
setting up customer profiles, keeping inventory and ordering information, etc. But what does all
this mean?

Most modern web applications are based on a database. The database stores information about
the users, products, orders, and more. A database is an important component of any web
application because it provides a central location for storing user information and business logic.
In addition to this, it allows you to store complex data structures with minimal effort.

Databases are used by businesses to collect and store customer information, financial records,
and inventory data. They're also used in research projects to store information about
experiments or tests. For example, if you were conducting a survey on the habits of people who
eat cereal for breakfast, you might use a database to keep track of your results.
Databases are also used by government agencies to store public records like birth certificates
and marriage licenses. Databases are also used by medical researchers who need to record the
medical history of patients in order to determine how effective certain treatments may be for
different diseases or conditions.

Web Application Databases Offer Benefits

Web applications are becoming more and more popular because they allow users to access
information from different devices at the same time. A web application database offers benefits
such as:

Security

A web application database provides security features such as encryption and password
protection. If a user’s password becomes lost or compromised, it will not be possible for
someone else to access the information stored in the database.

Accessibility

Users can access their data from any internet-enabled device, which includes smartphones and
tablets as well as laptops and desktops. This means that users do not have to worry about losing
their valuable data because it is stored on another device.

Reliability and scalability

Web applications are usually accessed by many users simultaneously, unlike traditional desktop
applications that are accessed by one person at a time, so web apps need to be able to handle
more requests simultaneously than their desktop counterparts. Web application databases use
distributed architecture (multiple servers) to scale up quickly when demand increases, so they
can handle large numbers of simultaneous requests without slowing down or crashing.

Ease of maintenance for IT staff

Because web application databases use distributed architecture, problems can be isolated and
fixed quickly, which reduces downtime for the end user and reduces costs for IT staffs
responsible for maintaining the system. Also, with database automation tools we can make
database tasks easier and safer.
Types of Databases in Web Application
A database is a collection of records, each of which is similar to other records in the same
database. There are two types of databases: relational and non-relational. Relational databases
are built on the principles of tabular data, which means there has to be a one-to-one relationship
between the columns and rows in the table. A non-Relational Database is also known as
NoSQL Database.

Relational

A database is a large collection of structured data, which can be accessed to find specific
information. Relational databases are famous for their structure and have been used by
programmers for years.

A relational database is data storage that maintains a relationship between two or more entities.
It is used whenever you want to store information in a way that it can be retrieved by your
application. In general, we can say that a relational database is a data storage structure where
each tuple on its own occupies one record and consists of values of attributes.

There are many advantages of using relational databases over other databases. Apart from this,
there are also some disadvantages associated with using these databases which need careful
consideration before employing them for storing your data.

Advantages

The main advantages of relational databases include:

• Data integrity. A correctly implemented relational database ensures that all data entered
remains accurate, complete, and consistent over time. This helps ensure that all users have
access to the most up-to-date data possible at any given moment without having to worry about
whether it will still be there when they need it later on down the line.
• They're easy to use. Relational databases are designed to be easy to understand and use. The
relationships between all the tables and data elements are clearly defined, making it easy to
understand how they work together. This makes it easier for people with little or no database
experience to understand how to use them without having to learn an entirely new language.
• Scalability. Relational databases scale easily from small applications up to large enterprise
systems. You can add more disk space and memory resources when needed without taking
down your application or disrupting end users. This makes relational databases ideal for large-
scale applications, such as data warehouses or customer relationship management systems.
• High availability and disaster recovery capabilities. Relational databases provide automated
backup capabilities that allow you to recover quickly from hardware failures or other disasters
without requiring human intervention or manual restoration procedures. This makes relational
databases ideal for mission-critical applications where downtime is not an option.

Disadvantages

• Not suitable for real-time data analysis. Relational databases can't be used for real-time data
analysis because they don't store the data in such a way that it can be queried quickly. This
means that if you want to analyze your data in real-time, you need a technology other than
Relational databases. A good example is NoSQL which is more suitable for real-time analysis
because it stores data in a different manner than relational databases do.
• The inability to store documents or graphs in their native format. This means that you need
to transform your data into tabular format before storing it. This can be very inconvenient if you
want to query your data in a different way than what is supported by the database engine itself
(for example, by using SQL or Structured Query Language).
• Not very good at storing sparse data (i.e., large empty spaces). For example, if you want to
store all email addresses from your customers and only non-empty addresses are stored, then
this will take up a lot of space compared to storing every single email address even if it's empty
(the latter would take less space).
• Relational databases have a fixed schema. You cannot change the structure of the database
during its lifetime, this is called fixed schema. This can limit your ability to add new features or
change existing ones. For example, if you want to add a new column for an existing table in a
relational database, you will have to re-write all queries that use this table and also update all
other tables that reference this table. This can be time-consuming and error-prone.

Non-Relational
Non-relational databases (sometimes called object-oriented databases) are very different from
Relational databases. The term non-relational (or NoSQL) database describes any kind of
database in which there is no strict distinction between relations, rows, and columns. The term
non-relational comes from the fact that the objects stored within the databases are not based on
relationships (also called joins), but rather are based on an implicit, often unstructured structure.
Non-relational databases exist mainly to help solve problems relating to responsiveness,
scalability, and performance.

Non-relational databases (or NoSQL) is a class of database management systems that were
designed to be more flexible than a relational database. The main reason is that they are
disconnected from the original data structure and don't use the traditional relationships between
tables in database design which makes them easier to organize, manage, and access.

Advantages

• Speed. The most obvious advantage of non-relational databases is that they can be extremely
fast. Non-relational databases can do things that would take too long in a relational database,
such as searching every record or even all records on disk, without having to query the database
first.
• Simplicity. Non-relational databases are generally easier to understand and use than relational
ones, making them ideal for smaller projects where there aren't many users or developers
working with the data at any given time. NoSQL databases might not be ideal for complex
projects.
• Scalability. Because they are not constrained by the schema, non-relational databases can scale
more easily than relational databases. You can add more hardware and therefore more nodes,
which increases the overall performance of the system. This is particularly useful when you
need to perform complex computations on large amounts of data.
• Data can be stored in any format necessary for the application. For example, if your
application requires XML documents, then you can store them in an XML column instead of
forcing them into a table schema.
• The processing time for queries is faster in some cases because there is no need to traverse
through multiple tables or join across multiple databases like with relational databases.

Disadvantages

• No standardization. Each vendor has its own APIs and features, making it challenging to
implement cross-platform applications.
• Some non-relational databases (especially those used for big data) have problems dealing
with large amounts of data at once because they don't have good query optimization
algorithms built into them as relational databases do.
• A non-relational database doesn't have a fixed structure like a relational database, so you'll
need to write code that can handle the unexpected — for example, you might have to write code
that handles different field lengths depending on what kind of data is being stored. This can
make it harder to maintain your application, especially if it's being used by other people who
aren't aware of these differences.
• The biggest disadvantage of non-relational databases is that they don't support ACID
transactions. In other words, to update data in a non-relational database, you need to perform
multiple queries and then combine them together. The other problem is that these databases are
not compatible with each other, so it's difficult to integrate them into a single system.

Graph Databases (NoSQL)

Graph databases are a relatively new type of database that is able to store and query complex
relationships between entities. Graph databases have been around for many years, but have
recently become popular as large-scale applications like Facebook and LinkedIn have adopted
them.

Graph-based database management systems provide a way to model relationships between


objects as nodes connected by edges (lines). Graphs can be used to represent complex
relationships among people, places, and things in your world such as connections between
people on social media sites like Facebook.

Advantages

• Easy to model real-world situations: The structure of a graph database allows you to model
any type of relationship that exists in your real-world business problem — not just the ones that
fit into a traditional table. This makes them ideal for applications such as social networks or
recommendation engines. Graphs are also great for representing complex data structures such
as trees, hierarchies, and link graphs.
• Efficient for traversing linked data: Graphs are particularly useful for traversing linked data
because they allow you to follow links between objects as easily as searching within an object.
You can easily find all records related to a particular item or set of items by following related
links between those records.
• Graph databases also allow you to query data on both nodes and edges at the same time, so
they're great for analyzing relationships between entities no matter how deep those relationships
may go!

Disadvantages

• Performance. Graphs are not known for their fast performance. They do not perform well
when there are multiple levels of nesting or loops in the graph structure. This means that they
can be slow when dealing with large amounts of data or graphs with high-degree vertices
(vertices connected to many other vertices).
• Scalability. Graphs are not scalable in an easy way like tables are in relational databases.
Because graphs are implemented as networks and each vertex can have multiple edges linking
it to other vertices, adding more vertices and edges to a graph makes it more difficult to manage
efficiently. This is especially true when each vertex has a large number of edges linking it to
other vertices in the database.
• They are relatively new. Many organizations have already invested heavily in relational or
document-oriented databases and may not want to throw away all that investment. In addition,
some organizations may not need the power of a graph database because their data can be
modeled using other types of databases.

List of Popular Web App Databases


Many different types of databases exist, with different features and capabilities. Some databases
are relational (or SQL-based), while others are non-relational (NoSQL). These are the best
databases for web applications. Depending upon your needs choose a right database to build
your software appplications.

MySQL (Relational)

MySQL is a relational database management system (RDBMS) based on SQL. It is a popular


database server, and a multi-user, multi-threaded SQL database. MySQL is developed by
Oracle Corporation. The name "MySQL" is a play on the name of co-founder Michael
Widenius's earlier project, Monty Python's Flying Circus. It is written in C and C++
programming languages, with some elements written in Java. It has been licensed under GPLv2
since 2004, but it can be used under the terms of the GNU Affero General Public License.
MySQL database is often used for data storage, especially in web applications, and it is also
widely used for creating and maintaining relational database tables. MySQL is owned by
Oracle Corporation and was developed by a Swedish company called MySQL AB, which was
bought by Sun Microsystems in 2008. As of 2009, the project is managed by Oracle
Corporation.

It has become the most popular open source and best database software in the world, used on
the web and mobile applications, by corporations large and small and across all industries.

PostgreSQL (Relational)

An object-relational database management system that supports SQL-based queries, similar to


those used by other RDBMS systems such as MySQL or Oracle Database. PostgreSQL is
developed and maintained by PostgreSQL Global Development Group, which is made up of
several companies and individuals who have contributed code to the project over time.

PostgreSQL's developers do not require contributors to sign a Contributor License Agreement


(CLA). The PostgreSQL license includes a clause requiring attribution of original authorship if
it's not done automatically by the contributor's revision control system.

The software is distributed under an ISC license, which allows anyone to use it for any purpose
without paying royalties or fees.

MongoDB (Non-Relational)

MongoDB is an open-source document-oriented database developed by MongoDB Inc.


(formerly 10gen). The first version was released in 2009. It is written in C++ and provides a
document-oriented data model that can be queried using a JSON-like query language.

A document can be thought of as a virtual "sheet" or "document" in a spreadsheet application


such as Microsoft Excel or Google Sheets. A document contains multiple fields that may be
similar to cells in an Excel spreadsheet or cells in an Access database table. These fields can
have different types: text, numbers, dates, and so on.

MongoDB's development began in 2007 when its creators were working on software for the
social media website Facebook.com. They attempted to create a new kind of database that
would be better suited to the needs of web applications than traditional relational databases, but
they found that commercial offerings did not meet their requirements. As a result, they
developed a prototype called GridFS before founding 10gen to continue work on it as a product
named MongoDB. In 2009, the company changed its name to MongoDB Inc., and in February
2010 it released the first production version of MongoDB.

Cassandra (Non-Relational)

Cassandra is an open-source database management system that runs on many servers, making it
well-suited for handling large amounts of data. It offers fast performance and can scale up to a
petabyte of data across multiple servers, making it useful for applications with high write-
throughput requirements.

Cassandra is built on the principles of Dynamo with the goal of addressing some of its
problems. The technology was developed at Facebook and released as an Apache Incubator
project in 2009. It graduated from incubation in June 2010 and became an Apache Top-level
Project (TLP) in January 2012.

Cassandra's architecture is based on Dynamo, but differs from it significantly in its design
details, especially regarding consistency guarantees and failure detection mechanisms. In
particular, Cassandra does not provide strong consistency; instead, it aims to provide high
availability by making it easy to deploy multiple copies of the data across many hosts while
tolerating failures at any one host. This makes Cassandra a popular choice for internet startups
that must scale quickly and cheaply.

Cassandra is a key-value store, but it has flexible data models, so you can use it to store virtually
any kind of data. You can also use Cassandra for full-text search, or even for storing graph data
(although there are better options for graph storage than Cassandra).

Neo4j (Graph database)

Neo4j is an open-source graph database management system that stores data in a native graph
database format. It's designed to store data and query it very quickly, making it ideal for
applications that involve complex relationships between entities. It uses the native graph data
model to provide ACID transactions, high availability, and indexing. It's used by many
companies to power their critical applications, including eBay and Walmart.

Unlike relational databases, Neo4j doesn't enforce a schema on your data. This makes it easier
to build applications that model real-world problems such as social networks or product
recommendations. You can create multiple nodes for the same entity without duplicating data
or having to use foreign keys. In addition, Neo4j allows you to add properties to existing nodes
without having to create a new table first. These features make Neo4j much more agile than
traditional relational databases when modeling complex relationships between entities with
many attributes and relationships between them.

MariaDB (Relational)

MariaDB is a fork of the MySQL relational database management system intended to remain
free under the GNU GPL. MariaDB was forked in 2009 by some of the original developers of
MySQL when Oracle announced that it would no longer fully support the community-
developed version of MySQL in favor of a paid enterprise product.

The original developers of MySQL created MariaDB to provide a better development


environment and more robust performance. MariaDB strives to be compatible with MySQL
and includes most of its storage engines. However, not all features are supported in MariaDB
Server so it is recommended that you check for compatibility before using any feature that may
be affected by a bug or limitation in MariaDB Server.

MSSQL (Relational)

MSSQL databases are the core of Microsoft SQL Server. It is a relational database management
system (RDBMS), a special type of database software that is used to create, store and
manipulate data in an organized manner.

MSSQL can be used to build enterprise-level business solutions and applications. Regardless of
the platform or device your users are using, you can use MSSQL to create a centralized data
store with a single version of the truth. You can also use it to create a single source of truth for
your data analytics and reporting technologies, such as Power BI and Tableau.

How to Connect Database to Web Application


Connecting a database to a web application is an important step in your development process.
By connecting your database to your web application, you can easily add new data, modify
existing data, delete data, and more.
There are a few ways to do it. The simplest way is to use a direct query to get the value you
need. This is not recommended because it will severely limit your flexibility and scalability.

Another approach is to use a stored procedure that returns the value. This can be done in SQL
Server, MySQL server, or other RDBMSs. But what if your web application needs more than
one value from the database? You would need to issue multiple queries or use another method.

The most common way to connect a database to an application is by using an Object Relational
Mapper (ORM). This technology connects your program to the database and allows you to use
it like a normal object. There are many different ORMs available today, but one of the most
popular ones is called Active Record (AR). This library has been around for over 10 years now
and has served as the foundation for many other ORMs such as Yii2 and Laravel.

Conclusion
The database is an integral part of any Web application or website. Whether it is used for storing
data in an easy-to-access manner or for maintenance, the database is going to play a role in the
success of your project and you can't overlook it. For those who are simply going to be
accessing data, the strength of the database will not matter much as long as it has all the
functionality they need. However, those who plan on using it or maintaining it should really
explore why one database type may work better than another. If a web app is going to run fast
and efficiently with minimal downtime, every consideration needs to be made so that
bottlenecks do not occur. The success of your project may depend on your choice of database.

Unit:3
5 mark
1. Explain database access
2. Explain database search
10 mark
3. Explain Creating multimedia databases
4. Explain Database support in web applications

Unit 3
1. Which of the following contains both date and time?
a) java.io.date
b) java.sql.date
c) java.util.date
d) java.util.dateTime
View Answer
Answer: d
Explanation: java.util.date contains both date and time. Whereas, java.sql.date contains only date.
2. Which of the following is advantage of using JDBC connection pool?
a) Slow performance
b) Using more memory
c) Using less memory
d) Better performance
View Answer
Answer: d
Explanation: Since the JDBC connection takes time to establish. Creating connection at the application start-up and
reusing at the time of requirement, helps performance of the application.
3. Which of the following is advantage of using PreparedStatement in Java?
a) Slow performance
b) Encourages SQL injection
c) Prevents SQL injection
d) More memory usage
View Answer
Answer: c
Explanation: PreparedStatement in Java improves performance and also prevents from SQL injection.
advertisement
4. Which one of the following contains date information?
a) java.sql.TimeStamp
b) java.sql.Time
c) java.io.Time
d) java.io.TimeStamp
View Answer
Answer: a
Explanation: java.sql.Time contains only time. Whereas, java.sql.TimeStamp contains both time and date.
5. What does setAutoCommit(false) do?
a) commits transaction after each query
b) explicitly commits transaction
c) does not commit transaction automatically after each query
d) never commits transaction
View Answer
Answer: c
Explanation: setAutoCommit(false) does not commit transaction automatically after each query. That saves a lot of
time of the execution and hence improves performance.
Note: Join free Sanfoundry classes at Telegram or Youtube
6. Which of the following is used to call stored procedure?
a) Statement
b) PreparedStatement
c) CallableStatment
d) CalledStatement
View Answer
Answer: c
Explanation: CallableStatement is used in JDBC to call stored procedure from Java program.
7. Which of the following is used to limit the number of rows returned?
a) setMaxRows(int i)
b) setMinRows(int i)
c) getMaxrows(int i)
d) getMinRows(int i)
View Answer
Answer: a
Explanation: setMaxRows(int i) method is used to limit the number of rows that the database returns from the query.
8. Which of the following is method of JDBC batch process?
a) setBatch()
b) deleteBatch()
c) removeBatch()
d) addBatch()
View Answer
Answer: d
Explanation: addBatch() is a method of JDBC batch process. It is faster in processing than executing one statement
at a time.
9. Which of the following is used to rollback a JDBC transaction?
a) rollback()
b) rollforward()
c) deleteTransaction()
d) RemoveTransaction()
View Answer
Answer: a
Explanation: rollback() method is used to rollback the transaction. It will rollback all the changes made by the
transaction.
10. Which of the following is not a JDBC connection isolation levels?
a) TRANSACTION_NONE
b) TRANSACTION_READ_COMMITTED
c) TRANSACTION_REPEATABLE_READ
d) TRANSACTION_NONREPEATABLE_READ
View Answer
Answer: d
Explanation: TRANSACTION_NONREPEATABLE_READ is not a JDBC connection isolation level.

1. What does JDBC stand for? a. Java Database Connection b. Java Database Connectivity c. Java Database
Control d. Java Database Console

Answer: b. Java Database Connectivity

2. Which of the following interfaces is used to connect to a database in JDBC? a. Connection b. DriverManager
c. Statement d. ResultSet

Answer: a. Connection

3. In JDBC, what is the role of the DriverManager class? a. To manage the connections to the database b. To
execute SQL queries c. To handle exceptions in JDBC d. To define the structure of a database

Answer: a. To manage the connections to the database


4. What is the purpose of the ResultSet interface in JDBC? a. To establish a connection to the database b. To
execute SQL queries c. To represent the result set of a query d. To manage transactions in JDBC

Answer: c. To represent the result set of a query

5. Which method is used to execute a SQL query in JDBC? a. executeQuery() b. executeUpdate() c. execute() d.
executeSql()

Answer: a. executeQuery()

6. What is the purpose of the PreparedStatement interface in JDBC? a. To execute SQL queries b. To manage
connections to the database c. To represent the result set of a query d. To precompile SQL queries for execution

Answer: d. To precompile SQL queries for execution

7. What is the role of the SQLException class in JDBC? a. To represent a generic exception in Java b. To
represent exceptions related to SQL operations c. To manage connections to the database d. To execute SQL queries

Answer: b. To represent exceptions related to SQL operations

8. Which method is used to close a connection in JDBC? a. close() b. shutdown() c. disconnect() d.


endConnection()

Answer: a. close()

9. What does the term "JDBC Driver" refer to in the context of Java Database Connectivity? a. A software
component that implements the JDBC API for a specific database b. A built-in class in Java for database operations
c. A database schema defined in Java d. A tool for managing JDBC connections

Answer: a. A software component that implements the JDBC API for a specific database

10. Which type of JDBC driver provides the highest level of performance? a. Type 1 b. Type 2 c. Type 3 d.
Type 4
graphqlCopy code
** Answer: d. Type 4 **

1. Which of the following steps is not required in JDBC to establish a connection to a database? a. Loading the
JDBC driver b. Creating a Connection object c. Instantiating a Statement object d. Executing a query

Answer: d. Executing a query

2. What is the purpose of the Class.forName("com.mysql.jdbc.Driver"); statement in JDBC? a. It loads the


MySQL database driver class. b. It establishes a connection to the MySQL database. c. It creates a new instance of
the MySQL database. d. It executes a SQL query.

Answer: a. It loads the MySQL database driver class.

3. Which of the following is true about the Statement interface in JDBC? a. It is used to establish a connection
to the database. b. It represents a precompiled SQL query. c. It is used to execute SQL queries and updates. d. It is
used to handle exceptions in JDBC.
Answer: c. It is used to execute SQL queries and updates.

4. What is the purpose of the ResultSetMetaData interface in JDBC? a. It represents the result set of a query. b.
It provides information about the structure of a ResultSet. c. It is used to manage connections to the database. d. It is
used to execute SQL queries.

Answer: b. It provides information about the structure of a ResultSet.

5. What is the primary purpose of the Connection.setAutoCommit() method in JDBC? a. To execute a SQL
query. b. To set the auto-commit mode for a connection. c. To close the connection to the database. d. To commit a
transaction.

Answer: b. To set the auto-commit mode for a connection.

6. Which of the following is a valid URL format for connecting to a MySQL database using JDBC? a.
jdbc:mysql://localhost:3306/mydatabase b. jdbc:oracle://localhost:1521/mydatabase c.
jdbc:sqlserver://localhost:1433/mydatabase d. jdbc:postgresql://localhost:5432/mydatabase

Answer: a. jdbc:mysql://localhost:3306/mydatabase

7. What is the purpose of the PreparedStatement.setXXX() methods in JDBC? a. To set the auto-commit mode
for a connection. b. To bind values to parameters in a SQL query. c. To create a new instance of the
PreparedStatement. d. To execute a SQL query.

Answer: b. To bind values to parameters in a SQL query.

8. In JDBC, what is the purpose of the CallableStatement interface? a. To execute a simple SQL query. b. To
represent the result set of a query. c. To execute stored procedures. d. To handle exceptions in JDBC.

Answer: c. To execute stored procedures.

9. What is the purpose of the DatabaseMetaData interface in JDBC? a. To provide information about the
structure of a ResultSet. b. To execute a SQL query. c. To manage connections to the database. d. To provide
information about the database.

Answer: d. To provide information about the database.

10. Which of the following methods is used to roll back a transaction in JDBC? a. commit() b. rollback() c.
setAutoCommit(false) d. close()
Advanced Java Questions & Answers – Web application
This set of Advanced Java Multiple Choice Questions & Answers (MCQs) focuses on “Web application”.
1. Servlet are used to program which component in a web application?
a) client
b) server
c) tomcat
d) applet
View Answer
Answer: b
Explanation: A servlet class extends the capabilities of servers that host applications which are accessed by way of a
request-response programming model.
2. Which component can be used for sending messages from one application to another?
a) server
b) client
c) mq
d) webapp
View Answer
Answer: c
Explanation: Messaging is a method of communication between software components or applications. MQ can be
used for passing message from sender to receiver.
3. How are java web applications packaged?
a) jar
b) war
c) zip
d) both jar and war
View Answer
Answer: d
Explanation: war are deployed on apache servers or tomcat servers. With Spring boot and few other technologies
tomcat is brought on the machine by deploying jar.
advertisement
4. How can we connect to database in a web application?
a) oracle sql developer
b) toad
c) JDBC template
d) mysql
View Answer
Answer: c
Explanation: JDBC template can be used to connect to database and fire queries against it.
5. How can we take input text from user in HTML page?
a) input tag
b) inoutBufferedReader tag
c) meta tag
d) scanner tag
View Answer
Answer: a
Explanation: HTML provides various user input options like input, radio, text, etc.
Subscribe Now: Java Newsletter | Important Subjects Newsletters
6. Which of the below is not a javascript framework for UI?
a) Vaadin
b) AngularJS
c) KendoUI
d) Springcore
View Answer
Answer: d
Explanation: Springcore is not a javascript framework. It is a comprehensive programming and configuration model
for enterprise applications based on java.
7. Which of the below can be used to debug front end of a web application?
a) Junit
b) Fitnesse
c) Firebug
d) Mockito
View Answer
Answer: c
Explanation: Firebug integrates with firefox and enables to edit, debug and monitor CSS, HTML and javascript of
any web page.
8. What type of protocol is HTTP?
a) stateless
b) stateful
c) transfer protocol
d) information protocol
View Answer
Answer: a
Explanation: HTTP is a stateless protocol. It works on request and response mechanism and each request is an
independent transaction.
9. What does MIME stand for?
a) Multipurpose Internet Messaging Extension
b) Multipurpose Internet Mail Extension
c) Multipurpose Internet Media Extension
d) Multipurpose Internet Mass Extension
View Answer
Answer: b
Explanation: MIME is an acronym for Multi-purpose Internet Mail Extensions. It is used for classifying file types
over the Internet. It contains type/subtype e.g. application/msword.
10. What is the storage capacity of single cookie?
a) 2048 MB
b) 2048 bytes
c) 4095 bytes
d) 4095 MB
View Answer
Answer: c
Explanation: Storage capacity of cookies is 4095 bytes/cookie.

Unit:4
4 SERVLETS
4.1 Java Servlet and CGI

The world has changed into a mobile-first era but even today, none of the applications
could emerge as effective as the web-based apps. Surfacing on top of this is the
prevalence of progressive web apps that perform functions identical to mobile apps. In
this article, we will understand the difference between the two functionalities in web-
based applications namely servlets and CGI.
Servlet is a Java class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response model. Servlets are mainly used to
extend the applications hosted by web servers, however, they can respond to other types
of requests too. For such applications, HTTP-specific servlet classes are defined by Java
Servlet technology. All the programs of Servlets are written in JAVA and they get to run
on JAVA Virtual Machine. The following image describes how a request from clients is
served with the help of threads:
Common Gateway
Interface(CGI): The Common Gateway Interface (CGI) provides the middleware
between WWW servers and external databases and information sources. The World Wide
Web Consortium (W3C) defined the Common Gateway Interface (CGI) and also defined
how a program interacts with a HyperText Transfer Protocol (HTTP) server. The Web
server typically passes the form information to a small application program that processes
the data and may send back a confirmation message. This process or convention for
passing data back and forth between the server and the application is called the common
gateway interface (CGI). The following image describes how a web server acts as an
intermediate between the CGI program and the client browser.

The following table explains the difference between the servlet and CGI:

Basis Servlet CGI

It is thread based i.e. for every


It is process-based i.e. for every new
Approach new request new thread is
request new process is created.
created.

The codes are written in


Language The codes are written any programming
JAVA programming
Used language.
language.

Object- Since codes are written in Since codes are written in any language,
Oriented Java, it is object oriented and all the languages are not object-oriented
Basis Servlet CGI

the user will get the benefits thread-based. So, the user will not get
of OOPs the benefits of OOPs

Portability It is portable. It is not portable.

It remains in the memory until It is removed from the memory after the
Persistence
it is not explicitly destroyed. completion of the process-basedrequest.

Server It can use any of the web- It can use the web-server that supports
Independent server. it.

Data Sharing Data sharing is possible. Data sharing is not possible.

It does not link the web server directly


Link It links directly to the server.
to the server.

It can read and set HTTP It can neither read nor set HTTP
HTTP server
servers. servers.

Construction and destruction Construction and destruction of the new


Cost
of new threads are not costly. processes are costly.

Speed Its can speed is slower. It can speed is faster.

Platform It can be Platform


It can be Platform dependent.
dependency Independent

4.2 A simple java Servlet


Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write
servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements
the Servlet interface and is specially designed to handle HTTP requests.
Sample Code
Following is the sample source code structure of a servlet example to show Hello
World −

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path
location must be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows −

$ javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR files on
your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm
not using any other library in Hello World program.

This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.

If everything goes fine, above compilation would produce HelloWorld.class file in


the same directory. Next section would explain how a compiled servlet would be
deployed in production.

Servlet Deployment
By default, a servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcat-


installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml
file. There could be various entries in this table already available, but never mind.

You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything
goes fine, you would get the following result

4.3 Anatomy of a java Servlet


Life Cycle of a Servlet (Servlet Life Cycle)
1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is used t
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method i
given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:

1. public void destroy()

4.4 Reading data from a client


You must have come across many situations when you need to pass some information
from your browser to web server and ultimately to your backend program. The
browser uses two methods to pass this information to web server. These methods are
GET Method and POST Method.

GET Method
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? (question mark) symbol
as follows −

http://www.test.com/hello?key1 = value1&key2 = value2


The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box.
Never use the GET method if you have password or other sensitive information to
pass to the server. The GET method has size limitation: only 1024 characters can be
used in a request string.

This information is passed using QUERY_STRING header and will be accessible


through QUERY_STRING environment variable and Servlet handles this type of
requests using doGet() method.

POST Method
A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ? (question mark) in the URL
it sends it as a separate message. This message comes to the backend program in the
form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.

Reading Form Data using Servlet


Servlets handles form data parsing automatically using the following methods
depending on the situation −

• getParameter() − You call request.getParameter() method to get the value of a


form parameter.
• getParameterValues() − Call this method if the parameter appears more than
once and returns multiple values, for example checkbox.
• getParameterNames() − Call this method if you want a complete list of all
parameters in the current request.

GET Method Example using URL


Here is a simple URL which will pass two values to HelloForm program using GET
method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

Given below is the HelloForm.java servlet program to handle input given by web
browser. We are going to use getParameter() method which makes it very easy to
access passed information −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


publicclassHelloFormextendsHttpServlet{

publicvoid doGet(HttpServletRequest request,HttpServletResponse response)


throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

PrintWriterout=response.getWriter();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";

out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<ul>\n"+
" <li><b>First Name</b>: "
+request.getParameter("first_name")+"\n"+
" <li><b>Last Name</b>: "
+request.getParameter("last_name")+"\n"+
"</ul>\n"+
"</body>"+
"</html>"
);
}
}

Assuming your environment is set up properly, compile HelloForm.java as follows −

$ javacHelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next
you would have to copy this class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/

<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>

Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name

=ALI in your browser's Location:box and make sure you already started tomcat
server, before firing above command in the browser. This would generate following
result −

4.5 Using GET Method to Read Form Data


• First Name: ZARA
• Last Name: ALI

GET Method Example Using Form


Here is a simple example which passes two values using HTML FORM and submit
button. We are going to use same Servlet HelloForm to handle this input.

<html>
<body>
<formaction="HelloForm"method="GET">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-


installationdirectory>/webapps/ROOT directory. When you would
access http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name: Last Name:

Try to enter First Name and Last Name and then click submit button to see the result
on your local machine where tomcat is running. Based on the input provided, it will
generate similar result as mentioned in the above example.

POST Method Example Using Form


Let us do little modification in the above servlet, so that it can handle GET as well as
POST methods. Below is HelloForm.java servlet program to handle input given by
web browser using GET or POST methods.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


publicclassHelloFormextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

PrintWriterout=response.getWriter();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+
"transitional//en\">\n";

out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<ul>\n"+
" <li><b>First Name</b>: "
+request.getParameter("first_name")+"\n"+
" <li><b>Last Name</b>: "
+request.getParameter("last_name")+"\n"+
"</ul>\n"+
"</body>"
"</html>"
);
}

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

doGet(request, response);
}
}

Now compile and deploy the above Servlet and test it using Hello.htm with the POST
method as follows −

<html>
<body>
<formaction="HelloForm"method="POST">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then
click submit button to see the result on your local machine where tomcat is running.

First Name: Last Name:

Based on the input provided, it would generate similar result as mentioned in the
above examples.

4.6 Reading http request header


Servlets - Client HTTP Request

When a browser requests for a web page, it sends lot of information to the web server
which cannot be read directly because this information travel as a part of header of
HTTP request. You can check HTTP Protocol for more information on this.

Following is the important header information which comes from browser side and
you would use very frequently in web programming −

Sr.No. Header & Description

Accept
1 This header specifies the MIME types that the browser or other clients can
handle. Values of image/png or image/jpeg are the two most common
possibilities.

Accept-Charset
2
This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.

Accept-Encoding
3
This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.

Accept-Language
4
This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc

Authorization
5
This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP
6
connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means that
persistent connections should be used.

Content-Length
7
This header is applicable only to POST requests and gives the size of the
POST data in bytes.

Cookie
8
This header returns cookies to servers that previously sent them to the
browser.

9 Host
This header specifies the host and port as given in the original URL.

Methods to read HTTP Header


There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object

Sr.No. Method & Description

Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this
request.

Enumeration getAttributeNames()
2
Returns an Enumeration containing the names of the attributes available to this
request.

3 Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.

Enumeration getParameterNames()
4
Returns an Enumeration of String objects containing the names of the
parameters contained in this request

HttpSession getSession()
5
Returns the current session associated with this request, or if the request does
not have a session, creates one.

6
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no
current session and value of create is true, returns a new session.

HTTP Header Request Example


Following is the example which uses getHeaderNames() method of
HttpServletRequest to read the HTTP header information. This method returns an
Enumeration that contains the header information associated with the current HTTP
request.

Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and
using nextElement() method to get each parameter name

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


publicclassDisplayHeaderextendsHttpServlet{

// Method to handle GET method request.


publicvoid doGet(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

// Set response content type


response.setContentType("text/html");

PrintWriterout=response.getWriter();
String title ="HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";

out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<table width = \"100%\" border = \"1\" align = \"center\">\n"+
"<tr bgcolor = \"#949494\">\n"+
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames =request.getHeaderNames();

while(headerNames.hasMoreElements()){
String paramName =(String)headerNames.nextElement();
out.print("<tr><td>"+ paramName +"</td>\n");
String paramValue =request.getHeader(paramName);
out.println("<td> "+ paramValue +"</td></tr>\n");
}
out.println("</table>\n</body></html>");
}

// Method to handle POST method request.


publicvoid doPost(HttpServletRequest request,HttpServletResponse response)
throwsServletException,IOException{

doGet(request, response);
}
}

Now calling the above servlet would generate the following result −

HTTP Header Request Example


Header Name Header Value(s)

accept */*

accept-language en-us

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;


user-agent
InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate

host localhost:8080

connection Keep-Alive

cache-control no-cache

4.6 Sending data to a client and writing the


http response header
Servlets - Server HTTP Response
when a Web server responds to an HTTP request, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical response
looks like this −

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>

The status line consists of the HTTP version (HTTP/1.1 in the example), a status code
(200 in the example), and a very short message corresponding to the status code (OK
in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back
to the browser from web server side and you would use them very frequently in web
programming −

Sr.No. Header & Description

Allow
1
This header specifies the request methods (GET, POST, etc.) that the server
supports.

Cache-Control
This header specifies the circumstances in which the response document can
2 safely be cached. It can have values public, private or no-cache etc. Public
means document is cacheable, Private means document is for a single user and
can only be stored in private (non-shared) caches and nocache means
document should never be cached.

Connection
3 This header instructs the browser whether to use persistent in HTTP
connections or not. A value of close instructs the browser not to use persistent
HTTP connections and keepalive means using persistent connections.

Content-Disposition
4
This header lets you request that the browser ask the user to save the response
to disk in a file of the given name.

Content-Encoding
5
This header specifies the way in which the page was encoded during
transmission.

Content-Language
6
This header signifies the language in which the document is written. For
example en, en-us, ru, etc

Content-Length
7
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.

Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension) type of
the response document.

Expires
9
This header specifies the time at which the content should be considered out-
of-date and thus no longer be cached.
Last-Modified
10 This header indicates when the document was last changed. The client can
then cache the document and supply a date by an If-Modified-Since request
header in later requests.

Location
11 This header should be included with all responses that have a status code in
the 300s. This notifies the browser of the document address. The browser
automatically reconnects to this location and retrieves the new document.

Refresh
12 This header specifies how soon the browser should ask for an updated page.
You can specify time in number of seconds after which a page would be
refreshed.

Retry-After
13
This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.

14 Set-Cookie
This header specifies a cookie associated with the page.

Methods to Set HTTP Response Header


There are following methods which can be used to set HTTP response header in your
servlet program. These methods are available with HttpServletResponse object.

Sr.No. Method & Description

String encodeRedirectURL(String url)


1
Encodes the specified URL for use in the sendRedirect method or, if encoding
is not needed, returns the URL unchanged.

String encodeURL(String url)


2
Encodes the specified URL by including the session ID in it, or, if encoding is
not needed, returns the URL unchanged.

boolean containsHeader(String name)


3
Returns a Boolean indicating whether the named response header has already
been set.

4 boolean isCommitted()
Returns a Boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.

6 void addDateHeader(String name, long date)


Adds a response header with the given name and date-value.

7 void addHeader(String name, String value)


Adds a response header with the given name and value.

8 void addIntHeader(String name, int value)


Adds a response header with the given name and integer value.

9 void flushBuffer()
Forces any content in the buffer to be written to the client.

10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.

void resetBuffer()
11
Clears the content of the underlying buffer in the response without clearing
headers or status code.

void sendError(int sc)


12
Sends an error response to the client using the specified status code and
clearing the buffer.

13 void sendError(int sc, String msg)


Sends an error response to the client using the specified status.

void sendRedirect(String location)


14
Sends a temporary redirect response to the client using the specified redirect
location URL.

15 void setBufferSize(int size)


Sets the preferred buffer size for the body of the response.

HTTP Header Response Example


You already have seen setContentType() method working in previous examples and
following example would also use same method, additionally we would
use setIntHeader() method to set Refresh header.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class Refresh extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set refresh, autoload time as 5 seconds


response.setIntHeader("Refresh", 5);

// Set response content type


response.setContentType("text/html");

// Get current time


Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";

String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();


String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Now calling the above servlet would display current system time after every 5
seconds as follows. Just run the servlet and wait to see the result −

Auto Refresh Header Setting


Current Time is: 9:44:50 PM

working with cookies

4.7 Cookies in Servlet


A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces.
They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in


response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
from the browser.

How to create Cookie?


Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you access
it from too many browsers with different values, you will get the different value.

index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
Output
4.2 Java Server Pages: JSP Overview

4.2.1JSP - Overview

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports
dynamic content. This helps developers insert java code in HTML pages by making
use of special JSP tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP
actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in
comparison with the CGI.

• Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike
CGI/Perl which requires the server to load an interpreter and the target script
each time the page is requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC,
JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.

Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −

vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing
etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

4.2.2 JSP - Environment Setup


A development environment is where you would develop your JSP programs, test
them and finally run them.
This tutorial will guide you to setup your JSP development environment which
involves the following steps −

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development
Kit (SDK) and setting up the PATH environment variable appropriately.

You can download SDK from Oracle's Java site − Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install
and configure the setup. Finally set the PATH and JAVA_HOME environment
variables to refer to the directory that contains java and javac,
typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add
the following line in your C:\autoexec.bat file.

set PATH = C:\jdk1.5.0_20\bin;%PATH%


set JAVA_HOME = C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,


select Properties, then Advanced, followed by Environment Variables. Then, you
would update the PATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and


you use the C shell, you will put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment


(IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile
and run a simple program to confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat


A number of Web Servers that support JavaServer Pages and Servlets development
are available in the market. Some web servers can be downloaded for free and Tomcat
is one of them.
Apache Tomcat is an open source software implementation of the JavaServer Pages
and Servlet technologies and can act as a standalone server for testing JSP and
Servlets, and can be integrated with the Apache Web Server. Here are the steps to set
up Tomcat on your machine −

• Download the latest version of Tomcat from https://tomcat.apache.org/.


• Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example, in C:\apache-tomcat-5.5.29 on windows,
or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and
create CATALINA_HOME environment variable pointing to these locations.

Tomcat can be started by executing the following commands on the Windows


machine −

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on the Unix (Solaris,
Linux, etc.) machine −

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web-applications included with Tomcat will be
available by visiting http://localhost:8080/.

Upon execution, you will receive the following output −


Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site
− https://tomcat.apache.org/.

Tomcat can be stopped by executing the following commands on the Windows


machine −

%CATALINA_HOME%\bin\shutdown
or

C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris,


Linux, etc.) machine −

$CATALINA_HOME/bin/shutdown.sh

or

/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify
the servlet classes to the compiler.

If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.

set CATALINA = C:\apache-tomcat-5.5.29


set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer,


select Properties, then Advanced, then Environment Variables. Then, you would
update the CLASSPATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the
following lines into your .cshrc file.

setenv CATALINA = /usr/local/apache-tomcat-5.5.29


setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

NOTE − Assuming that your development directory is C:\JSPDev


(Windows) or /usr/JSPDev (Unix), then you would need to add these directories as
well in CLASSPATH.

4.2.3 JSP Scriptlet tag (Scripting elements)


1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The index.html file gets
the username from the user and the welcome.jsp file prints the username with the welcome
message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response. So
you need not write out.print() to write data. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.

index.jsp

1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag. The index.html file gets
the username and sends the request to the welcome.jsp file, which displays the username.

File: index.jsp

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp

1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside the
_jspService() method. _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp

1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.

index.jsp

1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
Unit:4
5 mark
1. Explain Java Servlet and CGI programming-
2. Explain A simple java Servlet
3. Explain Anatomy of a java Servlet
4. Explain Reading data from a client
5. Explain Reading http request header
10 Mark
6. Explain sending data to a client and writing the http response header-
7. Explain working with cookies
8. Explain JSP Overview-Installation-
9. Explain JSP tags-Components of a JSP page-
10. Explain Expressions- Scriptlets-Directives-Declarations-
11. Explain A complete example
UNIT 4
Advanced Java Questions & Answers – Servlet
This set of Advanced Java Multiple Choice Questions & Answers (MCQs) focuses on “Servlet”.
1. How constructor can be used for a servlet?
a) Initialization
b) Constructor function
c) Initialization and Constructor function
d) Setup() method
View Answer
Answer: c
Explanation: We cannot declare constructors for interface in Java. This means we cannot enforce this requirement to
any class which implements Servlet interface.
Also, Servlet requires ServletConfig object for initialization which is created by container.
2. Can servlet class declare constructor with ServletConfig object as an argument?
a) True
b) False
View Answer
Answer: b
Explanation: ServletConfig object is created after the constructor is called and before init() is called. So, servlet init
parameters cannot be accessed in the constructor.
3. What is the difference between servlets and applets?
i. Servlets execute on Server; Applets execute on browser
ii. Servlets have no GUI; Applet has GUI
iii. Servlets creates static web pages; Applets creates dynamic web pages
iv. Servlets can handle only a single request; Applet can handle multiple requests
a) i, ii, iii are correct
b) i, ii are correct
c) i, iii are correct
d) i, ii, iii, iv are correct
View Answer
Answer: b
Explanation: Servlets execute on Server and doesn’t have GUI. Applets execute on browser and has GUI.
advertisement
4. Which of the following code is used to get an attribute in a HTTP Session object in servlets?
a) session.getAttribute(String name)
b) session.alterAttribute(String name)
c) session.updateAttribute(String name)
d) session.setAttribute(String name)
View Answer
Answer: a
Explanation: session has various methods for use.
5. Which method is used to get three-letter abbreviation for locale’s country in servlets?
a) Request.getISO3Country()
b) Locale.getISO3Country()
c) Response.getISO3Country()
d) Local.retrieveISO3Country()
View Answer
Answer: a
Explanation: Each country is usually denoted by a 3 digit code.ISO3 is the 3 digit country code.
Note: Join free Sanfoundry classes at Telegram or Youtube
6. Which of the following code retrieves the body of the request as binary data?
a) DataInputStream data = new InputStream()
b) DataInputStream data = response.getInputStream()
c) DataInputStream data = request.getInputStream()
d) DataInputStream data = request.fetchInputStream()
View Answer
Answer: c
Explanation: InputStream is an abstract class. getInputStream() retrieves the request in binary data.
7. When destroy() method of a filter is called?
a) The destroy() method is called only once at the end of the life cycle of a filter
b) The destroy() method is called after the filter has executed doFilter method
c) The destroy() method is called only once at the begining of the life cycle of a filter
d) The destroyer() method is called after the filter has executed
View Answer
Answer: a
Explanation: destroy() is an end of life cycle method so it is called at the end of life cycle.
8. Which of the following is true about servlets?
a) Servlets execute within the address space of web server
b) Servlets are platform-independent because they are written in java
c) Servlets can use the full functionality of the Java class libraries
d) Servlets execute within the address space of web server, platform independent and uses the functionality of java
class libraries
View Answer
Answer: d
Explanation: Servlets execute within the address space of a web server. Since it is written in java it is platform
independent. The full functionality is available through libraries.
9. How is the dynamic interception of requests and responses to transform the information done?
a) servlet container
b) servlet config
c) servlet context
d) servlet filter
View Answer
Answer: d
Explanation: Servlet has various components like container, config, context, filter. Servlet filter provides the
dynamic interception of requests and responses to transform the information.
10. Which are the session tracking techniques?
i. URL rewriting
ii. Using session object
iii.Using response object
iv. Using hidden fields
v. Using cookies
vi. Using servlet object
a) i, ii, iii, vi
b) i, ii, iv, v
c) i, vi, iii, v
d) i, ii, iii, v
View Answer
Answer: b
Explanation: URL rewriting, using session object, using cookies, using hidden fields are session tracking techniques.
. Who invented Java Programming?
a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
View Answer
Answer: b
Explanation: Java programming was developed by James Gosling at Sun Microsystems in 1995. James Gosling is
well known as the father of Java.
2. Which statement is true about Java?
a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language
View Answer
Answer: d
Explanation: Java is called ‘Platform Independent Language’ as it primarily works on the principle of ‘compile
once, run everywhere’.
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
View Answer
Answer: c
Explanation: JDK is a core component of Java Environment and provides all the tools, executables and binaries
required to compile, debug and execute a Java Program.
4. Which one of the following is not a Java feature?
a) Object-oriented
b) Use of pointers
c) Portable
d) Dynamic and Extensible
View Answer
Answer: b
Explanation: Pointers is not a Java feature. Java provides an efficient abstraction layer for developing without using
a pointer in Java. Features of Java Programming are Portable, Architectural Neutral, Object-Oriented, Robust,
Secure, Dynamic and Extensible, etc.
5. Which of these cannot be used for a variable name in Java?
a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned
View Answer
Answer: c
Explanation: Keywords are specially reserved words that can not be used for naming a user-defined variable, for
example: class, int, for, etc.
6. What is the extension of java code files?
a) .js
b) .txt
c) .class
d) .java
View Answer
Answer: d
Explanation: Java files have .java extension.
7. What will be the output of the following Java code?
1. class increment {
2. public static void main(String args[])
3. {
4. int g = 3;
5. System.out.print(++g * 8);
6. }
7. }
a) 32
b) 33
c) 24
d) 25
View Answer
Answer: a
Explanation: Operator ++ has more preference than *, thus g becomes 4 and when multiplied by 8 gives 32.
output:
$ javac increment.java
$ java increment
32
8. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
View Answer
Answer: d
Explanation: JAVA_HOME is used to store a path to the java installation.
9. What will be the output of the following Java program?
1. class output {
2. public static void main(String args[])
3. {
4. double a, b,c;
5. a = 3.0/0;
6. b = 0/4.0;
7. c=0/0.0;
8.
9. System.out.println(a);
10. System.out.println(b);
11. System.out.println(c);
12. }
13. }
a) NaN
b) Infinity
c) 0.0
d) all of the mentioned
View Answer
Answer: d
Explanation: For floating point literals, we have constant value to represent (10/0.0) infinity either positive or
negative and also have NaN (not a number for undefined like 0/0.0), but for the integral type, we don’t have any
constant that’s why we get an arithmetic exception.
10. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
View Answer
Answer: c
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation, Polymorphism and Abstraction.
11. What is not the use of “this” keyword in Java?
a) Referring to the instance variable when a local variable has the same name
b) Passing itself to the method of the same class
c) Passing itself to another method
d) Calling another constructor in constructor chaining
View Answer
Answer: b
Explanation: “this” is an important keyword in java. It helps to distinguish between local variable and variables
passed in the method as parameters.
12. What will be the output of the following Java program?
1. class variable_scope
2. {
3. public static void main(String args[])
4. {
5. int x;
6. x = 5;
7. {
8. int y = 6;
9. System.out.print(x + " " + y);
10. }
11. System.out.println(x + " " + y);
12. }
13. }
a) Compilation error
b) Runtime error
c) 5 6 5 6
d) 5 6 5
View Answer
Answer: a
Explanation: Second print statement doesn’t have access to y , scope y was limited to the block defined after
initialization of x.
output:
$ javac variable_scope.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem: y cannot be resolved to a variable
13. What will be the error in the following Java code?
byte b = 50;
b = b * 50;
a) b cannot contain value 50
b) b cannot contain value 100, limited by its range
c) No error in this code
d) * operator has converted b * 50 into int, which can not be converted to byte without casting
View Answer
Answer: d
Explanation: While evaluating an expression containing int, bytes or shorts, the whole expression is converted to int
then evaluated and the result is also of type int.
14. Which of the following is a type of polymorphism in Java Programming?
a) Multiple polymorphism
b) Compile time polymorphism
c) Multilevel polymorphism
d) Execution time polymorphism
View Answer
Answer: b
Explanation: There are two types of polymorphism in Java. Compile time polymorphism (overloading) and runtime
polymorphism (overriding).
15. What will be the output of the following Java program?
1. class leftshift_operator
2. {
3. public static void main(String args[])
4. {
5. byte x = 64;
6. int i;
7. byte y;
8. i = x << 2;
9. y = (byte) (x << 2);
10. System.out.print(i + " " + y);
11. }
12. }
a) 0 256
b) 0 64
c) 256 0
d) 64 0
View Answer
Answer: c
Explanation: None.
output:
$ javac leftshift_operator.java
$ java leftshift_operator
256 0
16. What will be the output of the following Java code?
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class main
8. {
9. public static void main(String args[])
10. {
11. box obj = new box();
12. obj.width = 10;
13. obj.height = 2;
14. obj.length = 10;
15. int y = obj.width * obj.height * obj.length;
16. System.out.print(y);
17. }
18. }
a) 100
b) 400
c) 200
d) 12
View Answer
Answer: c
Explanation: None.
output:
$ javac main.java
$ java main
200
17. What is Truncation in Java?
a) Floating-point value assigned to a Floating type
b) Floating-point value assigned to an integer type
c) Integer value assigned to floating type
d) Integer value assigned to floating type
View Answer
Answer: b
Explanation: None.
18. What will be the output of the following Java program?
1. class Output
2. {
3. public static void main(String args[])
4. {
5. int arr[] = {1, 2, 3, 4, 5};
6. for ( int i = 0; i < arr.length - 2; ++i)
7. System.out.println(arr[i] + " ");
8. }
9. }
a) 1 2 3 4 5
b) 1 2 3 4
c) 1 2
d) 1 2 3
View Answer
Answer: d
Explanation: arr.length() is 5, so the loop is executed for three times.
output:
$ javac Output.java
$ java Output
123
19. What will be the output of the following Java code snippet?
1. class abc
2. {
3. public static void main(String args[])
4. {
5. if(args.length>0)
6. System.out.println(args.length);
7. }
8. }
a) The snippet compiles and runs but does not print anything
b) The snippet compiles, runs and prints 0
c) The snippet compiles, runs and prints 1
d) The snippet does not compile
View Answer
Answer: a
Explanation: As no argument is passed to the code, the length of args is 0. So the code will not print.
20. What is the extension of compiled java classes?
a) .txt
b) .js
c) .class
d) .java
View Answer
Answer: c
Explanation: The compiled java files have .class extension.
21. Which exception is thrown when java is out of memory?
a) MemoryError
b) OutOfMemoryError
c) MemoryOutOfBoundsException
d) MemoryFullException
View Answer
Answer: b
Explanation: The Xms flag has no default value, and Xmx typically has a default value of 256MB. A common use
for these flags is when you encounter a java.lang.OutOfMemoryError.
22. What will be the output of the following Java code?
1. class String_demo
2. {
3. public static void main(String args[])
4. {
5. char chars[] = {'a', 'b', 'c'};
6. String s = new String(chars);
7. System.out.println(s);
8. }
9. }
a) abc
b) a
c) b
d) c
View Answer
Answer: a
Explanation: String(chars) is a constructor of class string, it initializes string s with the values stored in character
array chars, therefore s contains “abc”.
23. Which of these are selection statements in Java?
a) break
b) continue
c) for()
d) if()
View Answer
Answer: d
Explanation: Continue and break are jump statements, and for is a looping statement.
24. What will be the output of the following Java program?
1. class recursion
2. {
3. int func (int n)
4. {
5. int result;
6. if (n == 1)
7. return 1;
8. result = func (n - 1);
9. return result;
10. }
11. }
12. class Output
13. {
14. public static void main(String args[])
15. {
16. recursion obj = new recursion() ;
17. System.out.print(obj.func(5));
18. }
19. }
a) 1
b) 120
c) 0
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.javac
$ java Output
1
25. What will be the output of the following Java code?
1. class output
2. {
3. public static void main(String args[])
4. {
5. String c = "Hello i love java";
6. boolean var;
7. var = c.startsWith("hello");
8. System.out.println(var);
9. }
10. }
a) 0
b) true
c) 1
d) false
View Answer
Answer: d
Explanation: startsWith() method is case sensitive “hello” and “Hello” are treated differently, hence false is stored in
var.
Output:
false
26. Which of these keywords is used to define interfaces in Java?
a) intf
b) Intf
c) interface
d) Interface
View Answer
Answer: c
Explanation: interface keyword is used to define interfaces in Java.
27. What will be the output of the following Java program?
1. class output
2. {
3. public static void main(String args[])
4. {
5. StringBuffer s1 = new StringBuffer("Quiz");
6. StringBuffer s2 = s1.reverse();
7. System.out.println(s2);
8. }
9. }
a) QuizziuQ
b) ziuQQuiz
c) Quiz
d) ziuQ
View Answer
Answer: d
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
Output:
$ javac output.java
$ java output
ziuQ
28. What will be the output of the following Java code?
1. class Output
2. {
3. public static void main(String args[])
4. {
5. Integer i = new Integer(257);
6. byte x = i.byteValue();
7. System.out.print(x);
8. }
9. }
a) 257
b) 256
c) 1
d) 0
View Answer
Answer: c
Explanation: i.byteValue() method returns the value of wrapper i as a byte value. i is 257, range of byte is 256
therefore i value exceeds byte range by 1 hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
29. What will be the output of the following Java program?
1. class Output
2. {
3. public static void main(String args[])
4. {
5. double x = 2.0;
6. double y = 3.0;
7. double z = Math.pow( x, y );
8. System.out.print(z);
9. }
10. }
a) 9.0
b) 8.0
c) 4.0
d) 2.0
View Answer
Answer: b
Explanation: Math.pow(x, y) methods returns value of y to the power x, i:e x ^ y, 2.0 ^ 3.0 = 8.0.
Output:
$ javac Output.java
$ java Output
8.0
30. Which of the following is a superclass of every class in Java?
a) ArrayList
b) Abstract class
c) Object class
d) String
View Answer
Answer: c
Explanation: Object class is superclass of every class in Java.
31. What will be the output of the following Java code?
1. class Output
2. {
3. public static void main(String args[])
4. {
5. double x = 3.14;
6. int y = (int) Math.ceil(x);
7. System.out.print(y);
8. }
9. }
a) 3
b) 0
c) 4
d) 3.0
View Answer
Answer: c
Explanation: ciel(double X) returns the smallest whole number greater than or equal to variable x.
Output:
$ javac Output.java
$ java Output
4
32. What will be the output of the following Java program?
1. import java.net.*;
2. class networking
3. {
4. public static void main(String[] args) throws Exception
5. {
6. URL obj = new URL("https://www.sanfoundry.com/javamcq");
7. URLConnection obj1 = obj.openConnection();
8. int len = obj1.getContentLength();
9. System.out.print(len);
10. }
11. }
Note: Host URL is having length of content 127.
a) 127
b) 126
c) Runtime Error
d) Compilation Error
View Answer
Answer: a
Explanation: None.
Output:
$ javac networking.java
$ java networking
127
33. Which of the below is not a Java Profiler?
a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole
View Answer
Answer: c
Explanation: Memory leak is like holding a strong reference to an object although it would never be needed
anymore. Objects that are reachable but not live are considered memory leaks. Various tools help us to identify
memory leaks.
34. What will be the output of the following Java program?
1. import java.net.*;
2. class networking
3. {
4. public static void main(String[] args) throws MalformedURLException
5. {
6. URL obj = new URL("https://www.sanfoundry.com/javamcq");
7. System.out.print(obj.toExternalForm());
8. }
9. }
a) www.sanfoundry.com
b) https://www.sanfoundry.com/javamcq
c) sanfoundry
d) sanfoundry.com
View Answer
Answer: b
Explanation: toExternalForm() is used to know the full URL of an URL object.
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
35. What will be the output of the following Java code snippet?
1. import java.util.*;
2. class Arraylists
3. {
4. public static void main(String args[])
5. {
6. ArrayLists obj = new ArrayLists();
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
10. obj.add(1, "D");
11. System.out.println(obj);
12. }
13. }
a) [A, D, C]
b) [A, B, C]
c) [A, B, C, D]
d) [A, D, B, C]
View Answer
Answer: d
Explanation: obj is an object of class ArrayLists hence it is an dynamic array which can increase and decrease its
size. obj.add(“X”) adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in the list,
Hence obj.add(1,”D”) stores D at index position 1 of obj and shifts the previous value stored at that position by 1.
Output:
$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].
36. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
d) java.util
View Answer
Answer: c
Explanation: None.
37. What will be the output of the following Java program?
1. import java.util.*;
2. class Collection_iterators
3. {
4. public static void main(String args[])
5. {
6. LinkedList list = new LinkedList();
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
10. list.add(new Integer(1));
11. Iterator i = list.iterator();
12. Collections.reverse(list);
13. Collections.sort(list);
14. while(i.hasNext())
15. System.out.print(i.next() + " ");
16. }
17. }
a) 1 2 5 8
b) 2 1 8 5
c) 1 5 8 2
d) 2 8 5 1
View Answer
Answer: a
Explanation: Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8.
Output:
1258
38. Which of these statements is incorrect about Thread?
a) start() method is used to begin execution of the thread
b) run() method is used to begin execution of a thread before start() method in special cases
c) A thread can be formed by implementing Runnable interface only
d) A thread can be formed by a class that extends Thread class
View Answer
Answer: b
Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be
executed. start() method is used to begin execution of the thread that is execution of run(). run() itself is never used
for starting execution of the thread.
39. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
View Answer
Answer: d
Explanation: try is used for the block that needs to checked for exception.
40. What will be the output of the following Java code?
1. class newthread extends Thread
2. {
3. Thread t;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
11. public void run()
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
17. class multithreaded_programing
18. {
19. public static void main(String args[])
20. {
21. new newthread();
22. }
23. }
a) truetrue
b) falsefalse
c) true
d) false
View Answer
Answer: b
Explanation: This program was previously done by using Runnable interface, here we have used Thread class. This
shows both the method are equivalent, we can use any of them to create a thread.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
41. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private
View Answer
Answer: b
Explanation: Public, private, protected and default are the access modifiers.
42. What will be the output of the following Java program?
1. final class A
2. {
3. int i;
4. }
5. class B extends A
6. {
7. int j;
8. System.out.println(j + " " + i);
9. }
10. class inheritance
11. {
12. public static void main(String args[])
13. {
14. B obj = new B();
15. obj.display();
16. }
17. }
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: class A has been declared final hence it cannot be inherited by any other class. Hence class B does not
have member i, giving compilation error.
output:
$ javac inheritance.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
i cannot be resolved or is not a field
43. What is the numerical range of a char data type in Java?
a) 0 to 256
b) -128 to 127
c) 0 to 65535
d) 0 to 32767
View Answer
Answer: c
Explanation: Char occupies 16-bit in memory, so it supports 216 i:e from 0 to 65535.
44. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket
View Answer
Answer: d
Explanation: ServerSocket is a java.net class which provides system independent implementation of server side
socket connection.
45. What will be the output of the following Java program?
1. class overload
2. {
3. int x;
4. double y;
5. void add(int a , int b)
6. {
7. x = a + b;
8. }
9. void add(double c , double d)
10. {
11. y = c + d;
12. }
13. overload()
14. {
15. this.x = 0;
16. this.y = 0;
17. }
18. }
19. class Overload_methods
20. {
21. public static void main(String args[])
22. {
23. overload obj = new overload();
24. int a = 2;
25. double b = 3.2;
26. obj.add(a, a);
27. obj.add(b, b);
28. System.out.println(obj.x + " " + obj.y);
29. }
30. }
a) 4 6.4
b) 6.4 6
c) 6.4 6.4
d) 6 6
View Answer
Answer: a
Explanation: For obj.add(a,a); ,the function in line number 4 gets executed and value of x is 4. For the next function
call, the function in line number 7 gets executed and value of y is 6.4
output:
$ javac Overload_methods.java
$ java Overload_methods
4 6.4
46. Which of the following is true about servlets?
a) Servlets can use the full functionality of the Java class libraries
b) Servlets execute within the address space of web server, platform independent and uses the functionality of java
class libraries
c) Servlets execute within the address space of web server
d) Servlets are platform-independent because they are written in java
View Answer
Answer: b
Explanation: Servlets execute within the address space of a web server. Since it is written in java it is platform
independent. The full functionality is available through libraries.
Advanced Java Questions & Answers – Web application
This set of Advanced Java Multiple Choice Questions & Answers (MCQs) focuses on “Web application”.
1. Servlet are used to program which component in a web application?
a) client
b) server
c) tomcat
d) applet
View Answer
Answer: b
Explanation: A servlet class extends the capabilities of servers that host applications which are accessed by way of a
request-response programming model.
2. Which component can be used for sending messages from one application to another?
a) server
b) client
c) mq
d) webapp
View Answer
Answer: c
Explanation: Messaging is a method of communication between software components or applications. MQ can be
used for passing message from sender to receiver.
3. How are java web applications packaged?
a) jar
b) war
c) zip
d) both jar and war
View Answer
Answer: d
Explanation: war are deployed on apache servers or tomcat servers. With Spring boot and few other technologies
tomcat is brought on the machine by deploying jar.
advertisement
4. How can we connect to database in a web application?
a) oracle sql developer
b) toad
c) JDBC template
d) mysql
View Answer
Answer: c
Explanation: JDBC template can be used to connect to database and fire queries against it.
5. How can we take input text from user in HTML page?
a) input tag
b) inoutBufferedReader tag
c) meta tag
d) scanner tag
View Answer
Answer: a
Explanation: HTML provides various user input options like input, radio, text, etc.
Subscribe Now: Java Newsletter | Important Subjects Newsletters
6. Which of the below is not a javascript framework for UI?
a) Vaadin
b) AngularJS
c) KendoUI
d) Springcore
View Answer
Answer: d
Explanation: Springcore is not a javascript framework. It is a comprehensive programming and configuration model
for enterprise applications based on java.
7. Which of the below can be used to debug front end of a web application?
a) Junit
b) Fitnesse
c) Firebug
d) Mockito
View Answer
Answer: c
Explanation: Firebug integrates with firefox and enables to edit, debug and monitor CSS, HTML and javascript of
any web page.
8. What type of protocol is HTTP?
a) stateless
b) stateful
c) transfer protocol
d) information protocol
View Answer
Answer: a
Explanation: HTTP is a stateless protocol. It works on request and response mechanism and each request is an
independent transaction.
9. What does MIME stand for?
a) Multipurpose Internet Messaging Extension
b) Multipurpose Internet Mail Extension
c) Multipurpose Internet Media Extension
d) Multipurpose Internet Mass Extension
View Answer
Answer: b
Explanation: MIME is an acronym for Multi-purpose Internet Mail Extensions. It is used for classifying file types
over the Internet. It contains type/subtype e.g. application/msword.
10. What is the storage capacity of single cookie?
a) 2048 MB
b) 2048 bytes
c) 4095 bytes
d) 4095 MB
View Answer
Answer: c
Explanation: Storage capacity of cookies is 4095 bytes/cookie.
Unit:5
ADVANCED TECHNIQUES
JAR file format creation

Java Create Jar Files


In Java, JAR stands for Java ARchive, whose format is based on the zip format. The JAR files
format is mainly used to aggregate a collection of files into a single one. It is a single cross-
platform archive format that handles images, audio, and class files. With the existing applet code,
it is backward-compatible. In Java, Jar files are completely written in the Java programming
language.

We can either download the JAR files from the browser or can write our own JAR files
using Eclipse IDE.

The steps to bundle the source code, i.e., .java files, into a JAR are given below. In this section,
we only understand how we can create JAR files using eclipse IDE. In the following steps, we
don't cover how we can create an executable JAR in Java.

1. In the first step, we will open Eclipse IDE and select the Export option from
the File When we select the Export option, the Jar File wizard opens with the following
screen:
2. From the open wizard, we select the Java JAR file and click on the Next The Next button
opens JAR Export for JAR File Specification.
3. Now, from the JAR File Specification page, we select the resources needed for exporting
in the Select the resources to export After that, we enter the JAR file name and folder.
By default, the Export generated class files and resources checkbox is checked. We
also check the Export Java source files and resources checkbox to export the source
code.

If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or resource is
checked in the window on the right.
4. On the same page, there are three more checkboxes, i.e., Compress the content of the
JAR file, Add directory entries, and Overwrite existing files without warning. By
default, the Compress content of the JAR file checkbox is checked.
5. Now, we have two options for proceeding next, i.e., Finish and Next. If we click on
the Next, it will immediately create a JAR file to that location which we defined in
the Select the export destination. If we click on the Next button, it will open the
Jar Packaging Option wizard for creating a JAR description, setting the advance option,
or changing the default manifest.

6. For now, we skip the Next and click on the Finish button.

Java Internalization - Overview

Internalization
Internalization or I18N refers to the capability of an Application to be able to serve
users in multiple and different languages. Java has in-built support for Internalization.
Java also provides formatting of numbers, currencies and adjustment of date and time
accordingly.

Java Internationalization helps to make a java application handle different languages,


number formats, currencies, region specific time formatting.

Localization
Localization or L10N is the adaptability of an application that is how an application
adapts itself with a specific language, number formats, date and time settings etc.

A java application should be internationalized in order to be able to localize itself.

Culturally Dependent Information


Following information items often varies with different time
zones or cultures.
• Messages

• Date

• Time

• Number

• Currency

• Measurements

• Phone Numbers

• Postal Addresses

• GUI labels

Internationalization Classes
Java has a set of built-in classes which help in internationalization of an application.
These classes are following:

Sr.No. Class & Description

Locale
1
Represents a language along with country/region.

ResourceBundle
2
Contains localized text or objects.

NumberFormat
3
Use to format numbers/currencies as per the locale.

DecimalFormat
4
Use to format numbers as per customized format and as per locale.

5 DateFormat
Use to format dates as per locale.

SimpleDateFormat
6
Use to format dates as per customized format and as per locale.

7. Now, we go to the specified location, which we defined in the Select the export
destination, to ensure that the JAR file is created successfully or not.

Java Swing Tutorial


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.


3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents presentation
and controller acts as an interface between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Do You Know
o How to create runnable jar file in java?
o How to display image on a button in swing?
o How to change the component color by choosing a color from ColorChooser ?
o How to display the digital watch in swing tutorial ?
o How to create a notepad in swing?
o How to create puzzle game and pic puzzle game in swing ?
o How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.
Commonly used Methods of Component class
The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.

File: Simple.java

1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
File: Simple2.java

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
download this example
What we will learn in Swing Tutorial
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout

Advanced java Techniques


Introduction
Core Java (J2SE) and Advanced Java are the two components that make up the Java programming
language (JEE). The foundations of the Java programming language, including its data types,
functions, operators, loops, threads, and exception handling, are discussed in the "core Java" section
of this book. It is used in the process of developing apps for widespread usage. Whereas Intermediate
Java focuses on more advanced topics, such as database connection, networking, Servlet, web
services, and so on, Advanced Java addresses more fundamental ideas. In this article, we will talk
about what advanced Java is, and the concepts of advanced Java.

Advanced java
Everything that is beyond Core Java is known as Advanced Java. This includes the application
programming interfaces (APIs) that are specified in Java Enterprise Edition, as well as Servlet
programming, Web Services, the API, and so on. It is a Web and Enterprise application development
platform that, in its most basic form, adheres to the client-server architectural model.

Important concepts of advanced Java


Majorly there are three most important concepts in advanced Java and they are −

• JSP (Java server pages)


• JDBC (Java DataBase Connectivity)
• Java servlets
We will discuss these concepts in detail in the upcoming sections.

JSP (Java server pages)

Java Server Pages, sometimes known as JSP, is a server-side programming tool that allows the
construction of web-based applications in a manner that is both dynamic and independent of the
underlying platform. JSP is able to access the whole family of Java APIs, including the JDBC API,
which is used to connect to business databases. In a series of straightforward and uncomplicated
stages, this article will show you how to create online apps by making use of Java Server Pages.

The following is a list of the primary characteristics of JSP technology −

• A language used for the development of JSP pages, which are documents written in text
format that specifies how to handle a request and generate a response.
• An expression language that allows access to things stored on the server.
• In the JSP programming language, the mechanisms for introducing new extensions

JDBC (Java DataBase Connectivity)

Java Application Programming Interface (API) known as JDBC, which stands for Java Database
Connectivity, allows users to connect to databases and run queries on them. It is a specification
developed by Sun Microsystems that aims to give Java programs a standardized abstraction (API or
Protocol) for communicating with a variety of databases. It offers the language standards for
connecting to Java databases. It is used in the process of writing programs, which are necessary in
order to access databases. Access to databases and spreadsheets is possible using JDBC when
combined with a database driver. JDBC application programming interfaces allow users access to the
business data kept in a relational database (RDB).

Purpose of JDBC

It is necessary for enterprise applications built with the JAVA EE technology to connect with
databases in order to store information that is unique to the application. Therefore, an effective
database connection is required for interacting with a database. This connectivity need may be met
by using the ODBC (Open database connectivity) driver. This driver is used in conjunction with
JDBC in order to interface or communicate with several sorts of databases, including SQL server
databases, Mysql, Oracle, and MS Access amongst others.

Java Servlets
The Java applications known as servlets are executed on a web server or application server that
supports the Java programming language. They are put to use to handle the request that has been
acquired from the web server, to process the request, to generate the response, and finally to send the
response back to the web server.

The following is a list of properties of Servlets −

• Servlets are programs that run on the server.


• Servlets are capable of managing requests that are very sophisticated and are received from
the web server.

The technologies that are used in the process of developing dynamic web pages are what are known
as server-side extensions. In point of fact, in order to provide the functionality of dynamic web pages,
web pages need a container, also known as a web server. Independent Web server vendors provide
certain proprietary solutions in the form of application programming interfaces (APIs) to satisfy this
need (Application Programming Interface).

Conclusion
So here we come to the end of discussion on the advanced Java. In this article, we learned about what
is advanced java, and the concepts of advanced Java like JSP (Java servlet pages), JDBC (Java
Database Connectivity), and Java servlets.

Unit:5
5 mark
1. Explain JAR file format creation
2. Explain Internationalization
10 mark
1. Explain Swing Programming
2. Explain Advanced java Techniques

Unit 5
1. What is the purpose of the transient keyword in Java? a. It indicates that a variable should not be serialized. b.
It indicates that a variable is volatile. c. It is used to declare a variable as final. d. It is used for garbage collection.

Answer: a. It indicates that a variable should not be serialized.


2. Which design pattern is used to provide an interface for creating families of related or dependent objects
without specifying their concrete classes? a. Singleton Pattern b. Factory Method Pattern c. Abstract Factory
Pattern d. Builder Pattern

Answer: c. Abstract Factory Pattern

3. In Java, what is the purpose of the super keyword? a. It is used to call the superclass method. b. It is used to
invoke the superclass constructor. c. It is used to refer to the current instance of the class. d. It is used to indicate that
a class cannot be extended.

Answer: b. It is used to invoke the superclass constructor.

4. What is the difference between method overloading and method overriding in Java? a. Method overloading
occurs within the same class, while method overriding occurs in different classes. b. Method overloading has the
same method name but different parameters, while method overriding has the same method name and parameters. c.
Method overloading is a way to achieve runtime polymorphism, while method overriding is a way to achieve
compile-time polymorphism. d. Method overloading is a static binding, while method overriding is a dynamic
binding.

Answer: b. Method overloading has the same method name but different parameters, while method
overriding has the same method name and parameters.

5. What is the purpose of the finalize() method in Java? a. It is used to explicitly free the resources. b. It is used
to release the memory occupied by an object. c. It is used to perform cleanup operations before an object is garbage
collected. d. It is used to define the main method in a Java program.

Answer: c. It is used to perform cleanup operations before an object is garbage collected.

6. Which collection class allows null values and implements the Map interface in Java? a. HashMap b.
TreeMap c. LinkedHashMap d. Hashtable

Answer: a. HashMap

7. What is the purpose of the volatile keyword in Java? a. It is used to declare a variable as constant. b. It is used
to synchronize threads. c. It is used to indicate that a variable may be changed by multiple threads. d. It is used to
declare a variable as final.

Answer: c. It is used to indicate that a variable may be changed by multiple threads.

8. Which of the following is a design principle that suggests breaking a program into small, manageable, and
independent parts? a. Encapsulation b. Inheritance c. Abstraction d. Modularity

Answer: d. Modularity

9. What is the purpose of the this keyword in Java? a. It is used to refer to the current instance of the class. b. It is
used to invoke the superclass constructor. c. It is used to create an instance of the class. d. It is used to declare a
variable as an instance variable.

Answer: a. It is used to refer to the current instance of the class.


10. Which of the following is true about the ClassNotFoundException in Java? a. It is a checked exception. b. It
is a subclass of RuntimeException. c. It is thrown when the JVM cannot find the class at runtime. d. It is a type of
IOException.

1. What does GUI stand for?


a) Graphical User Interface
b) General User Interface
c) Graphics Utility Interface
d) Graphical Utility Interface
2. Which package contains the Java Swing classes?
a) java.lang
b) java.io
c) java.util
d) javax.swing
3. Which class is used as the base class for all Swing components?
a) Component
b) Container
c) JPanel
d) JFrame
4. Which layout manager is used by default for JFrame?

a) BorderLayout
b) FlowLayout
c) GridLayout
d) CardLayout
5. Which class is used to create a button in Java Swing?
a) JButton
b) JLabel
c) JRadioButton
d) JTextArea
6. Which event listener interface is used for handling button click events?
a) ActionListener
b) ItemListener
c) MouseListener
d) KeyListener
7. What is the purpose of the setVisible() method in JFrame?
a) To set the size of the frame
b) To set the title of the frame
c) To make the frame visible on the screen
d) To close the frame
8. Which method is used to add components to a container in Java Swing?
a) add()
b) setComponent()
c) insert()
d) append()
9. What is the purpose of the setLayout() method in Java Swing?
a) To set the background color of a component
b) To set the size of a component
c) To set the layout manager for a container
d) To set the font style for a component
10. Which layout manager is used to arrange components in a grid-like structure?

a) BorderLayout
b) FlowLayout
c) GridLayout
d) GridBagLayout
11. What is the purpose of the repaint() method in Java Swing?
a) To change the background color of a component
b) To add a new component to a container
c) To revalidate the layout of a container
d) To redraw a component on the screen
12. Which class is used to display text in Java Swing?
a) JTextField
b) JTextArea
c) JLabel
d) JList
13. Which event listener interface is used for handling keyboard events?
a) ActionListener
b) ItemListener
c) MouseListener
d) KeyListener
14. What is the purpose of the setResizable() method in JFrame?
a) To set the size of the frame
b) To set the title of the frame
c) To make the frame resizable or non-resizable
d) To close the frame
15. Which class is used to display images in Java Swing?
a) JButton
b) JLabel
c) JRadioButton
d) JTextArea
16. Which method is used to set the text content of a JTextField?
a) setText()
b) append()
c) setLabel()
d) setContent()
17. What is the purpose of the setDefaultCloseOperation() method in JFrame?

a) To set the size of the frame


b) To set the title of the frame
c) To specify the default close operation for the frame
d) To close the frame
18. Which class is used to display a list of selectable items in Java Swing?
a) JTextField
b) JTextArea
c) JLabel
d) JList
19. Which event listener interface is used for handling mouse events?
a) ActionListener
b) ItemListener
c) MouseListener
d) KeyListener
20. What is the purpose of the setEnabled() method in Java Swing?
a) To set the size of a component
b) To enable or disable user interaction with a component
c) To set the background color of a component
d) To set the font style for a component
21. Which class is used to display a dropdown list of selectable items in Java Swing?
a) JTextField
b) JTextArea c
) JLabel
d) JComboBox
22. Which event listener interface is used for handling item selection events in a JComboBox?
a) ActionListener
b) ItemListener
c) MouseListener
d) KeyListener
23. What is the purpose of the setToolTipText() method in JavaSwing?
a) To set the size of a component
b) To set the background color of a component
c) To specify a tooltip text for a component
d) To enable or disable user interaction with a component
24. Which class is used to display tabbed panes in Java Swing?

a) JTabbedPane
b) JSlider
c) JProgressBar
d) JSpinner
25. What is the purpose of the setIcon() method in Java Swing?
a) To set the size of an icon
b) To set the background color of an icon
c) To specify an image icon for a component
d) To enable or disable an icon
Answers and Explanations
Question 1
Answer:
a) Graphical User Interface
Explanation:
Graphical User Interface (GUI) stands for creating visual interfaces that allow users to interact with software
applications.
Question 2
Answer:
d) javax.swing
Explanation:
The javax.swing package contains the Java Swing classes for creating GUI components.
Question 3
Answer:
a) Component
Explanation:
The Component class is the base class for all Swing components. It provides common functionality for managing
components.
Question 4
Answer:
a) BorderLayout
Explanation:
By default, JFrame uses the BorderLayout layout manager.
Question 5
Answer:
a) JButton
Explanation:
The JButton class is used to create a button in Java Swing.
Question 6
Answer:
a) ActionListener
Explanation:
The ActionListener interface is used for handling button-click events.
Question 7
Answer:
c) To make the frame visible on the screen
Explanation:
The setVisible() method is used to make the frame visible on the screen.
Question 8
Answer:
a) add()
Explanation:
The add() method is used to add components to a container in Java Swing.
Question 9
Answer:
c) To set the layout manager for a container
Explanation:
The setLayout() method is used to set the layout manager for a container.
Question 10
Answer:
c) GridLayout
Explanation:
The GridLayout layout manager is used to arrange components in a grid-like structure.
Question 11
Answer:
d) To redraw a component on the screen
Explanation:
The repaint() method is used to redraw a component on the screen.
Question 12
Answer:
c) JLabel
Explanation:
The JLabel class is used to display images in Java Swing.
Question 13
Answer:
d) KeyListener
Explanation:
The KeyListener interface is used for handling keyboard events.
Question 14
Answer:
c) To make the frame resizable or non-resizable
Explanation:
The setResizable() method is used to make the frame resizable or non-resizable.
Question 15
Answer:
b) JLabel
Explanation:
The JLabel class is used to display images in Java Swing.
Question 16
Answer:
a) setText()
Explanation:
The setText() method is used to set the text content of a JTextField.
Question 17
Answer:
c) To specify the default close operation for the frame
Explanation:
The setDefaultCloseOperation() method is used to specify the default close operation for the frame.
Question 18
Answer:
d) JList
Explanation:
The JList class is used to display a list of selectable items in Java Swing.
Question 19
Answer:
c) MouseListener
Explanation:
The MouseListener interface is used for handling mouse events.
Question 20
Answer:
b) To enable or disable user interaction with a component
Explanation:
The setEnabled() method is used to enable or disable user interaction with a component.
Question 21
Answer:
d) JComboBox
Explanation:
The JComboBox class is used to display a dropdown list of selectable items in Java Swing.
Question 22
Answer:
b) ItemListener
Explanation:
The ItemListener interface is used for handling item selection events in a JComboBox.
Question 23
Answer:
c) To specify a tooltip text for a component
Explanation:
The setToolTipText() method is used to specify a tooltip text for a component.
Question 24
Answer:
a) JTabbedPane
Explanation:
The JTabbedPane class is used to display tabbed panes in Java Swing.
Question 25
Answer:
c) To specify an image icon for a component
Explanation:
The setIcon() method is used to specify an image icon for a component.
MySQL Questions and Answers – Internationalization and Localization Issues
This set of MySQL Database Multiple Choice Questions & Answers (MCQs) focuses on “Internationalization and
Localization Issues”.
1. The server sets its default time zone by examining its environment.
a) True
b) False
View Answer
Answer: a
Explanation: In MySQL, the server sets its default time zone by examining its environment. This is the local time
zone of the server host. The time zone can be specified explicitly at the server startup.
2. The system variable ‘system_time_zone’ can be reset at runtime.
a) True
b) False
View Answer
Answer: b
Explanation: The ‘system_time_zone’ represents the time zone that the server determines to be the server host time
zone at startup time. It exists only as a global system variable and cannot be reset at runtime.
3. The variable which represents the default time zone of the MySQL server is _____________
a) time_zone
b) system_time_zone
c) date_and_time
d) system_time
View Answer
Answer: a
Explanation: The system variable ‘time_zone’ represents the default time zone of the MySQL server. By default,
this variable is set to ‘SYSTEM’ which means to use the system_time_zone setting.
4. The number of options that can be used to control LOCAL capability at runtime is _____________
a) 0
b) 1
c) 2
d) 3
View Answer
Answer: c
Explanation: At runtime, the server can be started with the ‘–local-infile’ or ‘–skip-local-infile’ options to enable or
disable ‘LOCAL’ capability on the server side. It can be enabled at build time too.
5. If an error occurs during the transaction the troubleshoot is ____________
a) delete
b) rollback
c) commit
d) update
View Answer
Answer: b
Explanation: Whenever an error occurs during a transaction, it is generally taken to the state prior to the beginning
of transaction execution. This is known as rollback. It is a set of undo operations.
Note: Join free Sanfoundry classes at Telegram or Youtube
6. The ‘A’ in the ACID property of transactions is _______________
a) Availability
b) Accuracy
c) Adjustability
d) Atomicity
View Answer
Answer: d
Explanation: All the transaction systems have an important set of characteristics in common. This is known as the
‘ACID’ property of the transaction. It refers to the four elementary characteristics of a transaction.
7. The ‘C’ in the ACID property of transactions is _______________
a) Compound
b) Concrete
c) Collision
d) Consistency
View Answer
Answer: d
Explanation: The elementary characteristics of a transaction are known as the ‘ACID’ properties. ‘ACID’ is the
acronym for the four basic characteristics that a transaction must have for smooth processing.
8. The datatype that means a variable length non binary string is __________
a) VARCHAR
b) BINARY
c) VARBINARY
d) BLOB
View Answer
Answer: a
Explanation: In MySQL, there is a wide variety of string datatypes for use. Strings can even hold image and sound
data. All four options are string type names. VARCHAR represents a variable length non binary string.
9. The date and time datatype that stores time value in ‘hh:mm:ss’ format is ___________
a) DATE
b) TIME
c) DATETIME
d) TIMESTAMP
View Answer
Answer: b
Explanation: MySQL has some variety of date and time datatypes. These datatypes are crucial for representing
records in a table. The ‘TIME’ type represents a time value, stored in the ‘hh:mm:ss’ format.
10. The spatial datatype used to store a curve is _____________
a) GEOMETRY
b) POINT
c) LINESTRING
d) POLYGON
View Answer
3. Answer: c
Explanation: In MySQL, there are many spatial datatypes available for use. Some examples are GEOMETRY,
POINT, LINESTRING and POLYGON. The LINESTRING type is used to represent a curve.
4.
5.

You might also like