Advanced Java Programming - Unit Wise Questions
1. What is multithreading? How can you write multithreaded programs in java? Discuss with suitable example.
Multithreading is a process of executing two or more threads simultaneously to maximum utilization of CPU. A thread is a lightweight sub-process, the smallest unit of processing.
Multithreaded program can be created by using two mechanisms:
1. By extending Thread class
Thread class provide constructors and methods to create and perform operations on a thread. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Example:
class First extends Thread
{
@Override
public
void run()
{
for
(int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public
void run()
{
for
(int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public
static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}
2. By implementing Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run() which is used to perform action for a thread. The start() method of Thread class is used to start a newly created thread.
Example:
public class ExampleClass implements Runnable {
@Override
public void run() {
System.out.println("Thread has ended");
}
public static void main(String[] args) {
ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}
AI is thinking...
1. What is multithreading? Why is it important to develop in computer programs? Discuss life cycle of thread in detail.
The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Multithreading is important due to following reasons:
- It doesn't block the user because threads are independent and we can perform multiple operations at the same time.
- We can perform many operations together, so it saves time.
- Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Example:
Program to create two threads. The first thread should print numbers from 1 to 10 at intervals of 0.5 second and the second thread should print numbers from 11 to 20 at the interval of 1 second.
class First extends Thread
{
@Override
public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}
Life Cycle of Thread
A thread in Java at any point of time exists in any one of the following states.
- New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. In simple words, a thread has been created, but it has not yet been started. A thread is started by calling its start() method.
- Runnable: The thread is in the runnable state after the invocation of start() method, but the thread scheduler has not selected it to be the running thread. A thread starts life in the Ready-to-run state by calling the start method and wait for its turn. The thread scheduler decides which thread runs and for how long.
- Running: When the thread starts executing, then the state is changed to a “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
- Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in “dead state”. Once a thread is in this state, the thread cannot even run again.
- Blocked (Non-runnable state):This is the state when the thread is still alive but is currently not eligible to run. A thread that is blocked waiting for a monitor lock is in this state. A running thread can transit to one of the non-runnable states depending on the situation. A thread remains in a non-runnable state until a special transition occurs. A thread doesn’t go directly to the running state from a non-runnable state but transits first to the Ready-to-run state.
AI is thinking...
1. What is interface? How can you use the concept of interface to achieve multiple inheritance? Discuss with suitable example.
An interface in Java is a blueprint of a class. It has static constants and abstract methods. An interface is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in java.
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.
In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat { void eat(); } interface AnimalTravel { void travel(); } class Animal implements AnimalEat, AnimalTravel { public void eat() { System.out.println("Animal is eating"); } public void travel() { System.out.println("Animal is travelling"); } }
AI is thinking...
1. What are exceptions? Why is it important to handle exceptions? Discuss different keywords that are used to handle exception. (2+2+6)
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling.
Java provides five keywords that are used to handle the exception.
1. try: The "try" keyword is used to specify a block where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.
2. Catch: The "catch" block is used to handle the exception. This block must follow the try block and a single try block can have several catch blocks associated with it. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. It can be followed by finally block later.
3. Finally: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
4. throw: The "throw" keyword is used to throw an exception.
5. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Example:
class TestExceptions {
static void myMethod(int testnum) throws Exception {
System.out.println ("start - myMethod");
if (testnum == 12)
throw new Exception();
System.out.println("end - myMethod");
return;
}
public static void main(String args[]) {
int testnum = 12;
try {
System.out.println("try - first statement");
myMethod(testnum);
System.out.println("try - last statement");
}
catch ( Exception ex) {
System.out.println("An Exception");
}
finally {
System. out. println( "finally") ;
}
System.out.println("Out of try/catch/finally - statement");
}
}
Output:
try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement
AI is thinking...
1. Define inheritance. Discuss the benefits of using inheritance. Discuss multiple inheritance with suitable example.(1+2+7)
Inheritance is a concept that acquires the properties from one class to other classes. A class can inherit attributes and methods from another class. The class that inherits the properties is known as the sub-class or the child class. The class from which the properties are inherited is known as the superclass or the parent class.
Benefits of Inheritance
- Inheritance helps in code reuse. The child class may use the code defined in the parent class without re-writing it.
- Inheritance can save time and effort as the main code need not be written again.
- Inheritance provides a clear model structure which is easy to understand.
- An inheritance leads to less development and maintenance costs.
- With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.
- In inheritance base class can decide to keep some data private so that it cannot be altered by the derived class.
Multiple Inheritance
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat { void eat(); } interface AnimalTravel { void travel(); } class Animal implements AnimalEat, AnimalTravel { public void eat() { System.out.println("Animal is eating"); } public void travel() { System.out.println("Animal is travelling"); } }
AI is thinking...
1. What is exception handling? Discuss the use of each keyword (try, catch, throw, throws and finally) with suitable Java program.
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
Exception handling is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained. Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling
Java provides five keywords that are used to handle the exception.
1. try: The "try" keyword is used to specify a block where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.
2. Catch: The "catch" block is used to handle the exception. This block must follow the try block and a single try block can have several catch blocks associated with it. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. It can be followed by finally block later.
3. Finally: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
4. throw: The "throw" keyword is used to throw an exception.
5. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Example:
class TestExceptions {
static void myMethod(int testnum) throws Exception {
System.out.println ("start - myMethod");
if (testnum == 12)
throw new Exception();
System.out.println("end - myMethod");
return;
}
public static void main(String args[]) {
int testnum = 12;
try {
System.out.println("try - first statement");
myMethod(testnum);
System.out.println("try - last statement");
}
catch ( Exception ex) {
System.out.println("An Exception");
}
finally {
System. out. println( "finally") ;
}
System.out.println("Out of try/catch/finally - statement");
}
}
Output:
try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement
AI is thinking...
1. What is exception handling? Discuss exception handling in detail with suitable example.
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
Exception handling is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained. Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling
Java provides five keywords that are used to handle the exception.
1. try: The "try" keyword is used to specify a block where an exception can occur. It is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.
2. Catch: The "catch" block is used to handle the exception. This block must follow the try block and a single try block can have several catch blocks associated with it. When an exception occurs in a try block, the corresponding catch block that handles that particular exception executes. It can be followed by finally block later.
3. Finally: A finally block contains all the crucial statements that must be executed whether an exception occurs or not. The statements present in this block will always execute, regardless an exception occurs in the try block or not such as closing a connection, stream etc.
4. throw: The "throw" keyword is used to throw an exception.
5. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Example:
class TestExceptions {
static void myMethod(int testnum) throws Exception {
System.out.println ("start - myMethod");
if (testnum == 12)
throw new Exception();
System.out.println("end - myMethod");
return;
}
public static void main(String args[]) {
int testnum = 12;
try {
System.out.println("try - first statement");
myMethod(testnum);
System.out.println("try - last statement");
}
catch ( Exception ex) {
System.out.println("An Exception");
}
finally {
System. out. println( "finally") ;
}
System.out.println("Out of try/catch/finally - statement");
}
}
Output:
try - first statement
start - myMethod
An Exception
finally
Out of try/catch/finally - statement
AI is thinking...
2. Why do we need to handle the exception? Distinguish error and exception, Write a program to demonstrate your own exception class. [1+2+7]
An exception is an event that occurs during the execution of a program and that disrupts the normal flow of instructions. Java exceptions are specialized events that indicate something bad has happened in the application, and the application either needs to recover or exit.
Exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling
Error vs Exception
Error | Exception |
An error is caused due to lack of system resources. | An exception is caused because of the code. |
An error is irrecoverable. | An exception is recoverable. |
There is no means to handle an error by the program code. | Exceptions are handled using three keywords "try", "catch", and "throw". |
It belongs to java.lang.error | It belongs to java.lang.Exception |
As the error is detected the program will terminated abnormally. | As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly. |
Errors are classified as unchecked type. | Exceptions are classified as checked or unchecked type. |
E.g. Java.lang.StackOverFlow, java.lang.OutOfMemoryError | E.g. SQLException, IOException, ArrayIndexOutOfBoundException |
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.
Example:
class CustomException extends Exception { String message; CustomException(String str) { message = str; } public String toString() { return ("Custom Exception Occurred : " + message); } } public class MainException { public static void main(String args[]) { try { throw new CustomException("This is a custom message"); } catch(CustomException e) { System.out.println(e); } } }
AI is thinking...
3. Describe the responsibility of Serializable interface. Write a program to read an input string from
the user and write the vowels of that string in VOWEL.TXT and consonants in CONSOLNANT.TXT
(2+8)
AI is thinking...
4.Write an object oriented program to find area and perimeter of rectangle. (5)
AI is thinking...
4. How do you achieve multiple inheritance in java? Discuss.
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.
In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat { void eat(); } interface AnimalTravel { void travel(); } class Animal implements AnimalEat, AnimalTravel { public void eat() { System.out.println("Animal is eating"); } public void travel() { System.out.println("Animal is travelling"); } }
AI is thinking...
4. Write an object oriented program in Java to find the area of circle.
AI is thinking...
4. Write an object oriented program to find the area and perimeter of rectangle.
AI is thinking...
4. Discuss the use of interfaces to achieve multiple inheritance. (5)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces. To implement multiple interfaces, separate them with a comma.
In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat { void eat(); } interface AnimalTravel { void travel(); } class Animal implements AnimalEat, AnimalTravel { public void eat() { System.out.println("Animal is eating"); } public void travel() { System.out.println("Animal is travelling"); } }
AI is thinking...
4. What is package? How can you create your own package in Java? Explain with example.(1+4)
AI is thinking...
5. Write the simple java program that reads data from one file and writes data to another file.
Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
AI is thinking...
5. Write a simple java program that reads data from one file and writes data to another file.
Let us suppose we have a file named “test.txt”
in D-drive. Now we first read from this file character-by-character and later
we write the contents of this file to another file say “testwrite.txt” in
E-drive. For these tasks, we use the character stream classes namely FileReader
and FileWriter. The code is given below:
import java.io.FileReader;
import
java.io.FileWriter;
import java.io.IOException;
public
class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new
FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
AI is thinking...
5. Discuss the use of multithreading with suitable example. (5)
The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Example:
Program to create two threads. The first thread
should print numbers from 1 to 10 at intervals of 0.5 second and the second
thread should print numbers from 11 to 20 at the interval of 1 second.
class First extends Thread
{
@Override
public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}
AI is thinking...
5. Write a simple java program that reads data from one file and writes the data to another file (5)
Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
AI is thinking...
4. Define class. How do you create a class in Java? Differentiate class with interface.
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.
To create a class, use the keyword class.
Syntax:
Class vs Interface
AI is thinking...
6. Write a simple java program to read from and write to files.
Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
AI is thinking...
5. Write a simple Java program that reads a file named "Test.txt" and displays its contents.
import
java.io.FileReader;
import
java.io.IOException;
public
class FileReaderDemo {
public static void main(String[] args) {
try {
FileReader fr = new
FileReader("Test.txt");
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
AI is thinking...
4. An array is called balanced if it's even numbered elements (a[0], a[2], etc.) are even and its odd numbered elements (a[1], a[3],etc.) are Odd. Write a function named is Balanced that accepts an array of integers and returns 1 if the array is balanced otherwise it returns 0. [5]
AI is thinking...
4. A non-empty array A of length n is called on array of all possibilities if it contains all numbers
between 0 and A.length-1 inclusive. Write a method named isAllPossibilities that accepts an integer
array and returns 1 if the array is an array of all possiblities, otherwise it returns 0. (15)
public static int isAllPossibilities(int[] a)
{
int isAllPosibilities = 1;
if (a.Length == 0) isAllPosibilities = 0;
for (int i = 0; i < a.Length && isAllPosibilities==1; i++)
{
int index = -1;
for (int j = 0; j < a.Length && index==-1; j++)
{
if (i == a[j]) index = j;
}
if (index == -1)
isAllPosibilities = 0;
}
return isAllPosibilities;
}
AI is thinking...
6. Explain the importance of exception handling with suitable example.
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
Java exception handling is important because it helps maintain the normal, desired flow of the program even when unexpected events occur. If Java exceptions are not handled, programs may crash or requests may fail. Suppose there are 10 statements in a program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling.
Example:
class Example { 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"); } } }
AI is thinking...
6. Define the chain of constructor. What is the purpose of private constructor? [5]
Chain of constructor is the process of calling one constructor from another constructor with respect to current object. Constructor chaining can be done in two ways:
- Within same class: It can be done using this() keyword for constructors in same class
- From base class: by using super() keyword to call constructor from the base class
The main purpose of using a private constructor is to restrict object creation. We also use private constructors to implement the singleton design pattern.
Example:
public class A
{
//craeting a private constructor
private A()
{
}
void display()
{
System.out.println("Private Constructor");
}
}
private class Test
{
public static void main(String args[])
{
//compile time error
A obj = new A();
}
}
AI is thinking...
8. Write a simple java program to read from and write to files.
Let us suppose we have a file named “test.txt” in D-drive. Now we first read from this file character-by-character and later we write the contents of this file to another file say “testwrite.txt” in E-drive. For these tasks, we use the character stream classes namely FileReader and FileWriter. The code is given below:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWrite {
public static void main(String []args) {
try
{
FileReader fr = new FileReader("D:\\\\test.txt");
FileWriter fw = new FileWriter("E:\\\\testwrite.txt");
int c;
while((c=fr.read())!=-1) {
fw.write(c);
System.out.print((char)c);
}
fr.close();
fw.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
AI is thinking...
8. Discuss any five classes to handle files in java. (5)
AI is thinking...
9. Why multithreading is important in programming? Discuss.
The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Multithreading is important due to following reasons:
- It doesn't block the user because threads are independent and we can perform multiple operations at the same time.
- We can perform many operations together, so it saves time.
- Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Example:
Program to create two threads. The first thread should print numbers from 1 to 10 at intervals of 0.5 second and the second thread should print numbers from 11 to 20 at the interval of 1 second.
class First extends Thread
{
@Override
public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}
AI is thinking...
7. When does the finally block is mandatory in while handling exception? Describe with a suitable scenario. (5)
Java finally block is a block used to execute important code such as closing the connection, etc. It is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.
- finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
- The important statements to be printed can be placed in the finally block.
Example:
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed ");
}
System.out.println("rest of the code...");
}
}
AI is thinking...
10. Discuss any 5 exception classes in java.
Given below is a list of the exceptions classes:
- ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation like divide by zero.
- ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
- ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found.
- FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
- IOException: It is thrown when an input-output operation failed or interrupted.
Example of Arithmetic Exception:
AI is thinking...
9. Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [2+3]
Life Cycle of Thread
A thread in Java at any point of time exists in any one of the following states.
- New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. In simple words, a thread has been created, but it has not yet been started. A thread is started by calling its start() method.
- Runnable: The thread is in the runnable state after the invocation of start() method, but the thread scheduler has not selected it to be the running thread. A thread starts life in the Ready-to-run state by calling the start method and wait for its turn. The thread scheduler decides which thread runs and for how long.
- Running: When the thread starts executing, then the state is changed to a “running” state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
- Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in “dead state”. Once a thread is in this state, the thread cannot even run again.
- Blocked (Non-runnable state):This is the state when the thread is still alive but is currently not eligible to run. A thread that is blocked waiting for a monitor lock is in this state. A running thread can transit to one of the non-runnable states depending on the situation. A thread remains in a non-runnable state until a special transition occurs. A thread doesn’t go directly to the running state from a non-runnable state but transits first to the Ready-to-run state.
Program to execute multiple threads in priority base
class First extends Thread
{
@Override
public
void run()
{
for
(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}
}
class Second extends Thread
{
@Override
public
void run()
{
for
(int i = 11; i <= 20; i++)
{
System.out.println(i);
}
}
}
class Third extends Thread
{
@Override
public
void run()
{
for
(int i = 21; i <= 30; i++)
{
System.out.println(i);
}
}
}
public class ThreadPriority
{
public
static void main(String[] args) throws InterruptedException
{
Thread t1 = new First();
Thread t2 = new Second();
Thread t3 = new Third();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
AI is thinking...
10. Why multiple inheritance is not allowed in Java using classes? Give an example.(5)
Multiple inheritance is where we inherit the properties and behavior of multiple classes to a single class. In java, multiple inheritance is not supported because of ambiguity problem. We can take the below example where we have two classes Class1 and Class2 which have same method display(). If multiple inheritance is possible than Test class can inherit data members and methods of both Class1 and Class2 classes. Now, Test class have two display() methods inherited from Class1 and Class2. Problem occurs in method call, when display() method will be called with Test class object which method will be called, will it be of Class1 or Class2. This is ambiguity problem because of which multiple inheritance is not allowed in java.
Example:
class Class1{
public void display(){
System.out.println("Class 1 Display Method");
}
}
class Class2{
public void display(){
System.out.println("Class 2 Display");
}
}
public class Test extends Class1, Class2{
public static void main(String args[]){
Test obj = new Test();
//Ambiguity problem in method call which class display() method will be called.
obj.display();
}
}
AI is thinking...
10. When do we use final method and final class? Differentiate between function overloading and function overriding.[2+3]
AI is thinking...
13. Write short note on:
a. Multithreading
b. RMI architecture
AI is thinking...
13. Write short notes on: (2.5+2.5)
a) Multithreading
b) JSP
AI is thinking...
13. Write short note on:
a. Interface
b. Servlet
AI is thinking...
12. Why synchronization in essential in multithreading? Describe.
(5)
Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.
If we do not use synchronization, and let two or more threads access a shared resource at the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution and save certain values in a file temporary.txt which will be used to calculate some result when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will return wrong result.
To prevent such problems, synchronization was introduced. With synchronization in above case, once T1 starts using temporary.txt file, this file will be locked(LOCK mode), and no other thread will be able to access or modify it until T1 returns.
AI is thinking...
13. Write short notes on.[2.5+2.5]
a. JAVA beans and JAR file
b. MVC design pattern
a. JAVA beans and JAR file
b. MVC design pattern
MVC design pattern is also known as Model-View-Controller. It is a common architectural pattern which is used to design and create interfaces and the structure of an application. This pattern divides the application into three parts that are dependent and connected to each other.
1. Model: The Model contains only the pure application data. It doesn’t contain any information on how to show the data to the user. It is independent of the user interface. It controls the logic and rules of application.
2. View: 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.
3. Controller: The Controller acts as an interface between View and Model. It receives the user requests and processes them, including the necessary validations. The requests are then sent to model for data processing. Once they are processed, the data is again sent back to the controller and then displayed on the view.
AI is thinking...
2. Write a Java program to find the sum of two numbers using swing components. Use text fields for input and output. Your program displays output if you press any key in keyboard. Use key adapter to handle events.
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Addition
{
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame();
Addition()
{
l1 = new JLabel("First Number:");
t1 = new JTextField();
l2 = new JLabel("Second Number:");
t2 = new JTextField();
l3 = new JLabel("Press any key");
t3 = new JTextField();
t3.addkeyListener(new keychecker());
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.setSize(250,150);
f.setLayout(new GridLayout(3,2));
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
}
class keychecker extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
JOptionPane.showMessageDialog(f, "The sum is" +sum);
t3.setText(null);
}
public static void main(String args[])
{
new Addition();
}
}
AI is thinking...
1. Design a GUI form using swing with a text field, a text label for displaying the input message “Input any String”, and three buttons with caption CheckPalindrome, Reverse, FindVowels. Write a complete program for above scenario and for checking palindrome in first button, reverse it after clicking second button and extract the vowels from it after clicking third button. (10)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Palindrome extends JFrame
{
public static void main(String[] args)
{
Palindrome frame = new Palindrome();
frame.setVisible(true);
}
public Palindrome()
{
setLayout(new GridLayout(4,1,10,20));
JLabel inputLabel = new JLabel("Input any String: ");
JTextField inputTextField = new JTextField(20);
add(inputLabel);
add(inputTextField);
JLabel outputLabel = new JLabel("Output: ");
JTextField outputTextField = new JTextField(20);
add(outputLabel);
add(outputTextField);
outputTextField.setEditable(false);
JButton checkPalindromeButton = new JButton("Check Palindrome");
add(checkPalindromeButton);
JButton reverseButton = new JButton("Reverse");
add(reverseButton);
JButton findVowelButton = new JButton("Find Vowel");
add(findVowelButton);
checkPalindromeButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String copyUserInput="";
String userInput = inputTextField.getText();
int length = userInput.length();
for (int i = length-1; i>=0; i-- )
{
copyUserInput = copyUserInput + userInput.charAt(i);
}
if (copyUserInput.equalsIgnoreCase(userInput))
{
outputTextField.setText("String is palindrome.");
}
else
{
outputTextField.setText("String isn't a palindrome.");
}
}
});
reverseButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String reverseUserInput="";
String userInput = inputTextField.getText();
int length = userInput.length();
for (int i = length-1; i>=0; i-- )
{
reverseUserInput = reverseUserInput + userInput.charAt(i);
}
outputTextField.setText("Reverse String is: "+ reverseUserInput);
}
});
findVowelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
char[] vowel={'a','e','i','o','u','A','E','I','O','U'};
String userInput = inputTextField.getText();
int length = userInput.length();
char[] extractedVowel= new char[length];
String showVowel="";
for (int i =0; i<=length-1; i++ )
{
for (int j = 0; j<=vowel.length-1; j++)
{
if(userInput.charAt(i)== vowel[j])
{
extractedVowel[i] = userInput.charAt(i);
showVowel = showVowel + String.valueOf(extractedVowel[i]); //append the extractedVowel to string variable so that it can be displayed at once in a textfield in the form of string.
}
}
}
outputTextField.setText("Vowels: "+showVowel);
}
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
AI is thinking...
2. Write a program using swing components to add two numbers. Use text fields for inputs and output. Your program should display the result when the user presses a button. (10)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Addition extends JFrame implements ActionListener //implement listener interface
{
JLabel l1, l2;
JTextField t1, t2, t3;
JButton b1;
public Addition()
{
l1 = new JLabel("First Number:");
l1.setBounds(20, 10, 100, 20); //x, y, width, height
t1 = new JTextField(10);
t1.setBounds(120, 10, 100, 20);
l2 = new JLabel("Second Number:");
l2.setBounds(20, 40, 100, 20);
t2 = new JTextField(10);
t2.setBounds(120, 40, 100, 20);
b1 = new JButton("Sum");
b1.setBounds(20, 70, 80, 20);
t3 = new JTextField(10);
t3.setBounds(120, 70, 100, 120);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this); //Registering event
setSize(400,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) //Handle Event
{
if(e.getSource()==b1){
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
public static void main(String args[])
{
new Addition();
}
}
AI is thinking...
2. Write a program using swing components to find simple interest. Use text fields for inputs and output. Your program should display the result when the user presses a button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class SimpleInterest extends JFrame implements ActionListener //implement listener interface
{
JLabel l1, l2, l3;
JTextField t1, t2, t3, t4;
JButton b1;
public SimpleInterest()
{
l1 = new JLabel("Principal:");
l1.setBounds(20, 10, 100, 20); //x, y, width, height
t1 = new JTextField(10);
t1.setBounds(120, 10, 100, 20);
l2 = new JLabel("Time:");
l2.setBounds(20, 40, 100, 20);
t2 = new JTextField(10);
t2.setBounds(120, 40, 100, 20);
l3 = new JLabel("Rate:");
l3.setBounds(20, 70, 100, 20);
t3 = new JTextField(10);
t3.setBounds(120, 70, 100, 20);
b1 = new JButton("Simple Interest");
b1.setBounds(20, 100, 80, 20);
t4 = new JTextField(10);
t4.setBounds(120, 100, 100, 20);
add(l1);
add(t1);
add(l2);
add(t2);
add(l1);
add(t3);
add(b1);
add(t4);
b1.addActionListener(this); //Registering event
setSize(400,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) //Handle Event
{
if(e.getSource()==b1){
double P = Double.parseDouble(t1.getText());
double T = Double.parseDouble(t2.getText());
double R = Double.parseDouble(t3.getText());
double SI = (P*T*R)/100;
t4.setText(String.valueOf(SI));
}
public static void main(String args[])
{
new SimpleInterest() ;
}
}
AI is thinking...
2. Write a program using swing components to multiply two numbers. Use text fields for inputs and output. Your program should display the result when the user press a button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Multiplication extends JFrame implements ActionListener //implement listener interface
{
JLabel l1, l2;
JTextField t1, t2, t3;
JButton b1;
public Multiplication()
{
l1 = new JLabel("First Number:");
l1.setBounds(20, 10, 100, 20); //x, y, width, height
t1 = new JTextField(10);
t1.setBounds(120, 10, 100, 20);
l2 = new JLabel("Second Number:");
l2.setBounds(20, 40, 100, 20);
t2 = new JTextField(10);
t2.setBounds(120, 40, 100, 20);
b1 = new JButton("Product");
b1.setBounds(20, 70, 80, 20);
t3 = new JTextField(10);
t3.setBounds(120, 70, 100, 120);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this); //Registering event
setSize(400,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) //Handle Event
{
if(e.getSource()==b1){
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int product = num1 * num2;
t3.setText(String.valueOf(product));
}
public static void main(String args[])
{
new Multiplication();
}
}
AI is thinking...
2. What is layout management? Discuss any three layout management classes with example of each.
The layout management is used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms. The layout management classes are given below:
1. Border Layout
The BorderLayout is used
to arrange the components in five regions: north, south, east, west and center.
Each region (area) may contain one component only.
Components of the BorderLayout Manager
·
BorderLayout.NORTH
·
BorderLayout.SOUTH
·
BorderLayout..EAST
·
BorderLayout.WEST
·
BorderLayout.CENTER
BorderLayout
Constructors:
BorderLayout() |
creates a border layout but with no gaps
between the components. |
BorderLayout(int hgap, int vgap) |
creates a border layout with the given
horizontal and vertical gaps between the components. |
Example:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutExample {
BorderLayoutExample(){
JFrame f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
2. Flow Layout
The FlowLayout is used to arrange the
components in a line, one after another (in a flow). It arranges
components in a line, if no space left remaining components goes to next line. Align
property determines alignment of the components as left, right, center etc.
FlowLayout Constructors:
FlowLayout()
|
creates a flow layout with centered alignment
and a default 5 unit horizontal and vertical gap. |
FlowLayout(int align) |
creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap. |
FlowLayout(int align, inthgap,
intvgap) |
creates a flow layout with the given alignment
and the given horizontal and vertical gap. |
Example:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayoutExample {
FlowLayoutExample(){
JFrame f = new JFrame("Flow Layout");
JButton b1 = new JButton("button 1");
JButton b2 = new JButton("button 2");
JButton b3 = new JButton("button 3");
JButton b4 = new JButton("button 4");
JButton b5 = new JButton("button 5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout());
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutExample();
}
}
3. Grid Layout
The GridLayout is used to arrange the components in
rectangular grid. One component is displayed in each rectangle. Components are placed
in columns and rows.
Every Component in a GridLayout has the same width and
height. Components are added to a GridLayout starting at the top-left cell of
the grid and proceeding left to right until the row is full. Then the process
continues left to right on the next row of the grid, and so on.
GridLayout Constructors:
GridLayout() |
creates a grid layout with one column per
component in a row. |
GridLayout(int rows, int cols) |
creates a grid layout with the given rows and
columns but no gaps between the components. |
GridLayout(int rows, int cols, int int hgap,
int vgap) |
creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps. |
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
JButton b1, b2, b3, b4, b5, b6;
GridDemo()
{
JFrame f = new JFrame("GridLayoutDemo");
b1 = new JButton("A");
b2 = new JButton("B");
b3 = new JButton("C");
b4 = new JButton("D");
b5 = new JButton("E");
b6 = new JButton("F");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2, 3));
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String args[])
{
new GridDemo();
}
}
AI is thinking...
3. Write a program using swing components to find simple interest. Use text fields for inputs and output. Your program should display output if the user clicks a button. (10)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class SimpleInterest extends JFrame implements ActionListener //implement listener interface
{
JLabel l1, l2, l3;
JTextField t1, t2, t3, t4;
JButton b1;
public SimpleInterest()
{
l1 = new JLabel("Principal:");
l1.setBounds(20, 10, 100, 20); //x, y, width, height
t1 = new JTextField(10);
t1.setBounds(120, 10, 100, 20);
l2 = new JLabel("Time:");
l2.setBounds(20, 40, 100, 20);
t2 = new JTextField(10);
t2.setBounds(120, 40, 100, 20);
l3 = new JLabel("Rate:");
l3.setBounds(20, 70, 100, 20);
t3 = new JTextField(10);
t3.setBounds(120, 70, 100, 20);
b1 = new JButton("Simple Interest");
b1.setBounds(20, 100, 80, 20);
t4 = new JTextField(10);
t4.setBounds(120, 100, 100, 20);
add(l1);
add(t1);
add(l2);
add(t2);
add(l1);
add(t3);
add(b1);
add(t4);
b1.addActionListener(this); //Registering event
setSize(400,300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) //Handle Event
{
if(e.getSource()==b1){
double P = Double.parseDouble(t1.getText());
double T = Double.parseDouble(t2.getText());
double R = Double.parseDouble(t3.getText());
double SI = (P*T*R)/100;
t4.setText(String.valueOf(SI));
}
public static void main(String args[])
{
new SimpleInterest() ;
}
}
AI is thinking...
2. You are hired by a reputed software company which is going to design an application for "Movie
Rental System". Your responsibility is to design a schema named MRS and create a table named
Movie(id, Tille, Genre, Language, Length). Write a program to design a GUI form to take input for
this table and insert the data into table after clicking the OK button
(10)
AI is thinking...
5. Why do we need swing components ? Explain the uses of check boxes and radio buttons in GUI programming. (2+3)
AI is thinking...
6.Discuss grid layout with example.
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.
Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.
GridLayout Constructors:
GridLayout() | creates a grid layout with one column per component in a row. |
GridLayout(int rows, int cols) | creates a grid layout with the given rows and columns but no gaps between the components. |
GridLayout(int rows, int cols, int int hgap, int vgap) | creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. |
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
JButton b1, b2, b3, b4, b5, b6;
GridDemo()
{
JFrame f = new JFrame("GridLayoutDemo");
b1 = new JButton("A");
b2 = new JButton("B");
b3 = new JButton("C");
b4 = new JButton("D");
b5 = new JButton("E");
b6 = new JButton("F");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2, 3));
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String args[])
{
new GridDemo();
}
}
AI is thinking...
6. Discuss border layout with example.
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.
Components of the BorderLayout Manager
· BorderLayout.NORTH
· BorderLayout.SOUTH
· BorderLayout..EAST
· BorderLayout.WEST
· BorderLayout.CENTER
BorderLayout Constructors:
BorderLayout() | creates a border layout but with no gaps between the components. |
BorderLayout(int hgap, int vgap) | creates a border layout with the given horizontal and vertical gaps between the components. |
Example:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutExample {
BorderLayoutExample(){
JFrame f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
AI is thinking...
6. What are the benefits of using swing components? Explain.
Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich set of widgets. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu etc.
The benefits of using swing components are
- 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.
- Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI.
- Swing provides "extras" for components, such as: Icons on many components Decorative borders for components
- Tool tips 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
AI is thinking...
7. Discuss grid layout with suitable example. (5)
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.
Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.
GridLayout Constructors:
GridLayout() | creates a grid layout with one column per component in a row. |
GridLayout(int rows, int cols) | creates a grid layout with the given rows and columns but no gaps between the components. |
GridLayout(int rows, int cols, int int hgap, int vgap) | creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. |
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
JButton b1, b2, b3, b4, b5, b6;
GridDemo()
{
JFrame f = new JFrame("GridLayoutDemo");
b1 = new JButton("A");
b2 = new JButton("B");
b3 = new JButton("C");
b4 = new JButton("D");
b5 = new JButton("E");
b6 = new JButton("F");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2, 3));
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String args[])
{
new GridDemo();
}
}
AI is thinking...
7. Discuss group layout with suitable example.
GroupLayout groups its components and places them in a Container hierarchically. The grouping is done by instances of the Group class. Group is an abstract class, and two concrete classes which implement this Group class are SequentialGroup and ParallelGroup. SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns its child on top of each other. The GroupLayout class provides methods such as createParallelGroup() and createSequentialGroup() to create groups.
GroupLayout treats each axis independently. That is, there is a group representing the horizontal axis, and a group representing the vertical axis. Each component must exist in both a horizontal and vertical group, otherwise an IllegalStateException is thrown during layout or when the minimum, preferred, or maximum size is requested.
Example:
import java.awt.*;
import javax.swing.*;
public class GroupExample {
public static void main(String[] args) {
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPanel = frame.getContentPane();
GroupLayout groupLayout = new GroupLayout(contentPanel);
contentPanel.setLayout(groupLayout);
JLabel clickMe = new JLabel("Click Here");
JButton button = new JButton("This Button");
groupLayout.setHorizontalGroup(
groupLayout.createSequentialGroup()
.addComponent(clickMe)
.addGap(10, 20, 100)
.addComponent(button));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(clickMe)
.addComponent(button));
frame.pack();
frame.setVisible(true);
}
}
AI is thinking...
6. Why do we need layout management? What is GridBag layout?
The layout management is used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
GridBagLayout is one of
the most flexible — and complex — layout managers the Java platform provides. A
GridBagLayout places components in a grid of rows and columns, allowing
specified components to span multiple rows or columns. Not all rows necessarily
have the same height.Similarly, not all columns necessarily have the same
width. Essentially, GridBagLayout places components in rectangles (cells) in a
grid, and then uses the components' preferred sizes to determine how big the
cells should be. The way the program specifies the size and position
characteristics of its components is by specifying constraints for each
component using GridBagConstraints object, as demonstrated below:
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
AI is thinking...
7. Discuss MVC design pattern with example.
MVC design pattern is also known as Model-View-Controller. It is a common architectural pattern which is used to design and create interfaces and the structure of an application. This pattern divides the application into three parts that are dependent and connected to each other.
1. Model: The Model contains only the pure application data. It doesn’t contain any information on how to show the data to the user. It is independent of the user interface. It controls the logic and rules of application.
2. View: 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.
3. Controller: The
Controller acts as an interface between View and Model. It receives the
user requests and processes them, including the necessary validations. The
requests are then sent to model for data processing. Once they are processed,
the data is again sent back to the controller and then displayed on the
view.
AI is thinking...
8. Discuss border layout with suitable example.
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.
Components of the BorderLayout Manager
· BorderLayout.NORTH
· BorderLayout.SOUTH
· BorderLayout..EAST
· BorderLayout.WEST
· BorderLayout.CENTER
BorderLayout Constructors:
BorderLayout() | creates a border layout but with no gaps between the components. |
BorderLayout(int hgap, int vgap) | creates a border layout with the given horizontal and vertical gaps between the components. |
Example:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutExample {
BorderLayoutExample(){
JFrame f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
AI is thinking...
6. What is the task of Layout manager? Describe about default layout manager.
(1 +4)
The layout managers are used to arrange components in a particular manner. The Java LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
Border layout is the default layout manager for windows and dialog boxes.
Border Layout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only.
Components of the BorderLayout Manager
· BorderLayout.NORTH
· BorderLayout.SOUTH
· BorderLayout..EAST
· BorderLayout.WEST
· BorderLayout.CENTER
BorderLayout Constructors:
BorderLayout() | creates a border layout but with no gaps between the components. |
BorderLayout(int hgap, int vgap) | creates a border layout with the given horizontal and vertical gaps between the components. |
Example:
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BorderLayoutExample {
BorderLayoutExample(){
JFrame f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}
}
AI is thinking...
13. Write short notes on:[2.5+2.5]
a. Grid Layout
b. Ragged Array
a. Grid Layout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Components are placed in columns and rows.
Every Component in a GridLayout has the same width and height. Components are added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is full. Then the process continues left to right on the next row of the grid, and so on.
GridLayout Constructors:
GridLayout() | creates a grid layout with one column per component in a row. |
GridLayout(int rows, int cols) | creates a grid layout with the given rows and columns but no gaps between the components. |
GridLayout(int rows, int cols, int int hgap, int vgap) | creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. |
Example:
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
JButton b1, b2, b3, b4, b5, b6;
GridDemo()
{
JFrame f = new JFrame("GridLayoutDemo");
b1 = new JButton("A");
b2 = new JButton("B");
b3 = new JButton("C");
b4 = new JButton("D");
b5 = new JButton("E");
b6 = new JButton("F");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.setLayout(new GridLayout(2, 3));
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String args[])
{
new GridDemo();
}
}
b. Ragged Array
Ragged arrays are arrays of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
Syntax: int array_name = new int[row_size][column size];
Output:
AI is thinking...
1. Compare AWT with Swing. Write a GUI program using components to find sum and difference of two numbers.Use two text fields for giving input and a label for output. The program should display sum if user presses mouse and difference if user release mouse.(2+8)
AI is thinking...
2. why do we need event handling? Discuss the process of handling events with example. Differentiate event listener interface with adapter class. (3+4+3)
Change in the state of an object is known as event. Events are generated as result of user interaction with the graphical user interface components. For example, click on button, dragging mouse, entering a character through keyboard, selecting an item from list etc.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Event handling has three main components,
- Events : An event is a change of state of an object.
- Events Source : Event source is an object that generates an event.
- Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.
A source generates an Event and send it to one or more listeners. Listener waits until it receives an event. Once the event is received, the listener process the event and then returns. Listener needs to be registered with the source object so that the listener can receive the event notification. There are three things that are done in event handling:
1. Create a class that represents the event handler.
2. Implement an appropriate interface called “event listener interface” in the above class.
3. Register the event handler
The event listeners listen for a particular event and whenever the event occurs they fire the action that is registered for them.
Example
import java.awt.event.*;
import javax.swing.*;
public class EventListener extends JFrame implements
ActionListener {
public
EventListener(){
JButton btn =
new JButton("Click Me");
add(btn);
btn.addActionListener(this);
//registering the event handler
setSize(100,
100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Hello");
}
public static void main(String []a) {
new
EventListener();
}
}
Here, whenever the “Click Me” button is clicked, an event is generated and a particular action of opening a dialog box and displaying message “Hello” happens.
Event Listener Interface vs Adapter Class
Many of the listener interfaces have more than one method. When
we implement a listener interface in any class then we must have to implement
all the methods declared in that interface because all the methods in an
interface are final and must be override in class which implement it.
Adapter class makes it easy to deal with
this situation. An adapter class provides empty implementations of all methods
defined by that interface. Adapter classes are very useful if we want to
override only some of the methods defined by that interface.
AI is thinking...
7. Discuss any three event classes in Java.
AI is thinking...
6. How can we use listener interface to handle events? Compare listener interface with adapter class. (3+2)
AI is thinking...
7. Why is it important to handle events? List any five event classes.
AI is thinking...
7. What is action event? Discuss (5)
The ActionEvent is generated when button is clicked or the item of a list is double-clicked. The listener related to this class is ActionListener. To have any component listen for an ActionEvent, we must register the component with an ActionListener as: component.addActionListener(new MyActionListener()); and then write the public void actionPerformed(ActionEvent e); method for the component to react to the event.
Example
import java.awt.event.*;
import javax.swing.*;
public class EventListener extends JFrame implements
ActionListener {
public
EventListener(){
JButton btn =
new JButton("Click Me");
add(btn);
btn.addActionListener(this);
//registering the event handler
setSize(100,
100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Hello");
}
public static void main(String []a) {
new
EventListener();
}
}
Here, whenever the “Click Me” button is clicked, an
event is generated and a particular action of opening a dialog box and
displaying message “Hello” happens.
AI is thinking...
5. Define event delegation model. Why do we need adapter class in event handling?
(2+3)
AI is thinking...
10. Discuss any five event classes in java.
AI is thinking...
11. Discuss the role of event listeners to handle events with suitable example.
AI is thinking...
11. How can you handle events using adapter classes? Discuss. (5)
AI is thinking...
3. Write a Java program using JDBC to extract name of those students who live in Kathmandu district, assuming that the student table has four attributes (ID, name, district, and age).
Before Writing the code please run the Xampp server and create a database name test and add a table called student with (id, name, district and age) column name.
Program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Studentjdbc{
public static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish a connection
String url = "jdbc:mysql//localhost/test";
String username = "root";
String password = "";
Connection conn = DriverManager.getConnection(url, username, password);
//Create a statement
Statement st = conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT name FROM student WHERE district = 'Katmandu' ");
while(rs.next()){
String name = rs.getString("name");
System.out.println("Name: "+ name);
}
st.close();
conn.close();
}catch (SQLException sqlExcep){
System.out.println("Error: " + sqlExcep.getMessage());
}
}
}
AI is thinking...
4. What is JDBC? How do you execute SQL queries in JDBC?
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
The following steps are involved in executing SQL statements in JDBC:
1. Load the JDBC driver.
2. Specify the name and location (given as a URL) of the database being used.
3. Connect to the database with a Connection object.
4. Execute a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Simplejdbc{
public static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish a connection
String url = "jdbc:mysql//localhost/test";
Connection conn = DriverManager.getConnection(url);
//Create a statement
Statement st = conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT * FROM Employee");
while(rs.next()){
int id = rs.getInt("E_ID");
String name = rs.getString("E_Name");
String address = rs.getString("E_Address");
Date d = rs.getDate("DOB");
System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);
}
st.close();
conn.close();
}catch (SQLException sqlExcep){
System.out.println("Error: " + sqlExcep.getMessage());
}
}
}
AI is thinking...
5. What is JDBC? Discuss different driver types of JDBC.
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
Type 1: JDBC-ODBC Bridge
- To use a Type 1 driver in a client machine, an ODBC driver should be installed and configured correctly.
- This type of driver does not directly interact with the database. To interact with database, it needs ODBC driver.
- The JDBC-ODBC bridge driver converts JDBC method class into ODBC method calls.
- It can be used to connect to any type of the databases.
Type 2: Native –API driver
- Type 2 drivers are written partially in Java and partially in native code.
- The Native-API of each database should be installed in the client system before accessing a particular database. So in this way, a Native-API driver is database specific driver.
- This driver converts JDBC method calls into native calls of the database API.
Type 3: Net Pure Java Driver
- In a Type 3 driver, the JDBC driver on the client machine uses the socket to communicate with the middleware at the server. The middleware or server acts as a gateway to access the database.
- The client database access requests are sent through the network to the middleware or server and then the middleware converts the request to the database specific API.
- Type-3 drivers are fully written in Java, hence they are portable drivers.
Type 4: Pure Java Driver
- This driver interact directly with database. It does not require any native database library and middleware server, that is why it is also known as Thin Driver.
- No client-side or server-side installation.
- It is fully written in Java language, hence they are portable drivers.
AI is thinking...
6. What is JDBC? How do you execute SQL statements in JDBC? (2+3)
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
The following steps are involved in executing SQL statements in JDBC:
1. Load
the JDBC driver.
2. Specify
the name and location (given as a URL) of the database being used.
3. Connect
to the database with a Connection object.
4. Execute
a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example:
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
public class
Simplejdbc{
public
static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//
Establish a connection
String url = "jdbc:mysql//localhost/test";
Connection conn = DriverManager.getConnection(url);
//Create a statement
Statement st =
conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT * FROM Employee");
while(rs.next()){
int id =
rs.getInt("E_ID");
String
name = rs.getString("E_Name");
String
address = rs.getString("E_Address");
Date
d = rs.getDate("DOB");
System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);
}
st.close();
conn.close();
}catch
(SQLException sqlExcep){
System.out.println("Error:
" + sqlExcep.getMessage());
}
}
}
AI is thinking...
8. Discuss different driver types on JDBC.
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
Type 1: JDBC-ODBC Bridge
- To use a Type 1 driver in a client machine, an ODBC driver should be installed and configured correctly.
- This type of driver does not directly interact with the database. To interact with database, it needs ODBC driver.
- The JDBC-ODBC bridge driver converts JDBC method class into ODBC method calls.
- It can be used to connect to any type of the databases.
Type 2: Native –API driver
- Type 2 drivers are written partially in Java and partially in native code.
- The Native-API of each database should be installed in the client system before accessing a particular database. So in this way, a Native-API driver is database specific driver.
- This driver converts JDBC method calls into native calls of the database API.
Type 3: Net Pure Java Driver
- In a Type 3 driver, the JDBC driver on the client machine uses the socket to communicate with the middleware at the server. The middleware or server acts as a gateway to access the database.
- The client database access requests are sent through the network to the middleware or server and then the middleware converts the request to the database specific API.
- Type-3 drivers are fully written in Java, hence they are portable drivers.
Type 4: Pure Java Driver
- This driver interact directly with database. It does not require any native database library and middleware server, that is why it is also known as Thin Driver.
- No client-side or server-side installation.
- It is fully written in Java language, hence they are portable drivers.
AI is thinking...
8. What is JDBC? How do you execute SQL statements in JDBC?
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
The following steps are involved in executing SQL statements in JDBC:
1. Load the JDBC driver.
2. Specify the name and location (given as a URL) of the database being used.
3. Connect to the database with a Connection object.
4. Execute a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Simplejdbc{
public static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish a connection
String url = "jdbc:mysql//localhost/test";
Connection conn = DriverManager.getConnection(url);
//Create a statement
Statement st = conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT * FROM Employee");
while(rs.next()){
int id = rs.getInt("E_ID");
String name = rs.getString("E_Name");
String address = rs.getString("E_Address");
Date d = rs.getDate("DOB");
System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);
}
st.close();
conn.close();
}catch (SQLException sqlExcep){
System.out.println("Error: " + sqlExcep.getMessage());
}
}
}
AI is thinking...
8. How do you execute SQL statement in JDBC? (5)
Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to connect Java application with Database. JDBC is used to interact with various type of Database such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL statement and retrieve result from database.
The following steps are involved in executing SQL statements in JDBC:
1. Load the JDBC driver.
2. Specify the name and location (given as a URL) of the database being used.
3. Connect to the database with a Connection object.
4. Execute a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Simplejdbc{
public static void main( String args[] ) {
try{
//Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish a connection
String url = "jdbc:mysql//localhost/test";
Connection conn = DriverManager.getConnection(url);
//Create a statement
Statement st = conn.createStatement();
//Execute a statement
ResultSet rs = st.executeQuery("SELECT * FROM Employee");
while(rs.next()){
int id = rs.getInt("E_ID");
String name = rs.getString("E_Name");
String address = rs.getString("E_Address");
Date d = rs.getDate("DOB");
System.out.println(id+"\\t"+name+"\\t"+address+"\\t"+d);
}
st.close();
conn.close();
}catch (SQLException sqlExcep){
System.out.println("Error: " + sqlExcep.getMessage());
}
}
}
AI is thinking...
7. What is row set? Explain cached row set in detail.(1+4)
AI is thinking...
8. What are the benefits of using JDBC? What is prepared statement?
Benefits of using JDBC:
- JDBC
enables enterprise applications to continue using existing data even if the
data is stored on different database management systems.
- The
combination of the java API and the JDBC API makes the databases transferable
from one vendor to another without modifications in the application code.
- JDBC is usually used to connect a user application to a ‘behind the scenes’ database, no matter of what database management software is used to control the database. In this function, JDBC is cross-platform or platform independent.
- With JDBC, the complexity of connecting a user program to a ‘behind the scenes’ database is hidden, and makes it easy to deploy and economical to maintain.
Prepared Statement
Prepared Statement is
used to execute parameterized or dynamic SQL queries.
E.g. of parameterized query:
String sql="insert into emp values(?,?,?)";
As we
can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
It is preferred when a particular query is to be executed multiple times. We can pass the parameters to SQL query at run time using this interface.
The
prepareStatement() method of Connection interface is used to return the
object of PreparedStatement.
PreparedStatement pstmt = conn.prepareStatement(queryString);
Example:
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101); //1 specifies the first parameter in the query
stmt.setString(2,"Ramesh");
int i=stmt.executeUpdate();
System.out.println("No. of rows updated="+i);
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}
AI is thinking...
8. How prepared statements are different with statement? List the types of JDBC driver.[2+3]
Difference between Statement and Prepared Statement
Statement |
PreparedStatement |
It
is used when SQL query is to be executed only once. |
It
is used when SQL query is to be executed multiple times. |
We cannot pass parameters
at runtime. |
We can pass parameters at
runtime. |
Used
for CREATE, ALTER, DROP statements. |
Used
for the queries which are to be executed multiple times. |
Performance is very low. |
Performance is better
than Statement. |
Used to execute normal
SQL queries. |
Used to execute dynamic
SQL queries. |
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
Type 1: JDBC-ODBC Bridge
- To use a Type 1 driver in a client machine, an ODBC driver should be installed and configured correctly.
- This type of driver does not directly interact with the database. To interact with database, it needs ODBC driver.
- The JDBC-ODBC bridge driver converts JDBC method class into ODBC method calls.
- It can be used to connect to any type of the databases.
Type 2: Native –API driver
- Type 2 drivers are written partially in Java and partially in native code.
- The Native-API of each database should be installed in the client system before accessing a particular database. So in this way, a Native-API driver is database specific driver.
- This driver converts JDBC method calls into native calls of the database API.
Type 3: Net Pure Java Driver
- In a Type 3 driver, the JDBC driver on the client machine uses the socket to communicate with the middleware at the server. The middleware or server acts as a gateway to access the database.
- The client database access requests are sent through the network to the middleware or server and then the middleware converts the request to the database specific API.
- Type-3 drivers are fully written in Java, hence they are portable drivers.
Type 4: Pure Java Driver
- This driver interact directly with database. It does not require any native database library and middleware server, that is why it is also known as Thin Driver.
- No client-side or server-side installation.
- It is fully written in Java language, hence they are portable drivers.
AI is thinking...
3. What is socket? How can you write java programs that communicate with each other using TCP sockets? Discuss with suitable example.
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Sockets provide the communication mechanism between two programs using TCP. We create client server programs using TCP as follows:
Creating a Socket Client:
The Socket class is used to implement a client program. We use this class to make connection to a server, send data to and read data from that server. The following steps are applied for a communication with the server:
1. The client initiates connection to a server specified by hostname/IP address and port number. (creation of socket object)
2. Send data to the server using an OutputStream.
3. Read data from the server using an InputStream.
4. Close the connection
Creating a Socket Server
The ServerSocket class is used to implement a server program. Here are the typical steps involve in developing a server program:
1. Create a server socket and bind it to a specific port number
2. Listen for a connection from the client and accept it. This results in a client socket is created for the connection.
3. Read data from the client via an InputStream obtained from the client socket.
4. Send data to the client via the client socket’s OutputStream.
5. Close the connection with the client.
Example:
Java program using TCP that enables chatting between client and server
//Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("SERVER:......\\n");
ServerSocket s = new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
System.out.println("Client connected”);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
while(true)
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}
in.close();
out.close();
cs.close();
}
catch(IOException e) { }
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("CLIENT:......\\n");
Socket con=new Socket("localhost", 95);
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e){ }
}
}
AI is thinking...
9. Discuss the process of sending email messages using Java.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "fromaddress@gmail.com";
// Sender's email ID needs to be mentioned
String from = "toaddress@gmail.com";
// Assuming you are sending email from through gmails smtp
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "465");
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.auth", "true");
// Get the Session object.// and pass username and password
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("fromaddress@gmail.com", "*******");
}
});
// Used to debug SMTP issues
session.setDebug(true);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
System.out.println("sending...");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
AI is thinking...
9. What is TCP socket? Differentiate it with UDP socket.
Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets. Stream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets.
Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP sockets. Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable.
TCP | UDP |
TCP is a connection oriented protocol. | UDP is a connectionless oriented protocol. |
TCP assure reliable delivery of data to the destination. | UDP does not assure reliable delivery of data to the destination. |
TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data. | UDP does not provides error checking mechanisms such as flow control and acknowledgement of data. |
Delivery of data is guaranteed if you are using TCP. | Delivery of data is not guaranteed if you are using UDP. |
TCP is comparatively slow because of these extensive error checking mechanism. | UDP makes fast and best effort service to transmit data. |
Retransmission of lost packets is possible. | There is no retransmission of lost packets in UDP. |
The Java code to perform client-server communication using UDP sockets is given below:
//UDPClient.java
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket ();
byte[] buf = new byte[256]; //Byte array to store information
String messg = "Hello UDP Server\\n";
buf = messg.getBytes (); //Getting the size of message
InetAddress address = InetAddress.getByName ("127.0.0.1");
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);
socket.send(packet); // Sends datagram packet, packet
}
catch (IOException e)
{
}
}
}
//UDPServer.java
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket (1234);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
String received = new String (packet.getData());
System.out.println ("Received packet: " + received);
}
catch (IOException e)
{
}
}
}
AI is thinking...
9. What is socket? Differentiate TCP socket from UDP socket.
Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets.
Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP sockets. Stream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets. Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable.
TCP | UDP |
TCP is a connection oriented protocol. | UDP is a connectionless oriented protocol. |
TCP assure reliable delivery of data to the destination. | UDP does not assure reliable delivery of data to the destination. |
TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data. | UDP does not provides error checking mechanisms such as flow control and acknowledgement of data. |
Delivery of data is guaranteed if you are using TCP. | Delivery of data is not guaranteed if you are using UDP. |
TCP is comparatively slow because of these extensive error checking mechanism. | UDP makes fast and best effort service to transmit data. |
Retransmission of lost packets is possible. | There is no retransmission of lost packets in UDP. |
The Java code to perform client-server communication using UDP sockets is given below:
//UDPClient.java
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket ();
byte[] buf = new byte[256]; //Byte array to store information
String messg = "Hello UDP Server\\n";
buf = messg.getBytes (); //Getting the size of message
InetAddress address = InetAddress.getByName ("127.0.0.1");
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);
socket.send(packet); // Sends datagram packet, packet
}
catch (IOException e)
{
}
}
}
//UDPServer.java
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket (1234);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
String received = new String (packet.getData());
System.out.println ("Received packet: " + received);
}
catch (IOException e)
{
}
}
}
AI is thinking...
9 What is socket? How can you write java programs that communicate with each other using TCP sockets? (1+4)
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Sockets provide the communication mechanism between two programs using TCP. We create client server programs using TCP as follows:
Creating a Socket Client:
The Socket class is used to implement a client program. We use this class to make connection to a server, send data to and read data from that server. The following steps are applied for a communication with the server:
1. The client initiates connection to a server specified by hostname/IP address and port number. (creation of socket object)
2. Send data to the server using an OutputStream.
3. Read data from the server using an InputStream.
4. Close the connection
Creating a Socket Server
The ServerSocket class is used to implement a server program. Here are the typical steps involve in developing a server program:
1. Create a server socket and bind it to a specific port number
2. Listen for a connection from the client and accept it. This results in a client socket is created for the connection.
3. Read data from the client via an InputStream obtained from the client socket.
4. Send data to the client via the client socket’s OutputStream.
5. Close the connection with the client.
Example:
Java program using TCP that enables chatting between client and server
//Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("SERVER:......\\n");
ServerSocket s = new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
System.out.println("Client connected”);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
while(true)
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}
in.close();
out.close();
cs.close();
}
catch(IOException e) { }
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("CLIENT:......\\n");
Socket con=new Socket("localhost", 95);
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e){ }
}
}
AI is thinking...
8. What is Java Mail API ? How can you use this API to send email messages? (1+4)
AI is thinking...
10. What is UDP socket? Differentiate it with TCP socket. (2+3)
Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets.
Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP sockets. Stream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets. Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable.
TCP | UDP |
TCP is a connection oriented protocol. | UDP is a connectionless oriented protocol. |
TCP assure reliable delivery of data to the destination. | UDP does not assure reliable delivery of data to the destination. |
TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data. | UDP does not provides error checking mechanisms such as flow control and acknowledgement of data. |
Delivery of data is guaranteed if you are using TCP. | Delivery of data is not guaranteed if you are using UDP. |
TCP is comparatively slow because of these extensive error checking mechanism. | UDP makes fast and best effort service to transmit data. |
Retransmission of lost packets is possible. | There is no retransmission of lost packets in UDP. |
The Java code to perform client-server communication using UDP sockets is given below:
//UDPClient.java
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket ();
byte[] buf = new byte[256]; //Byte array to store information
String messg = "Hello UDP Server\\n";
buf = messg.getBytes (); //Getting the size of message
InetAddress address = InetAddress.getByName ("127.0.0.1");
DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);
socket.send(packet); // Sends datagram packet, packet
}
catch (IOException e)
{
}
}
}
//UDPServer.java
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main (String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket (1234);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket (buf, buf.length);
socket.receive (packet);
String received = new String (packet.getData());
System.out.println ("Received packet: " + received);
}
catch (IOException e)
{
}
}
}
AI is thinking...
9. Write Java programs using TCP sockets that communicate with each other in a computer network.
//Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("SERVER:......\\n");
ServerSocket s = new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
System.out.println("Client connected”);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
while(true)
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}
in.close();
out.close();
cs.close();
}
catch(IOException e) { }
}
}
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("CLIENT:......\\n");
Socket con=new Socket("localhost", 95);
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e){ }
}
}
AI is thinking...
11. What is InetAddress class? Discuss.
The InetAddress class represents an IP address, both IPv4 and IPv6. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com, www.facebook.com, etc. We can use the InetAddress class if we need to convert between host names and Internet addresses.
Commonly used methods of InetAddress class:
- getByName(String host): creates an InetAddress object based on the provided hostname.
- getByAddress(byte[] addr): returns an InetAddress object from a byte array of the raw IP address.
- getAllByName(String host): returns an array of InetAddress objects from the specified hostname, as a hostname can be associated with several IP addresses.
- getLocalHost(): returns the address of the localhost.
To get the IP address/hostname you can use a couple of methods below:
- getHostAddress(): it returns the IP address in string format.
- getHostname(): it returns the host name of the IP address.
Example:
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.collegenote.net");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){
System.out.println(e);}
}
}
AI is thinking...
12. What is socket? How can you communicate two programs in a network using TCP Socket?
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Sockets provide the communication mechanism between two programs using TCP. We create client server programs using TCP as follows:
Creating a Socket Client:
The Socket class is used to implement a client program. We use this class to make connection to a server, send data to and read data from that server. The following steps are applied for a communication with the server:
1. The client initiates connection to a server specified by hostname/IP address and port number. (creation of socket object)
2. Send data to the server using an OutputStream.
3. Read data from the server using an InputStream.
4. Close the connection
Creating a Socket Server
The ServerSocket class is used to implement a server program. Here are the typical steps involve in developing a server program:
1. Create a server socket and bind it to a specific port number
2. Listen for a connection from the client and accept it. This results in a client socket is created for the connection.
3. Read data from the client via an InputStream obtained from the client socket.
4. Send data to the client via the client socket’s OutputStream.
5. Close the connection with the client.
Example:
Java program using TCP that enables chatting between client and server
//Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("SERVER:......\\n");
ServerSocket s = new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
System.out.println("Client connected”);
BufferedReader in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter(cs.getOutputStream(),true);
while(true)
{
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}
in.close();
out.close();
cs.close();
}
catch(IOException e) { }
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[]) throws IOException
{
try
{
System.out.println("CLIENT:......\\n");
Socket con=new Socket("localhost", 95);
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out=new PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the server:");
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
String st=din.readLine();
out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e){ }
}
}
AI is thinking...
12. What is a socket? Write client and server programs in which a server program accepts a radius of a circle from the client program. Computes area, sends the computed area to the client program, and displays it by client program.[1+4]
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.
Program
// Server Program
import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(1064);
System.out.println("Waiting for Client Request");
Socket s=ss.accept();
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Received radius");
double r=Double.valueOf(str);
double area=3.14*r*r;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
br.close();
ps.close();
s.close();
ss.close();
}
}
AI is thinking...
2. What is Java Beans? How is it different from other Java classes? Discuss property design patterns with suitable example of each.
AI is thinking...
3. What is java beans? Differentiate it with java class. Discuss bean writing process with suitable examples. (2+2+6)
AI is thinking...
5. What is java beans? How is it different from java class?
AI is thinking...
9. Compare JavaFX with swing. Explain HBox and BBox layouts of JavaFX.(2+3)
AI is thinking...
11. What is java beans? Differentiate it with java classes.
AI is thinking...
11. Discuss property design patterns for Java Beans. (5)
AI is thinking...
10. Define Java Bean. How is it different from other Java programs? What is design pattern?
AI is thinking...
9. What is the task of manifest file? Write the procedure to create it.
[2 + 3]
AI is thinking...
11. What is Java Bean? How is it different from other Java classes?
AI is thinking...
11. Give any two differences between class and bean. Write the steps to create JAR files. [2+3]
AI is thinking...
2. Explain life-cycle of servlet in detail.Create a simple servlet that reads and displaysdata from HTML form. Assume form with two fields username and password.(5+5)
AI is thinking...
3. Define servlet. Discuss life cycle of servlet. Differentiate servlet with JSP. Write a simple JSP file to display 'IOST' 20 times.
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().
init():
- The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.
service():
- The service() method is the main method to perform the actual task.
- The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.
destroy():
- Finally server unloads the servlet from the memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
Servlets | JSP |
Servlet is a pure java code. | JSP is a tag based approach. |
We write HTML in servlet code. | We write JSP code in HTML. |
Servlet is faster than JSP. | JSP is slower than servlet because it first translate into java code then compile. |
Writing code for servlet is harder than JSP as it is html in java. | JSP is easy to code as it is java in html. |
Servlet can accept all protocol requests. | JSP only accept http requests. |
Modification in Servlet is a time consuming task because it includes reloading, recompiling and restarting the server. | JSP modification is fast, just need to click the refresh button. (reloading, recompilation and restart the server is not required) |
Servlets do not have implicit objects. | JSP does have implicit objects. |
In Servlet, we can override the service() method. | In JSP, we cannot override its service() method. |
In MVC pattern, servlet act as a controller. | In MVC, JSP act as a view. |
In Servlet, by default session management is not enabled we need to enable explicitly. | In JSP, session management is automatically enabled. |
Packages are to be imported at the top of the servlet. | Packages can be imported anywhere in the JSP code. |
Program
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF-8”>
<title> JSP program to display “IOST” 20 times</title>
</head>
<body>
<h1> Displaying “IOST” 20 times!!</h1>
<table>
<%
for(int i=1; i<=20; i++){
%>
<tr><td> IOST </td></tr>
<% } %>
</table>
</body>
</html>
AI is thinking...
3. What is servlet? Differentiate it with JSP. Discuss life cycle of servlet in detail.
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
Servlets |
JSP |
Servlet is a pure java code. |
JSP is a tag based approach. |
We write HTML in servlet code. |
We write JSP code in HTML. |
Servlet is faster than JSP. |
JSP is slower than servlet
because it first translate into java code then compile. |
Writing
code for servlet is harder than JSP as it is html in java. |
JSP
is easy to code as it is java in html. |
Servlet
can accept all protocol requests. |
JSP
only accept http requests. |
Modification
in Servlet is a time consuming task because it includes reloading,
recompiling and restarting the server. |
JSP
modification is fast, just need to click the refresh button. (reloading,
recompilation and restart the server is not required) |
Servlets do not have implicit
objects. |
JSP does have implicit objects. |
In
Servlet, we can override the service() method. |
In
JSP, we cannot override its service() method. |
In MVC pattern, servlet act as a
controller. |
In MVC, JSP act as a view. |
In Servlet, by default session
management is not enabled we need to enable explicitly. |
In JSP, session management is
automatically enabled. |
Packages are to be imported at
the top of the servlet. |
Packages can be imported anywhere
in the JSP code. |
Life Cycle of Servlets
In the life cycle of servlet there are three important
methods. These methods are: init(), service() and destroy().
init():
-
The server invokes
the init( ) method of the servlet. This method is invoked only
when the servlet is loaded in the memory for the first time. It is possible
to pass initialization parameters to the servlet so it may configure itself.
service():
-
The service() method is the main method
to perform the actual task.
-
The web server calls the service() method
to handle requests coming from the client/browsers and to write the response
back to the client (to process the HTTP rerquest). The service() method is
called for each HTTP request.
destroy():
-
Finally server unloads the servlet from the
memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
AI is thinking...
3. Describe the process to deploy the servlet. Write a program to a JSP web form to take input of a student and submit it to second JSP file which may simply print the values of form submission. [4+6]
Second Part:
//StudentForm.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Form.</title>
</head>
<body>
<h1>Fill up the form!</h1>
<form action="PrintDetail.jsp" method="POST">
Name: <input type="text" name="name"><br><br>
Roll No.: <input type="text" name="roll"><br><br>
Address: <input type="text" name="address"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
// PrintDetail.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Print Student Details.</title>
</head>
<body>
<h1>Student Details!</h1>
Name: <%= request.getParameter("name") %><br>
Roll No.: <%= request.getParameter("roll") %><br>
Address: <%= request.getParameter("address") %><br>
</body>
</html>
AI is thinking...
5. Explain the significance of cookies and sessions with suitable example? [5]
AI is thinking...
7. Discuss different methods used in life cycle of servlet.
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().
init():
- The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.
service():
- The service() method is the main method to perform the actual task.
- The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.
destroy():
- Finally server unloads the servlet from the memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
AI is thinking...
9. What is JSP? Differentiate it with servlet. (2+3)
Java Server Pages (JSP) is server side technology to create dynamic java web application. It allows
java programming code to be embedded in the HTML pages.
-
Scripting elements are used to provide
dynamic pages.
- JSP simply puts Java inside HTML pages.
Servlets |
JSP |
Servlet is a pure java code. |
JSP is a tag based approach. |
We write HTML in servlet code. |
We write JSP code in HTML. |
Servlet is faster than JSP. |
JSP is slower than servlet
because it first translate into java code then compile. |
Writing
code for servlet is harder than JSP as it is html in java. |
JSP
is easy to code as it is java in html. |
Servlet
can accept all protocol requests. |
JSP
only accept http requests. |
Modification
in Servlet is a time consuming task because it includes reloading,
recompiling and restarting the server. |
JSP
modification is fast, just need to click the refresh button. (reloading,
recompilation and restart the server is not required) |
Servlets do not have implicit
objects. |
JSP does have implicit objects. |
In
Servlet, we can override the service() method. |
In
JSP, we cannot override its service() method. |
In MVC pattern, servlet act as a
controller. |
In MVC, JSP act as a view. |
In Servlet, by default session
management is not enabled we need to enable explicitly. |
In JSP, session management is
automatically enabled. |
Packages are to be imported at
the top of the servlet. |
Packages can be imported anywhere
in the JSP code. |
AI is thinking...
10. Write a Java program using servlet to display "Tribhuvan University". (5)
AI is thinking...
10. What is JSP? Discuss with suitable example.
Java Server Pages (JSP) is server side technology to create dynamic java web application. It allows java programming code to be embedded in the HTML pages.
- Scripting elements are used to provide dynamic pages.
- JSP simply puts Java inside HTML pages.
JSP provides the following scripting elements:
1. JSP Comments:
Syntax:
<%-- comments --%>
2. JSP Scriplet: A scriptlet tag is used to execute java source code in JSP.
Syntax:
<% java source code; %>
3. JSP Expression:
JSP expression can be used to insert a single java expression directly into the response message. This expression will be place inside a out.print() method.
Syntax:
<%= Java Expression %>
4. JSP Declaration: JSP declaration tag is used to declare variables and methods.
Syntax:
<%! Variable or method declaration %>
Example
AI is thinking...
10. What is servlet? Discuss its life cycle.
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
Life Cycle of Servlets
In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().
init():
- The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.
service():
- The service() method is the main method to perform the actual task.
- The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.
destroy():
- Finally server unloads the servlet from the memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
AI is thinking...
8. Explain the life cycle of a servlet.
(5)
A servlet is a small java program that executes on the server-side of web connection and dynamically extends the functionality of a web server. Servlet technology is used to create Dynamic web application.
In the life cycle of servlet there are three important methods. These methods are: init(), service() and destroy().
init():
- The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is loaded in the memory for the first time. It is possible to pass initialization parameters to the servlet so it may configure itself.
service():
- The service() method is the main method to perform the actual task.
- The web server calls the service() method to handle requests coming from the client/browsers and to write the response back to the client (to process the HTTP rerquest). The service() method is called for each HTTP request.
destroy():
- Finally server unloads the servlet from the memory using the destroy() method to clean any resources.
- The destroy() method is called only once at the end of the life cycle of a servlet.
AI is thinking...
10. What is servlet? Write a simple JSP file to display "Tribhuwan University" five times. (2+3)
AI is thinking...
11. How do you handle HTTP request (GET) using servlet?
Handling HTTP GET
requests involves overriding the doGet
method.
The following example shows the use of HTTP GET method.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType(“text/html”);
PrintWriter pw = res.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println(“<title>HW</title>”);
pw.println("</head>");
pw.println("<body>");
pw.println("<h2>Hello World!</h2>");
pw.println("</body>");
pw.println("</html>");
pw.close();
}
}
AI is thinking...
13. Write a simple JSP program to display “Kathmandu, Nepal” 10 times. (5)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type”
content=“text/htm; charset=UTF-8”>
<title> JSP program to display “Kathmandu,
Nepal” 10 times</title>
</head>
<body>
<h1> Displaying “Kathmandu,
Nepal” 10 times!!</h1>
<table>
<%
for(int i=1; i<=10; i++){
%>
<tr><td> Kathmandu, Nepal</td></tr>
<% } %>
</table>
</body>
</html>
AI is thinking...
13. Write a simple JSP program to display “Tribhuvan University” 10 times.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF-8”>
<title> JSP program to display “Tribhuvan University” 10 times</title>
</head>
<body>
<h1> Displaying “Tribhuvan University” 10 times!!</h1>
<table>
<%
for(int i=1; i<=10; i++){
%>
<tr><td> Tribhuvan University</td></tr>
<% } %>
</table>
</body>
</html>
AI is thinking...
11. How forms can be created and processed using JSP? Make it clear with your own assumptions. [5]
AI is thinking...
13. Write a simple JSP program to display “Lalitpur, Nepal” 10 times.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/htm; charset=UTF-8”>
<title> JSP program to display “Lalitpur, Nepal” 10 times</title>
</head>
<body>
<h1> Displaying “Lalitpur, Nepal” 10 times!!</h1>
<table>
<%
for(int i=1; i<=10; i++){
%>
<tr><td> Lalitpur, Nepal</td></tr>
<% } %>
</table>
</body>
</html>
AI is thinking...
12. Write short notes on: (2*2.5 = 5)
a. JDBC drivers
b. Java server pages
AI is thinking...
13. Write short notes on:
- Servlet API
- RMI vs CORBA
Servlet API
Two packages javax.servlet and javax.servlet.http contains the classes and interfaces that are required to build servlet. These two packages constitute the servlet API and these are not part of the core packages. Therefore they are not included in Java Software Development Kit (JSDK).
- The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
Interfaces defined in javax.servlet package: Servlet, ServletConfig, ServletContext, ServletRequest, ServletResponse
Classes in javax.servlet packages: GenericServlet, ServletInputStream, ServletOutputStream, ServletException
- The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. Its functionality is to make easy to build servlets that work with HTTP requests and responses.
Interfaces used in javax.servlet.http package: HttpServletRequest, HttpServletResponse, HttpSession
Classes used in javax.servlet.http package: Cookie, HttpServlet
RMI vs CORBA
RMI | CORBA |
RMI is a Java-specific technology. | CORBA is independent of programming languages. It Can access foreign language objects. |
It uses Java interface for implementation. | It uses Interface Definition Language (IDL) to separate interface from implementation. |
RMI programs can download new classes from remote JVMs. | CORBA doesn't have this code sharing mechanism. |
RMI passes objects by remote reference or by value. | CORBA passes objects by reference. |
RMI uses the Java Remote Method Protocol as its underlying remoting protocol. | CORBA use Internet Inter- ORB Protocol (IIOP) as its underlying remoting protocol. |
The responsibility of locating an object implementation falls on JVM. | The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter. |
Distributed garbage collection is available integrated with local collectors. | No distributed garbage collection is available |
Generally simpler to use. | More complicated. |
It is free of cost. | Cost money according to the vendor. |
| CORBA has better scalability. |
AI is thinking...
1, What is the significance of stub and skeleton In RMI? Create a RMI application such that a
client sends an Integer number to the server and the server return the factorial value of that integer.
Give a clear specification for every step.
(10)
AI is thinking...
3. Explain RMI architecture layers in detail. Write a Java programs using RMI to find product of two numbers.(4+6)
AI is thinking...
3. What is RMI? How can you use RMI to develop a program that runs in different machine? Discuss with suitable example.
RMI is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.
To create an application that uses RMI, one needs to use the
classes and interfaces defined by the java.rmi package.
To create an RMI application, the following steps need to be followed:
1. Define a remote interface
2. Implement the remote interface
3. Develop the server application program
4. Develop a client application program
5. Generate Stubs and Skeletons
6. Start the RMI registry on server machine
7. Start the server
8. Start the client
Example:
Define a remote interface
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int a,int b)throws RemoteException;
}
Implementation of remote interface
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements
Adder
{
AdderRemote()throws RemoteException{
super();
}
public int add(int a,int b)
{
return a+b;
}
}
Writing the Server Program
import java.rmi.*;
import java.rmi.registry.*;
public class AddServer {
public static void main(String args[]) {
try {
AdderRemote s1=new AdderRemote();
LocateRegistry.createRegistry(1099);
Naming.rebind("AddService",s1);
}
catch(Exception e) {
System.out.println(e);
}
}
}
Writing the Client Program
import java.rmi.*;
public class Client {
public static void main(String args[]) {
try{
String ip="rmi://127.0.0.1/Addservice";
Adder st = (Adder)Naming.lookup(ip);
System.out.println(st.sum(25,8));
}
catch(Exception e) {
System.out.println(e);
}
}
}
AI is thinking...
7. Describe the process to run the RMI application. [5]
RMI is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.
To create an application that uses RMI, one needs to use the classes and interfaces defined by the java.rmi package.
To create an RMI application, the following steps need to be followed:
1. Define a remote interface
2. Implement the remote interface
3. Develop the server application program
4. Develop a client application program
5. Generate Stubs and Skeletons
6. Start the RMI registry on server machine
7. Start the server
8. Start the client
Example:
Define a remote interface
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int a,int b)throws RemoteException;
}
Implementation of remote interface
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder
{
AdderRemote()throws RemoteException{
super();
}
public int add(int a,int b)
{
return a+b;
}
}
Writing the Server Program
import java.rmi.*;
import java.rmi.registry.*;
public class AddServer {
public static void main(String args[]) {
try {
AdderRemote s1=new AdderRemote();
LocateRegistry.createRegistry(1099);
Naming.rebind("AddService",s1);
}
catch(Exception e) {
System.out.println(e);
}
}
}
Writing the Client Program
import java.rmi.*;
public class Client {
public static void main(String args[]) {
try{
String ip="rmi://127.0.0.1/Addservice";
Adder st = (Adder)Naming.lookup(ip);
System.out.println(st.sum(25,8));
}
catch(Exception e) {
System.out.println(e);
}
}
}
AI is thinking...
12. What is RMI? Discuss architecture of RMI in detail. (1+4)
Remote Method Invocation (RMI) is a mechanism that allows an object running in
one java virtual machine (JVM) to invoke methods on an object running in
another java virtual machine (JVM). It
Architecture of RMI
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
- Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
- The client program requests the remote objects on the server and tries to invoke its methods.
The RMI architecture consists of four layers:
1. Application Layer:
This layer is the actual systems i.e. client and
server which are involved in communication. The java program on the client side
communicates with the java program on the server-side.
2. Proxy Layer: This layer contains the client stub and server skeleton objects.
- Stub is an object that resides on the client machine and it acts as a proxy for the remote object. It is like a gateway for the client program. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure which is then executed on the server.
- The server object which resides in a server machine is known as Skeleton. Stub communicates with server application with the help of an intermediate Skeleton object. The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.
3. Remote Reference Layer: This layer is responsible to maintain the session during the method call. i.e. It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects. The invocation semantics of the RMI connection is defined and supported by this layer.
4. Transport Layer: The
transport layer is responsible for setting up communication between the two
machines. This layer uses standard TCP/IP protocol for
connection. The actual transportation of data is performed through this layer.
AI is thinking...
12. What is CORBA? How is it different from RMI? (2+3)
The Common Object Request Broker Architecture (CORBA) is a
standard developed by the Object Management Group (OMG) to provide
interoperability among distributed objects.
Difference between RMI and CORBA
RMI | CORBA |
RMI is a Java-specific technology. | CORBA is independent of programming languages. It Can access foreign language objects. |
It uses Java interface for implementation. | It uses Interface Definition Language (IDL) to separate interface from implementation. |
RMI programs can download new classes from remote JVMs. | CORBA doesn't have this code sharing mechanism. |
RMI passes objects by remote reference or by value. | CORBA passes objects by reference. |
RMI uses the Java Remote Method Protocol as its underlying remoting protocol. | CORBA use Internet Inter- ORB Protocol (IIOP) as its underlying remoting protocol. |
The responsibility of locating an object implementation falls on JVM. | The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter. |
Distributed garbage collection is available integrated with local collectors. | No distributed garbage collection is available |
Generally simpler to use. | More complicated. |
It is free of cost. | Cost money according to the vendor. |
| CORBA has better scalability. |
AI is thinking...
11. Why CORBA is important? Compare CORBA with RMI. (3+2)
AI is thinking...
12. What is RMI? Discuss architecture of RMI.
Remote Method Invocation (RMI) is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). It
Architecture of RMI
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
- Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
- The client program requests the remote objects on the server and tries to invoke its methods.
The RMI architecture consists of four layers:
1. Application Layer: This layer is the actual systems i.e. client and server which are involved in communication. The java program on the client side communicates with the java program on the server-side.
2. Proxy Layer: This layer contains the client stub and server skeleton objects.
- Stub is an object that resides on the client machine and it acts as a proxy for the remote object. It is like a gateway for the client program. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure which is then executed on the server.
- The server object which resides in a server machine is known as Skeleton. Stub communicates with server application with the help of an intermediate Skeleton object. The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.
3. Remote Reference Layer: This layer is responsible to maintain the session during the method call. i.e. It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects. The invocation semantics of the RMI connection is defined and supported by this layer.
4. Transport Layer: The transport layer is responsible for setting up communication between the two machines. This layer uses standard TCP/IP protocol for connection. The actual transportation of data is performed through this layer.
AI is thinking...
12. What is RMI? How is it different from CORBA?
Remote Method Invocation (RMI) is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.
Difference between RMI and CORBA
RMI | CORBA |
RMI is a Java-specific technology. | CORBA is independent of programming languages. It Can access foreign language objects. |
It uses Java interface for implementation. | It uses Interface Definition Language (IDL) to separate interface from implementation. |
RMI programs can download new classes from remote JVMs. | CORBA doesn't have this code sharing mechanism. |
RMI passes objects by remote reference or by value. | CORBA passes objects by reference. |
RMI uses the Java Remote Method Protocol as its underlying remoting protocol. | CORBA use Internet Inter- ORB Protocol (IIOP) as its underlying remoting protocol. |
The responsibility of locating an object implementation falls on JVM. | The responsibility of locating an object implementation falls on Object Adapter either Basic Object Adapter or Portable Object Adapter. |
Distributed garbage collection is available integrated with local collectors. | No distributed garbage collection is available |
Generally simpler to use. | More complicated. |
It is free of cost. | Cost money according to the vendor. |
| CORBA has better scalability. |
AI is thinking...
12. What is RMI? Differentiate it with CORBA?
Remote Method Invocation (RMI) is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). RMI provides remote communication between java programs. Objects with methods that can be invoked across JVMs are called remote objects. The remote object is called the server object.
Difference between RMI and CORBA
RMI |
CORBA |
RMI is a Java-specific technology. |
CORBA
is independent of programming languages. It
Can access foreign language objects. |
It uses Java interface for implementation. |
It uses Interface Definition Language (IDL) to separate
interface from implementation. |
RMI programs can download new classes from remote JVMs. |
CORBA doesn't have this code sharing mechanism. |
RMI passes objects by remote reference or by value. |
CORBA passes objects by reference. |
RMI uses the Java Remote Method Protocol as its underlying
remoting protocol. |
CORBA use Internet Inter- ORB Protocol (IIOP) as its
underlying remoting protocol. |
The responsibility of locating an object implementation
falls on JVM. |
The responsibility of locating an object implementation
falls on Object Adapter either Basic Object Adapter or Portable Object
Adapter. |
Distributed garbage collection is available integrated with
local collectors. |
No distributed garbage collection is available |
Generally
simpler to use. |
More
complicated. |
It
is free of cost. |
Cost
money according to the vendor. |
|
CORBA
has better scalability. |
AI is thinking...
12. What are different layers of RMI architecture? Explain.
Remote Method Invocation (RMI) is a mechanism that allows an object running in one java virtual machine (JVM) to invoke methods on an object running in another java virtual machine (JVM). It
Architecture of RMI
In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).
- Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).
- The client program requests the remote objects on the server and tries to invoke its methods.
The RMI architecture consists of four layers:
1. Application Layer: This layer is the actual systems i.e. client and server which are involved in communication. The java program on the client side communicates with the java program on the server-side.
2. Proxy Layer: This layer contains the client stub and server skeleton objects.
- Stub is an object that resides on the client machine and it acts as a proxy for the remote object. It is like a gateway for the client program. When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton) via RMI infrastructure which is then executed on the server.
- The server object which resides in a server machine is known as Skeleton. Stub communicates with server application with the help of an intermediate Skeleton object. The responsibility of the skeleton object is to send parameters to method implementation and send the return values back to the client.
3. Remote Reference Layer: This layer is responsible to maintain the session during the method call. i.e. It manages the references made by the client to the remote server object. This layer is also responsible for handling duplicated objects. The invocation semantics of the RMI connection is defined and supported by this layer.
4. Transport Layer: The transport layer is responsible for setting up communication between the two machines. This layer uses standard TCP/IP protocol for connection. The actual transportation of data is performed through this layer.
AI is thinking...