Skip to content

Instantly share code, notes, and snippets.

@sohanmanju
Last active December 22, 2019 04:37
Show Gist options
  • Save sohanmanju/87548bdc514a172947ec883ef17d570a to your computer and use it in GitHub Desktop.
Save sohanmanju/87548bdc514a172947ec883ef17d570a to your computer and use it in GitHub Desktop.
Java Model Papers
Chapter 1:
Q1. Explain method overloading and method overriding with an example.
ans. Overriding and Overloading are two very important concepts in Java. They are confusing for Java novice programmers. This post illustrates their differences by using two simple examples.
1. Definitions
Overloading occurs when two or more methods in one class have the same method name but different parameters.
Overriding means having two methods with the same method name and parameters (i.e., method signature).
One of the methods is in the parent class and the other is in the child class.
Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.
2. Overriding vs. Overloading
Here are some important facts about Overriding and Overloading:
1). The real object type in the run-time, not the reference variable's type, determines which overridden method is used at runtime.
In contrast, reference type determines which overloaded method will be used at compile time.
2). Polymorphism applies to overriding, not to overloading.
3). Overriding is a run-time concept while overloading is a compile-time concept.
3. An Example of Overriding
Here is an example of overriding. After reading the code, guess the output.
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
public void bark(){
System.out.println("bowl");
}
}
public class OverridingTest{
public static void main(String [] args){
Dog dog = new Hound();
dog.bark();
}
}
Output:
bowl
In the example above, the dog variable is declared to be a Dog. During compile time, the compiler checks if the Dog class has the bark() method.
As long as the Dog class has the bark() method, the code compilers. At run-time, a Hound is created and assigned to dog.
The JVM knows that dog is referring to the object of Hound, so it calls the bark() method of Hound. This is called Dynamic Polymorphism.
4. An Example of Overloading
class Dog{
public void bark(){
System.out.println("woof ");
}
//overloading method
public void bark(int num){
for(int i=0; i<num; i++)
System.out.println("woof ");
}
}
In this overloading example, the two bark method can be invoked by using different parameters.
Compiler know they are different because they have different method signature (method name and method parameter list).
Q. What is an Applet? Give an Example
Ans. An applet is a Java program that can be embedded into a web page.
It runs inside the web browser and works at client side.
An applet is embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the web site more dynamic and entertaining.
Important points :
All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer. JDK provides a standard applet viewer tool called applet viewer.
In general, execution of an applet does not begin at main() method.
Output of an applet window is not performed by System.out.println(). Rather it is handled with various AWT methods, such as drawString().
Sample Program:
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
// HelloWorld class extends Applet
public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}
Q.Explain TCP/IP client and server sockets.
Ans. TCP/IP sockets are used to implement t reliable, bidirectional, persistent, point-to-point, and stream -based connections between hosts on the Internet.
A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.
Applets may only establish socket connections back to the host from which the applet was downloaded.
This restriction exists because it would be dangerous for applets loaded through a firewall to have access to any arbitrary machine.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The Server Socket class is designed to be a listener, which waits for clients to connect before doing anything.
The Socket class is designed to connect to server sockets and initiate protocol exchanges.
The creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that connection.
Q.Explain how multiple inheritance is implemented in Java? With an example
Yes, we can implement more than one interfaces in our program because that doesn’t cause any ambiguity(see the explanation below).
interface X
{
public void myMethod();
}
interface Y
{
public void myMethod();
}
class JavaExample implements X, Y
{
public void myMethod()
{
System.out.println("Implementing more than one interfaces");
}
public static void main(String args[]){
JavaExample obj = new JavaExample();
obj.myMethod();
}
}
Output:
Implementing more than one interfaces
As you can see that the class implemented two interfaces. A class can implement any number of interfaces.
In this case there is no ambiguity even though both the interfaces are having same method.
Why? Because methods in an interface are always abstract by default, which doesn’t let them give their implementation (or method definition ) in interface itself.
Q. What is an exception? Write the program to perform exception handling on dividing zero by zero
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Ex:
class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user.
Q. Explain Package and Import command in Java?
Ans. import keyword is used to import built-in and user-defined packages into your java source file so that your class can refer to a class that is in another package by directly using its name.
package keyword is used to specify the package to which a class should be included into.
Ex:
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
Q.List and Explain the Java Buzzwords
Ans.1.Simple
2.Secure
3.Portable
4.Object-Oriented
5.Robust
6.Multithreading
7.Architecture Neutral
8.Interpreted
9.High Performance
10.Distributed
11.Dynamic
Explained here: https://www.quora.com/What-are-Java-buzzwords
Q.Nested Classes in java and explain how to demonstrate access protection in an inner class.
Ans. In java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.
The scope of a nested class is bounded by the scope of its enclosing class. Thus in above example, class NestedClass does not exist independently of class OuterClass.
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// can access display private static member of outer class
System.out.println("outer_private = " + outer_private);
// The following statement will give compilation error
// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);
}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Q. Life Cycle of an Applet in Java.
Below is the description of each applet life cycle method:
init(): The init() method is the first method to execute when the applet is executed. Variable declaration and initialization operations are performed in this method.
start(): The start() method contains the actual code of the applet that should run. The start() method executes immediately after the init() method. It also executes whenever the applet is restored, maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The stop() method executes when the applet is minimized or when moving from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is closed or when the tab containing the webpage is closed. stop() method executes just before when destroy() method is invoked. The destroy() method removes the applet object from memory.
paint(): The paint() method is used to redraw the output on the applet display area. The paint() method executes after the execution of start() method and whenever the applet or browser is resized.
The method execution sequence when an applet is executed is:
init()
start()
paint()
The method execution sequence when an applet is closed is:
stop()
destroy()
Q. Difference between throw and throws in exception handling.
Ans. throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the
exceptions which a method might throw.
Q.To create a package in Java.
Ans. Creating a package in Java is a very easy task. Choose a name for the package and include a package command as the first statement in the Java source file. The java source file can contain the classes, interfaces, enumerations, and annotation types that you want to include in the package. For example, the following statement creates a package named MyPackage.
code:
package MyPackage;
The package statement simply specifies to which package the classes defined belongs to.
--------------------------------------------------------------------------------------------------------------------------
Chapter 2:
Q. What is a thread? Exaplain two ways of creating a thread in Java.
Ans.A thread is actually a lightweight process. Unlike many other computer languages, Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called thread and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking.
Java defines two ways by which a thread can be created.
By implementing the Runnable interface.
By extending the Thread class.
Implementing the Runnable Interface
The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form,
public void run()
run() method introduces a concurrent thread into your program. This thread will end when run() method terminates.
You must specify the code that your thread will execute inside run() method.
run() method can call other methods, can use other classes and declare variables just like any other normal method.
class MyThread implements Runnable
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Extending Thread class
This is another way to create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.
class MyThread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
classMyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
mt.start();
}
}
Q. What is the need of Synchronization? Explain with an example how synchronization is implemented.
Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of Java object or synchronization of Java class becomes extremely important. Synchronization in Java is possible by using Java keywords "synchronized" and "volatile”.
Using synchronized keyword along with method is easy just apply synchronized keyword in front of the method. What we need to take care is that static synchronized method locked on class object lock and nonstatic synchronized method locks on current object (this). So it’s possible that both static and nonstatic java synchronized method running in parallel. This is the common mistake a naive developer do while writing Java synchronized code.
public class Counter{
private static int count = 0;
public static synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
Q. Explain delegation event model. Explain what happens at the push of a button.
The Delegation Event model is one of the many techniques used to handle events in GUI (Graphical User Interface) programming languages. GUI represents a system where an user visually/graphically interacts with the system. Other interactive systems are text based or called CUI (Character User Interface). CUI interacts with the system by typing out commands in the console. GUI programming is inherently event driven; that means, whenever an user initiates an activity such as a mouse move that changes the co-ordinates of the mouse pointer in the screen, or clicks a button, scrolls a page, and so forth, each is deemed as an event that the GUI event handler maps the activity to a piece of code that explains what response the application should provide to the user. This is the basis of event handling.
Q. Explain Producer & Consumer Model.
Producer-Consumer solution using threads in Java
In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be awakened.
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC {
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();
// to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
Q. Explain Thread Priority and how it's assigned.
Every thread in Java has a priority that helps the thread scheduler to determine the order in which threads scheduled. The threads with higher priority will usually run before and more frequently than lower priority threads. By default, all the threads had the same priority, i.e., they regarded as being equally distinguished by the scheduler, when a thread created it inherits its priority from the thread that created it. However, you can explicitly set a thread's priority at any time after its creation by calling its setPriority() method. This method accepts an argument of type int that defines the new priority of the thread. Its syntax is.
final void setPriority(int priority)
Here, priority is an integer value that must range between 1 and 10, with 10 being the highest priority, 1 being the lowest and 5 being the default. If you specify a priority that is out of range, then an IllegalArgumentException exception thrown. Some thread priorities are static member variables of java.lang.Thread class. These include MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY representing values 1,5 and 10 respectively. The priority of the main thread is Thread.NORM_PRIORITY, i.e., 5.
For example: To set the thread to the maximum priority, the following statements should be used.
Thread t1 = new thread(task);
t1.setPriority(Thread.Max_Priority);
t1.start() ;
You can also determine the current thread priority by calling the getPriority() method.
final int getpriority()
This method returns an in t value which indicates the current priority of the thread.
Q. Explain Deadlock. How to overcome it with a program example.
Ans.Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.
Solution to deadlock:
Live Demo
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
Q. Java Adapter class and write a program for mouse event handling.
Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter class, you will not be forced to provide the implementation of all the methods of listener interfaces. So it saves code.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Q. Explain the following.
1. Event Classes
2. Event Listener Interface
3. Source of events
Ans.
Event Classes: The Event classes represent the event. Java provides us various Event classes.
Following is the declaration for java.util.EventObject class:
public class EventObject
extends Object
implements Serializable
Event Listener Interface: The Event listener represent the interfaces responsible to handle events. It is a marker interface which every listener interface has to extend.This class is defined in java.util package.
Following is the declaration for java.util.EventListener interface:
public interface EventListener
Q.Differentiate between isAlive() and Join(). Implement a Java Program to create five threads with different priorirties. Send two threads to the highest priority and two to sleep states. Check the aliveness of the threads.
Ans. Sometimes one thread needs to know when other thread is terminating. In java, isAlive() and join() are two different methods that are used to check whether a thread has finished its execution or not.
The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false.
final boolean isAlive()
But, join() method is used more commonly than isAlive(). This method waits until the thread on which it is called terminates.
final void join() throws InterruptedException
Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.
ThreadClass.java
class ThreadClass implements Runnable
{
long click=0;
Thread t;
private volatile boolean running =true; public ThreadClass(int p) {
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while(running)
{
click++;
}
}
public void stop()
{
running =false;
}
public void start()
{
t.start();
}
}
Demo.java
public class Demo {
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ThreadClass hi1=new ThreadClass(Thread.NORM_PRIORITY + 2);
ThreadClass hi2=new ThreadClass(Thread.NORM_PRIORITY -2);
ThreadClass hi3=new ThreadClass(Thread.NORM_PRIORITY + 3);
ThreadClass hi4=new ThreadClass(Thread.NORM_PRIORITY - 3);
ThreadClass hi5=new ThreadClass(Thread.NORM_PRIORITY +4);
hi1.start();
hi2.start();
hi3.start();
hi4.start();
hi5.start();
System.out.println("thread one is alive:" +hi1.t.isAlive()); System.out.println("thread two is alive:" +hi2.t.isAlive()); System.out.println("thread three is alive:" +hi3.t.isAlive()); System.out.println("thread four is alive:" +hi4.t.isAlive()); System.out.println("thread four is alive:" +hi5.t.isAlive()); try
{ hi5.t.sleep(1000); hi3.t.sleep(1000);
}
catch(InterruptedException e){
System.out.println("main thread interrupted");
}
hi1.stop();
hi2.stop();
hi3.stop();
hi4.stop();
hi5.stop();
try
{
System.out.println("waiting for threads to finish");
hi1.t.join();
hi2.t.join();
hi3.t.join();
hi4.t.join();
hi5.t.join();
}
catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
System.out.println("priority of thread1:" +hi1.t.getPriority());
System.out.println("priority of thread2:" +hi2.t.getPriority());
System.out.println("priority of thread3:" +hi3.t.getPriority());
System.out.println("priority of thread4:" +hi4.t.getPriority());
System.out.println("priority of thread5:" +hi5.t.getPriority());
System.out.println("thread one is alive:" +hi1.t.isAlive());
System.out.println("thread two is alive:" +hi2.t.isAlive());
System.out.println("thread three is alive:" +hi3.t.isAlive());
System.out.println("thread four is alive:" +hi4.t.isAlive());
System.out.println("thread five is alive:" +hi5.t.isAlive());
System.out.println("main thread exiting");
}
}
Q.Briefly Explain the process of IPC.
Ans. An operating system can implement both method of communication. First, we will discuss the shared memory method of communication and then message passing. Communication between processes using shared memory requires processes to share some variable and it completely depends on how programmer will implement it. One way of communication using shared memory can be imagined like this: Suppose process1 and process2 are executing simultaneously and they share some resources or use some information from other process, process1 generate information about certain computations or resources being used and keeps it as a record in shared memory. When process2 need to use the shared information, it will check in the record stored in shared memory and take note of the information generated by process1 and act accordingly. Processes can use shared memory for extracting information as a record from other process as well as for delivering any specific information to other process.
Ex: Producer-Consumer problem
Q.Explain MVC and it's advantages
Ans.The Model View Controller (MVC) design pattern specifies that an application consist of a data model, presentation information, and control information. The pattern requires that each of these be separated into different objects.
MVC is more of an architectural pattern, but not for complete application. MVC mostly relates to the UI / interaction layer of an application. You’re still going to need business logic layer, maybe some service layer and data access layer.
-The Model contains only the pure application data, it contains no logic describing how to present the data to a user.
-The View presents the model’s data to the user. The view knows how to access the model’s data, but it does not know what this data means or what the user can do to manipulate it.
-The Controller exists between the view and the model. It listens to events triggered by the view (or another external source) and executes the appropriate reaction to these events. In most cases, the reaction is to call a method on the model. Since the view and the model are connected through a notification mechanism, the result of this action is then automatically reflected in the view.
Advantages
Multiple developers can work simultaneously on the model, controller and views.
MVC enables logical grouping of related actions on a controller together. The views for a specific model are also grouped together.
Models can have multiple views.
--------------------------------------------------------------------------------------------------------------------------
UNIT 3
Q. Advantages of Swings over AWT.
Swing provides both additional components and added functionality to AWT-replacement components
Swing components can change their appearance based on the current "look and feel" library that's being used. You can use the same look and feel as the platform you're on, or use a different look and feel
Swing components follow the Model-View-Controller paradigm (MVC), and thus can provide a much more flexible UI. Swing provides "extras" for components, such as:
-Icons on many components
-Decorative borders for components
-Tooltips for components
Swing components are lightweight (less resource intensive than AWT)
Swing provides built-in double buffering
Swing provides paint debugging support for when you build your own components
Q. Write a brief note on Containers in Swings.
Ans. Containers are an integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it provides the capability to add a component to itself. Following are certain noticable points to be considered.
-Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.
-Container can add only a Component to itself.
-A default layout is present in each container which can be overridden using setLayout method.
Q. Different Swing Buttons in Java.
Containers are an integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it provides the capability to add a component to itself. Following are certain noticable points to be considered.
Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden using setLayout method.
The JButton class provides the functionality of a push button. You have already seen a simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be associated with the push button. Three of its constructors are shown here:
JButton(Icon icon) JButton(String str) JButton(String str, Icon icon)
Toggle buttons are objects of the JToggleButton class. JToggleButton implements AbstractButton. In addition to creating standard toggle buttons, JToggleButton is a superclass for two other Swing components that also represent two-state controls. These are JCheckBox and JRadioButton, which are described later in this chapter. Thus, JToggleButton defines the basic functionality of all two-state components.
The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines several constructors. The one used here is
JCheckBox(String str)
adio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. They are supported by the JRadioButton class, which extends JToggleButton. JRadioButton provides several constructors. The one used in the example is shown here:
JRadioButton(String str)
Q. Components in Swings.
Swing components are basic building blocks of an application. Swing has a wide range of various components, including buttons, check boxes, sliders, and list boxes.
-JButton is in implementation of a push button. It is used to trigger an action if the user clicks on it.
-JLabel is a simple component for displaying text, images or both. It does not react to input events.
-JTextField is a text component that allows editing of a single line of non-formatted text.
-JPasswordField is a JTextField subclass that does not show the characters that the user types.
Q. Differentiate between JList and JCombobox
A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.
JComboBox
A JComboBox can be editable or read-only.
An ActionListener, ChangeListener or ItemListener interfaces can be used to handle the user actions on a JComboBox.
A getSelectedItem() method can be used to get the selected or entered item from a combo box.
JList
A JList is a component that allows the user to choose either a single selection or multiple selections.
A JList class itself does not support scrollbar. In order to add scrollbar, we have to use JScrollPane class together with the JList class. The JScrollPane then manages a scrollbar automatically.
Q. Brief Overview of the JDBC process
Ans. DBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is an standard API specification developed in order to move data from frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.
1. Loading the Driver
To begin with, you first need load the driver or register it before using it in the program . Registration is to be done once in your program. You can register a driver in one of two ways mentioned below :
Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object .The following example uses Class.forName() to load the Oracle driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time . The following example uses DriverManager.registerDriver()to register the Oracle driver –
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
2. Create the connections
After loading the driver, establish connections using :
Connection con = DriverManager.getConnection(url,user,password)
user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator. It can be created as follows:
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 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 programmer before calling the function. Use of this can be referred from final code.
3. 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();
Here, con is a reference to Connection interface used in previous step .
4. Execute the query
Now comes the most important part i.e executing the query. Query here is an SQL Query . Now we know we can have multiple types of queries. Some of them are as follows:
Query for updating / inserting table in a database.
Query for retrieving data .
The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.
The executeUpdate(sql query) method ofStatement interface is used to execute queries of updating/inserting .
Example:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is sql query of the type String
5.Close the connections
So finally we have sent the data to the specified location and now we are at the verge of completion of our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection.
Example :
con.close();
Q.Explain J2EE multitier architecture
Ans. J2EE (Java 2 Enterprise Edition) is an environment for developing and deploying enterprise applications. The J2EE platform consists of J2EE components, services, Application Programming Interfaces (APIs) and protocols that provide the functionality for developing multi-tiered and distributed Web based applications.
J2EE is four-tier architecture. These consist of Client Tier (Presentation tier or Application tier), Web tier, Enterprise JavaBeans Tier (or Application server tier), and the Enterprise Information Systems Tier or the Data tier.
Two or more tiers can physically reside on the same Java Virtual Machine although each tier provides a specific type of functionality to an application. Some of the APIs of J2EE components can be used on more than one tier (i.e. XML API), while other APIs (i.e., EJB API) or associated with a particular tier. Following diagram is representing the multi-tier architecture of J2EE.
Q. Explain JDBC packages.
Ans. JDBC 4.0 API is mainly divided into two package
java.sql
javax.sql
java.sql package
This package include classes and interface to perform almost all JDBC operation such as creating and executing SQL Queries.
javax.sql package
This package is also known as JDBC extension API. It provides classes and interface to access server-side data.
Q. What is a skeleton. Explain Entity Java Bean
An "Entity Bean" is a type of Enterprise JavaBean, a server-side Java EE component, that represents persistent data maintained in a database. An entity bean can manage its own persistence (Bean managed persistence) or can delegate this function to its EJB Container (Container managed persistence). An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash.
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:
It reads the parameter for the remote method
It invokes the method on the actual remote object, and
It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
Q. Message driven bean with an example.
Ans. A message driven bean is a stateless, server-side, transaction-aware component that is driven by a Java message (javax.jms.message). It is invoked by the EJB Container when a message is received from a JMS Queue or Topic. It acts as a simple message listener.
A Java client, an enterprise bean, a Java ServerPagesTM (JSP) component, or a non-J2EE application may send the message. The client sending the message to the destination need not be aware of the MDBs deployed in the EJB Container. However, the message must conform to JMS specifications.
Before MDBs were introduced, JMS described a classical approach to implement asynchronous method invocation. The approach used an external Java program that acted as the listener, and on receiving a message, invoked a session bean method.
package com.javatpoint;
import javax.ejb.MessageDriven;
import javax.jms.*;
@MessageDriven(mappedName="myTopic")
public class MyListener implements MessageListener{
@Override
public void onMessage(Message msg) {
TextMessage m=(TextMessage)msg;
try{
System.out.println("message received: "+m.getText());
}catch(Exception e){System.out.println(e);}
}
}
Q. J2SE and J2EE differences.
Ans.
J2SE(Java Platform, Standard Edition)
Also known as Core Java, this is the most basic and standard version of Java.It’s the purest form of Java, a basic foundation for all other editions.
It consists of a wide variety of general purpose API’s (like java.lang, java.util) as well as many special purpose APIs
J2SE is mainly used to create applications for Desktop environment.
It consist all the basics of Java the language, variables, primitive data types, Arrays, Streams, Strings Java Database Connectivity(JDBC) and much more. This is the standard, from which all other editions came out, according to the needs of the time.
The famous JVM of Java, the heart of Java development, was also given by this edition only.It’s because of this feature, that Java has such a wide usage.
J2EE(Java Platform, Enterprise Edition)
The Enterprise version of Java has a much larger usage of Java, like development of web services, networking, server side scripting and other various web based applications.
J2EE is a community driven edition, i.e. there is a lot of continuous contributions from industry experts, Java developers and other open source organizations.
J2EE uses many components of J2SE, as well as, has many new features of it’s own like Servlets, JavaBeans, Java Message Services, adding a whole new functionalities to the language.
J2EE uses HTML, CSS, JavaScript etc., so as to create web pages and web services. It’s also one of the most widely accepted web development standard.
There are also many languages like .net and php, which can do that work, but what distinguishes it from other languages is the versatility, compatibility and security features, which are not that much prominent in other languages.
Nowadays, developers are going more towards this edition, as it more versatile and web friendly that it’s other counterparts.
Apart from these three versions, there was another Java version, released Java Card.
This edition was targeted, to run applets smoothly and securely on smart cards and similar technology.
Portability and security was its main features.
Q. Session Java Bean
Ans. Session bean encapsulates business logic only, it can be invoked by local, remote and webservice client.
It can be used for calculations, database access etc.
The life cycle of session bean is maintained by the application server (EJB Container).
Types of Session Bean
There are 3 types of session bean.
1) Stateless Session Bean: It doesn't maintain state of a client between multiple method calls.
2) Stateful Session Bean: It maintains state of a client across multiple requests.
3) Singleton Session Bean: One instance per application, it is shared between clients and supports concurrent access.
-------------------------------------------------------------------------------------------------------------------------
Unit 4
Q. Servlets and their applications.
Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows:
-Better performance: because it creates a thread for each request, not process.
-Portability: because it uses Java language.
-Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.
-Secure: because it uses java language.
Servlets may be used at different levels on a distributed framework. The following are some examples of servlet usage:
To accept form input and generate HTML Web pages dynamically.
As part of middle tiers in enterprise networks by connecting to SQL databases via JDBC.
In conjunction with applets to provide a high degree of interactivity and dynamic Web content generation.
For collaborative applications such as online conferencing.
A community of servlets could act as active agents which share data with each other.
Servlets could be used for balancing load among servers which mirror the same content.
Protocol support is one of the most viable uses for servlets. For example, a file service can start with NFS and move on to as many protocols as desired; the transfer between the protocols would be made transparent by servlets. Servlets could be used for tunneling over HTTP to provide chat, newsgroup or other file server functions.
Q.Java Servlet package.
Ans. There are two packages in Java Servlet that provide various features to servlet. These two packages are javax.servlet and javax.servlet.http.
javax.servlet package: This package contains various servlet interfaces and classes which are capable of handling any type of protocol.
javax.servlet.http package: This package contains various interfaces and classes which are capable of handling a specific http type of protocol.
Q. Explain RMI.
Ans. 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.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's understand the stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes method on the stub object, it does the following tasks:
It initiates a connection with remote Virtual Machine (JVM),
It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
It waits for the result
It reads (unmarshals) the return value or exception, and
It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks:
It reads the parameter for the remote method
It invokes the method on the actual remote object, and
It writes and transmits (marshals) the result to the caller.
Q. Servlet and JSP differences.
Ans. A servlet is a Java class which 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 webs servers, however, they can respond to other types of requests too. For such applications, HTTP-specific servlet classes are defined by Java Servlet technology.
A JSP is a text document which contains two types of text: static data and dynamic data. The static data can be expressed in any text-based format (like HTML, XML, SVG and WML), and the dynamic content can be expressed by JSP elements.
Java Server Pages (JSP) is a server-side programming technology that allows the creation of a dynamic, platform-independent method for developing Web-based applications. JSP have access to the whole family of Java APIs, including the JDBC API to access enterprise databases. JavaServer Pages (JSP) is a technology for creating Web pages that support dynamic content. This helps programmers embed java code in HTML pages by making use of specific JSP tags, most of which begin with <% and end with %>. Servlets implement a component-based, platform-independent method for developing Web-based applications, without the performance restrictions of CGI programs. Servlets have access to the complete family of Java APIs, including the JDBC API to access enterprise databases. Servlets are platform-independent because they are drafted in Java.Java security manager on the server implements a set of limitations to preserve the resources on a server machine.
Q. JSP tags
Ans. here are four types of JSP tags, which are important and often required.
1. Directives
These types of tags are used primarily to import packages. Altenatively you can also use these tags to define error handling pages and for session information of JSP page.
Example:
<%@page language="java" %>
2. Declarations
JSP declarations starts with '<%!' and ends with '%>'. In this you can make declarions such as int i = 1, double pi = 3.1415 etc. If needed, you can also write Java code inside declarations.
Example 1
Code:
<%!
int radius = 7;
double pi = 3.1415;
%>
3. Scriptlets
JSP Scriptlets starts with '<%' and ends with '%>'. This is where the important Java code for JSP page is written.
Example
Code:
<%
String id, name, dob, email, address;
id = request.getParameter("id");
name = request.getParameter("name");
dob = request.getParameter("dob");
email = request.getParameter("email");
address = request.getParameter("address");
sessionEJB.addClient(id, name, dob, email, address);
%>
request, response, session and out are the variables available in scriptlets.
4.4. Expressions
JSP expressions starts with '<%=' and ends with '%>'. If you want to show some value, you need to put it in between these tags.
Example:
Code:
<%!
double radius = 7;
double pi = 22/7;
double area()
{
return pi*radius*radius;
}
%>
<html>
<body>
Area of circle is <%= area() %>
</body>
</html>
You will see the output:
Code:
Area of circle is 147.0
Q.(1) Session Tracking (2) Cookie (3) HTTPS Request and Response handling
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete description of the different types of HTTP requests is beyond the scope of this book. However, the GET and POST requests are commonly used when handling form input. Therefore, this section presents examples of these cases.
Q. Steps to Create Servlet Application using tomcat server
Ans. To create a Servlet application you need to follow the below mentioned steps. These steps are common for all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat is an open source web server for testing servlets and JSP technology. Download latest version of Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the below mentioned steps :
Create directory structure for your application.
Create a Servlet
Compile the Servlet
Create Deployement Descriptor for your application
Start the server and deploy the application
1. Creating the Directory Structure
Sun Microsystem defines a unique directory structure that must be followed to create a servlet application.
Create the above directory structure inside Apache-Tomcat\webapps directory. All HTML, static files(images, css etc) are kept directly under Web application folder. While all the Servlet classes are kept inside classes folder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.
2. Creating a Servlet
There are three different ways to create a servlet.
By implementing Servlet interface
By extending GenericServlet class
By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discussed earlier HttpServlet gives the definition of service() method of the Servlet interface. The servlet class that we will create should not override service() method. Our servlet class will override only doGet() or doPost() method.
When a request comes in for the servlet, the Web Container calls the servlet's service() method and depending on the type of request the service() method calls either the doGet() or doPost() method.
3. Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
4. Create Deployment Descriptor
Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets and JSP pages. DD is used for several important purposes such as:
Mapping URL to Servlet class.
Initializing parameters.
Defining Error page.
Security roles.
Declaring tag libraries.
5. Start the Server
Double click on the startup.bat file to start your Apache Tomcat Server.
Q. Life Cycle of a Servlet.
Ans. A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
Q. Write a program to write a cookie and read the cookie.
Cookie lets you save information to the browser that you can use to your server. With cookies, you can define some parameters eg. to know if the user is logged in. Cookies are sent to your server whenever you make a request. Think cookies like a temporary storage of parameters or information that you can get, retrieve and check.
Here is a simple cookie example that will be added to the response and to the user’s browser.
Creating a Cookie
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(HttpServletResponse response) {
//create a cookie with name 'website' and value 'javapointers'
Cookie cookie = new Cookie("website", "javapointers");
//set the expiration time
//1 hour = 60 seconds x 60 minutes
cookie.setMaxAge(60 * 60);
//add the cookie to the response
response.addCookie(cookie);
//return the jsp with the response
return "home";
}
Reading a Cookie
@RequestMapping(value = "/home/cookie", method = RequestMethod.GET)
public String readCookie(HttpServletRequest request) {
//get all cookies
Cookie[] cookies = request.getCookies();
//iterate each cookie
for (Cookie cookie : cookies) {
//display only the cookie with the name 'website'
if (cookie.getName().equals("website")) {
System.out.println(cookie.getValue());
}
}
return "home";
}
Q. EJB Transaction Attributes.
Ans. A transaction is a single unit of work items, which follows the ACID properties. ACID stands for Atomic, Consistent, Isolated, and Durable.
Atomic − If any of the work item fails, the whole unit will be considered failed. Success meant, all items execute successfully.
Consistent − A transaction must keep the system in consistent state.
Isolated − Each transaction executes independent of any other transaction.
Durable − Transaction should survive system failure if it has been executed or committed.
EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions. Transactions can be managed by the container or by custom code handling in bean's code.
Container Managed Transactions − In this type, the container manages the transaction states.
Bean Managed Transactions − In this type, the developer manages the life cycle of transaction states.
Q. What is RMI and explain Client Side and Server Side Method.
Ans. RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.
Architecture of an RMI Application
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to invoke its methods.
It is the program that runs on server dealing with the generation of content of web page.
1) Querying the database
2) Operations over databases
3) Access/Write a file on server.
4) Interact with other servers.
5) Structure web applications.
6) Process user input. For example if user input is a text in search box, run a search algorithm on data stored on server and send the results.
Client-side Programming :
It is the program that runs on the client machine (browser) and deals with the user interface/display and any other processing that can happen on client machine like reading/writing cookies.
1) Interact with temporary storage
2) Make interactive web pages
3) Interact with local storage
4) Sending request for data to server
5) Send request to server
6) work as an interface between server and user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment