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

Q1 a) The stub and skeleton are integral components of the Remote Method Invocation (RMI) architecture in Java,

working together to facilitate communication between distributed objects.

Stub: The stub serves as the client-side representative of a remote object, implementing the remote interface. Acting as
a placeholder for the remote object, the stub is responsible for marshalling parameters, handling communication
details, and initiating method calls on the server-side. It abstracts the complexities of network communication and
provides a local interface for the client to interact with the remote object.

Skeleton: On the server-side, the skeleton is the counterpart to the stub. It receives requests from the stub, performs
unmarshalling of parameters, and directs the method calls to the actual implementation of the remote object. The
skeleton handles the intricacies of communication on the server side, ensuring that the method invocations are properly
routed to the appropriate methods in the remote object's implementation.

In summary, the stub and skeleton work hand-in-hand to enable transparent communication between distributed
objects, allowing developers to invoke remote methods as if they were local, while abstracting away the underlying
complexities of network communication.

Q1 b)

import java.util.ArrayList;

import java.util.List;

public class DisplayIntegers {

public static void main(String[] args) {

// Create a collection of integers (in this case, a List)

List<Integer> integerList = new ArrayList<>();

integerList.add(1);

integerList.add(3);

integerList.add(5);

integerList.add(7);

integerList.add(9);

// Display the collection using the enhanced for-each loop

System.out.println("Collection of Integers:");

for (int num : integerList) {

System.out.println(num);
}

Q1 c)

ArrayList<String> al = new ArrayList<String>();

In this, both the reference variable and the object instance is of type ArrayList wheras in

List<String> all = new ArrayList<String>();

The reference variable is of the more general, list interface. The second approach is generally considered a good practice
because it allows for easier switching of implementations if needed.

Q1 d) Threads in Java go through different states during their life cycle. Here are the different states and corresponding
code snippets:

1. New:

 The thread is in a new state before the start() method is invoked.

Thread newThread = new Thread(() -> {


// Thread's task
});

2. Runnable:

 The thread is in a runnable state after the start() method is called.

Thread runnableThread = new Thread(() -> {


// Thread's task });
runnableThread.start();

3. Blocked:

 A thread transitions to the blocked state when it wants to access an object that another thread has
locked.

synchronized (someObject) {
// Critical section
// Other thread trying to access someObject will be blocked
}

4. Waiting:

 A thread transitions to the waiting state when it waits indefinitely for another thread to perform a
particular action.
synchronized (someObject) {
someObject.wait(); // Thread waits
}

5. Terminated:

 A thread is in the terminated state when its run() method completes execution or when the stop()
method is called.

Thread terminatedThread = new Thread(() -> {


// Thread's task });
terminatedThread.start();
// Some time later
terminatedThread.join(); // Wait for the thread to complete

These states represent the life cycle of a thread in Java, and threads can transition between these states based on their
execution and synchronization with other threads.

Q1 e)

The code class Test ( int a; char b; b = a+32;} will not compile properly as the expression is placed directly in the class
body, outside any constructor or method. Secondly, here, the types int and char are incompatible with each other,
which is not allowed here. Also, the value of variable ‘a’ has not been initialized.

Q1 f)

In Java, the this keyword is a reference variable that is used to refer to the current object. It is commonly used in
instance methods and constructors to distinguish instance variables from local variables when they have the same
name. Additionally, it can be used to invoke the current object's methods.

public class MyClass {

// Instance variable

private int number;

// Constructor with a parameter

public MyClass(int number) {

// Use of this to differentiate between instance variable and parameter

this.number = number;

}
// Method to display the current object's number

public void displayNumber() {

// Use of this to access the instance variable

System.out.println("Number: " + this.number);

public static void main(String[] args) {

// Creating an object of MyClass

MyClass myObject = new MyClass(42);

// Display the number using the displayNumber method

myObject.displayNumber();

Q1 g)

The static keyword in Java is used to create class-level variables and methods. When a member (variable or method) is
declared as static, it belongs to the class rather than an instance of the class. A static variable is shared among all class
objects and a static method can only be used without the instance of the class, just by using the class name.

public class Test {


public static int var = 10;

static void printVar() {


System.out.println(var);
}

public static void main(String[] args) {


Test.printVar(); // the method is being called using the classname

Test t1 = new Test();


Test t2 = new Test();

System.out.println(++t1.var);
System.out.println(t2.var);
// since both t1 and t2 share the same var variable, they both show that the value was incremented
}
}

Q1 h)

JDBC (Java Database Connectivity) is a Java API that provides a standard interface for connecting Java applications with
relational databases. There are four types of JDBC drivers, each with its own characteristics:

1. Type 1: JDBC-ODBC Bridge Driver (Bridge Driver):

 Description: This driver uses ODBC (Open Database Connectivity) to connect to databases. It translates
JDBC calls into ODBC calls. It requires the ODBC driver to be installed on the client machine.

 Advantages:

 Platform-independent for Java applications but ODBC driver must be installed.

 Easy to use for small applications or prototyping.

 Disadvantages:

 Requires native ODBC driver on each client machine.

 Slower performance compared to other driver types.

2. Type 2: Native-API Driver (Partly Java Driver):

 Description: This driver uses a database-specific native API to connect to the database. The native API is
typically written in C or C++. The driver is partially written in Java and includes native methods.

 Advantages:

 Better performance than the Type 1 driver.

 Doesn't require an ODBC driver.

 Disadvantages:

 Not completely Java-based.

 Still needs native code, which may limit portability.

3. Type 3: Network Protocol Driver (Middleware Driver):

 Description: This driver uses a middleware component to convert JDBC calls into a database-
independent protocol. The middleware, often referred to as a "bridge server," acts as a mediator
between the Java application and the database.

 Advantages:

 Database independence for Java applications.


 Better performance than Type 1 and Type 2 drivers.

 Disadvantages:

 Requires additional software (the middleware) to be installed.

 Performance depends on the efficiency of the middleware.

4. Type 4: Thin Driver (Pure Java Driver):

 Description: This is a fully Java-based driver that communicates directly with the database using a
database-specific protocol. It doesn't require any native code or middleware. It is also known as the
"Thin Driver."

 Advantages:

 Completely written in Java, making it platform-independent.

 No need for additional software installation.

 Typically provides better performance than other driver types.

 Disadvantages:

 Requires a separate driver for each database.

Q1 i)

Set and Map are both interfaces in Java's collections framework, but they serve different purposes and have distinct
characteristics. Here's a contrast between Set and Map:

Set:

1. Purpose:

 A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction
and is used when you want to store a group of unique elements.

2. Implementation Classes:

 Common implementations of the Set interface are HashSet, LinkedHashSet, and TreeSet.

3. Key Characteristics:

 No duplicate elements are allowed.

 Elements are not stored in any specific order (the order may vary depending on the implementation).

 It provides methods for adding, removing, and checking the existence of elements.

4. Example Usage:

Set<String> uniqueWords = new HashSet<>();

uniqueWords.add("apple")
; uniqueWords.add("banana");

uniqueWords.add("orange");

Map:

1. Purpose:

 A Map is a collection of key-value pairs, where each key is associated with exactly one value. It is used to
represent relationships between pairs of objects.

2. Implementation Classes:

 Common implementations of the Map interface are HashMap, LinkedHashMap, TreeMap, and
HashTable.

3. Key Characteristics:

 Each key must be unique within the Map.

 Values can be duplicated.

 It provides methods to put a key-value pair, get a value by key, remove entries, and check for the
existence of a key.

4. Example Usage:

Map<String, Integer> wordCount = new HashMap<>();

wordCount.put("apple", 5);

wordCount.put("banana", 3);

wordCount.put("orange", 8);

Q1 j)

In Java, the volatile keyword is a modifier that can be applied to instance variables of a class. It is used to indicate that a
variable's value may be changed by multiple threads simultaneously. Essentially, it ensures visibility and atomicity for
certain operations involving the variable

The volatile modifier guarantees atomic reads and writes for the variable. However, it does not provide atomicity for
compound actions like incrementing a variable.

class SharedResource {

// Declaring a volatile variable

private volatile boolean flag = false;

// Method to set the flag

public void setFlag() {


flag = true;

// Method to check the flag

public boolean checkFlag() {

return flag;

Q2 a)

class Ellipse {
private double radius;
private String color;
Ellipse(){
this.radius = 1.0;
this.color = "red";
}

Ellipse(double radius){
this.radius = radius;
}

double getRadius(){
return this.radius;
}

double getArea(){
return 3.14 * this.radius * this.radius;
}
}

public class TestEllipse{


public static void main(String[] args) {
Ellipse e1 = new Ellipse(1.2);

System.out.println("The radius is: " + e1.getRadius());


System.out.println("The area is: " + e1.getArea());
}
}

Q2 b)

The final keyword in Java is used to indicate that a variable, method, or class cannot be further modified once it has
been declared or defined. Here are examples demonstrating different uses of the final keyword:

1. Final Variable:

class Example {
final int finalVariable = 42;
void modifyVariable() {
// Error: Cannot assign a value to final variable
// finalVariable = 50;
}
}

In this example, finalVariable is a final instance variable. Once assigned a value, it cannot be modified. Attempting to
modify it will result in a compilation error.

2. Final Method:

class Example {
final void finalMethod() {
// Method implementation
}
}

class Subclass extends Example {


// Error: Cannot override the final method from Example
// void finalMethod() { }
}

In this example, finalMethod is a final method in the Example class. Subclasses cannot override or modify this method.

3. Final Class:

class Example {
final void finalMethod() {
// Method implementation
}
}

class Subclass extends Example {


// Error: Cannot override the final method from Example
// void finalMethod() { }
}

Here, FinalClass is a final class. It cannot be extended. Attempting to create a subclass of FinalClass will result in a
compilation error.

Q4 a) Synchronization in Java is a technique used to control access to shared resources in a multithreaded environment,
ensuring that only one thread can access a critical section of code or a shared resource at a time. The primary goal of
synchronization is to prevent data inconsistency or corruption that may arise when multiple threads attempt to modify
shared data concurrently.

In Java, synchronization is typically achieved using the synchronized keyword. This keyword can be applied to methods
or blocks of code to ensure that only one thread can execute the synchronized portion at any given time. This helps in
maintaining the integrity of shared data and preventing race conditions, where the outcome of an operation depends on
the timing or interleaving of multiple threads.
class SharedResource {
private int counter = 0;
private final Object lock = new Object(); // A lock object for synchronization

// Synchronized method
public synchronized void synchronizedMethod() {
counter++;
System.out.println("Sync Method - Thread " + Thread.currentThread().getId() + "
incremented counter to: " + counter);
}

// Method using a synchronized block


public void synchronizedBlockMethod() {
synchronized (lock) {
counter++;
System.out.println("Sync Block - Thread " + Thread.currentThread().getId() +
" incremented counter to: " + counter);
}
}
}

class MyThread extends Thread {


private SharedResource sharedResource;

public MyThread(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}

@Override
public void run() {
sharedResource.synchronizedMethod();
sharedResource.synchronizedBlockMethod();
}
}

public class SynchronizationExample {


public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();

// Creating multiple threads


Thread thread1 = new MyThread(sharedResource);
Thread thread2 = new MyThread(sharedResource);
Thread thread3 = new MyThread(sharedResource);

// Starting the threads


thread1.start();
thread2.start();
thread3.start();
}
}
Q4 b)

