AJ unit I
AJ unit I
AJ unit I
1. BASICS OF JAVA
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 −
publicclassMyFirstJavaProgram {
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.
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.
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.
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.
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'
• 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.
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
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.
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)
2) Running
3) Suspended
4) Blocked
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.
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)
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
Output:
Let's takes an example to understand how we can create, start and run the thread using the
runnable interface.
ThreadExample2.java
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.
6) Socket
A socket is an endpoint between two way communications.
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
o ContentHandlerFactory
o CookiePolicy
o CookieStore
o DatagramSocketImplFactory
o FileNameMap
o SocketOption<T>
o SocketOptions
o SocketImplFactory
o URLStreamHandlerFactory
o ProtocolFamily
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.
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.
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 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 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.
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.
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.
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.
Constructors
The class contains only a single constructor which is given below.
UNIT 1
5 mark
1. Components and event handling
2. Media techniques
10 mark
1. Threading concepts
2. Networking features
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.
Interview Process
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.
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:
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:
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons
The RMI application have all these features, so it is called the distributed 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. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
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
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 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.
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. }
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. }
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. }
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. }}
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. }}
The following table lists the different forms of transparency in a distributed system −
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.
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.
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.
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
Disadvantages
• 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.
Broker
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
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.
Features of SOA
A service-oriented architecture provides the following features −
SOA Operation
The following figure illustrates how does SOA operate −
Advantages
• 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.
• 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.
• 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.
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).
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.
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.
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.
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
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.
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
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.
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 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.
How can we build sophisticated distributed applications with only a handful of operations? The space itself
provides a set of key features.
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.
Copied to Clipboard
import net.jini.core.entry.*;
public class MessageEntry implements Entry {
public String content;
public MessageEntry() {
}
Copied to Clipboard
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
import net.jini.space.JavaSpace;
3. DATABASE
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.
• 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 −
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 −
The new features in these packages include changes in the following areas −
• 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();
/*
*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
Example:
• Java
// Java Program to Establish Connection in JDBC
// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;
// Main class
classMain {
System.out.println("enter name");
String name = k.next();
System.out.println("enter class");
String cls = k.next();
// Registering drivers
DriverManager.registerDriver(
neworacle.jdbc.OracleDriver());
// 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");
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
publicclassconnectionDB {
finalString DB_URL
= "jdbc:mysql://localhost:3306/testDB?useSSL=false";
// Database credentials
// 1. Root
finalString USER = "root";
// 2. Password to fetch database
finalString PASS = "Imei@123";
App/Main Class where the program is compiled and run calling the above connection
class object
• Java
// Main class
// It's connection class is shown above
publicclassGFG {
intid = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String password = rs.getString("password");
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.
The Media format data contains the formatting information related to the media data such as
sampling rate, frame rate, encoding scheme etc.
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.
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.
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.
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.
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 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.
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.
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
• 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 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.
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.
MySQL (Relational)
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)
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'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 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.
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.
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
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
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
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: 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
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.
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.
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.
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.
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.
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:
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
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.
It can read and set HTTP It can neither read nor set HTTP
HTTP server
servers. servers.
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.
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.
<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
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
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.
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 −
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.
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.*;
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>"
);
}
}
$ 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>
=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 −
<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>
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.
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>"
);
}
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.
Based on the input provided, it would generate similar result as mentioned in the
above examples.
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 −
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.
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.
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
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"
);
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>");
}
doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
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 −
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.
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.
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.
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
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"
);
}
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 −
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.
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 Description
Cookie(String name, String value) constructs a cookie with a specified name and value.
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.
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. }
index.html
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
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.
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
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.
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.
%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/.
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
$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.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the
following lines into your .cshrc file.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.
o scriptlet tag
o expression tag
o declaration tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
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>
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.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
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>
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
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.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
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
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.
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.
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.
• 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:
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.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
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 ?
Method Description
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.
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.
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
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.
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.
• 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
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 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.
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.
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.
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.
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.
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) 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.