public class MyExClass extends Exception {

public MyExClass(String message) {


super(message);
}

public static void main(String[] args) {


try {
// Example of using MyExClass
validateString("HelloWorld"); // This will throw an exception
} catch (MyExClass ex) {
System.out.println("Caught an exception: " + ex.getMessage());
}
}

public static void validateString(String input) throws MyExClass {


if (input.length() > 10) {
throw new MyExClass("String too large");
} else {
System.out.println("Valid string: " + input);
}
}
}

Q5 b)

// Datagram sender

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DatagramServer {


public static void main(String[] args) throws Exception {
String inp = "Ritik";
DatagramSocket ds = new DatagramSocket();

DatagramPacket dp = new DatagramPacket(inp.getBytes(), inp.length(),


InetAddress.getLocalHost(), 9701);
ds.send(dp);
}
}

// Datagram client

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DatagramClient {


public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(9701);

byte[] buf = new byte[1024];


InetAddress ip = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);

String input = new String(dp.getData(), 0, dp.getLength());

System.out.println("Message recieved: " + input);


System.out.println("The number of character recieved: " + input.length());
}
}

Q7 a) Layout managers in Java are used to define the way components are arranged within a container, such as a JPanel
or JFrame. They help in achieving a consistent and flexible user interface across different platforms and screen sizes.
Layout managers handle the positioning and sizing of components, adapting them dynamically as the user interface
changes.

1. FlowLayout: Arranges components in a left-to-right flow, wrapping to the next row when the current row is
filled.

2. BorderLayout: Divides the container into five regions (north, south, east, west, and center), where components
can be placed, and resizes them as the container is resized.

3. GridLayout: Organizes components in a grid of rows and columns, placing one component in each cell.

4. CardLayout: Manages a stack of components, displaying one at a time, like a deck of cards.

5. BoxLayout: Places components in either a vertical or horizontal line, allowing for flexible alignment.

6. GridBagLayout: Provides a powerful and flexible grid-based layout, allowing components to span multiple rows
and columns with varying weights.

These layout managers facilitate the organization and positioning of components within a container, providing different
strategies for creating user interfaces in Java applications.Here's an example of using the GridLayout:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;

public class GridLayoutExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("GridLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a JPanel with GridLayout


JPanel panel = new JPanel(new GridLayout(3, 3, 10, 10));
// The parameters for GridLayout are rows, columns, horizontal gap, and vertical
gap

// Add buttons to the panel


for (int i = 1; i <= 9; i++) {
JButton button = new JButton("Button " + i);
panel.add(button);
}

// Add the panel to the frame


frame.add(panel);

// Set frame properties


frame.setSize(300, 300);
frame.setVisible(true);
}
}

Q7 b)

Adapter classes in Java are used to provide default implementations for various listener interfaces, allowing developers
to create event listeners by extending these adapter classes and only implementing the methods relevant to their needs.
Adapter classes simplify the implementation of interfaces by providing empty default implementations for all methods.

In GUI programming, adapter classes are commonly used for event handling. One such example is the
MouseMotionAdapter class, which provides default implementations for the MouseMotionListener interface.

Here's an example program demonstrating the usage of MouseMotionAdapter:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MouseMotionAdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame("MouseMotionAdapter Example");
JPanel panel = new JPanel();

// Using a MouseMotionAdapter to handle mouse motion events


panel.addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved: X=" + e.getX() + ", Y=" + e.getY());
}
});

frame.getContentPane().add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Q9 a)

import java.sql.*;
import java.util.*;

public class JDBC {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

//Creating the connection


String url = "jdbc:mysql://localhost:3306/mysql";
String user = "ritik";
String pass = "ritik";

String query;

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

query = "SELECT * FROM COLLEGE.STUDENT WHERE ENROLLMENT_NO < 120";

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(query);
while (rs.next()) {
int i = rs.getInt("enrollment_no");
String n = rs.getString("student_name");
int a = rs.getInt("phone_no");
String d = rs.getString("course");

System.out.println("Enrollment Number: " + i + ", Name: " + n + ", Phone


Number: " + a + ", Course: " + d);
}
} catch (InputMismatchException ignored) {
System.out.println("Enter a valid ID!");
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
}
}

Q9 b)

import java.io.*;
import java.util.StringTokenizer;

public class FileCopy {


public static void main(String[] args) {
try(BufferedReader br = new BufferedReader(new
FileReader("C:\\Users\\admin\\IdeaProjects\\Lab\\tempFile\\Experiment1"))){
String line;
int wordsCopied = 0, linesCopied = 0;
BufferedWriter bw = new BufferedWriter(new
FileWriter("C:\\Users\\admin\\IdeaProjects\\Lab\\tempFile\\Experiment2"));
while (( line = br.readLine()) != null){
bw.write(line);
bw.newLine();
linesCopied++;
StringTokenizer st = new StringTokenizer(line, " ");
wordsCopied += st.countTokens();
}
bw.flush();
bw.close();
System.out.println("The number of words copied: " + wordsCopied);
System.out.println("The number of lines copied: " + linesCopied);

}
catch (IOException ignored){}
}
}

You might also like