0% found this document useful (0 votes)
18 views20 pages

Java Previous Year

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views20 pages

Java Previous Year

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

1. What is the use of constructor in In java?

Write a program where we can overload


constructor to initiize instance variable of a class?

In Java, a constructor is a special method used to initialize objects of a class. It has the
same name as the class and no return type. Constructors are invoked automatically when
an object of the class is created.
Java allows constructor overloading, which means you can define multiple constructors
in a class with different parameters. This allows you to initialize objects in different ways.

program example:

class Employee {
String name;
int age;

// Default constructor (no parameters)


public Employee() {
name = "Unknown";
age = 0;
}

// Constructor with one parameter (overloaded)


public Employee(String name) {
this.name = name;
age = 0;
}

// Constructor with two parameters (overloaded)


public Employee(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display the employee details


public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
// Using different constructors to create objects
Employee emp1 = new Employee(); // Default constructor
Employee emp2 = new Employee("Alice"); // Constructor with 1 parameter
Employee emp3 = new Employee("Bob", 30); // Constructor with 2 parameters

// Displaying employee information


emp1.displayInfo();
emp2.displayInfo();
emp3.displayInfo();
}
}

2. What is the use of late binding? Write a program to check whether entered string is
having more then two digits in it or not.

Late Binding (Dynamic Binding) refers to the decision of which method to call being
made at runtime rather than compile-time. In object-oriented programming, this typically
happens when methods are overridden in subclasses.
• In early binding (also called static binding), the method to be executed is determined at
compile-time.
• In late binding, it is determined at runtime. This feature is essential for polymorphism,
where the method that is called depends on the actual object (i.e., runtime type) rather
than the reference type.

Program to Check if a String Contains More Than Two Digits:


import java.util.Scanner;

public class Main {


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

// Prompt the user to enter a string


System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Initialize digit count


int digitCount = 0;
// Loop through each character in the string
for (int i = 0; i < input.length(); i++) {
// Check if the character is a digit
if (Character.isDigit(input.charAt(i))) {
digitCount++;
}

// If digit count exceeds 2, we can stop checking


if (digitCount > 2) {
break;
}
}

// Check if there are more than 2 digits


if (digitCount > 2) {
System.out.println("The string contains more than two digits.");
} else {
System.out.println("The string does not contain more than two digits.");
}

scanner.close();
}
}

3. What is the use of Wrapper classes Write a program where we can say down casting
may fail

Wrapper classes in Java provide a way to use primitive data types (like int, char, double)
as objects. Each primitive type has a corresponding wrapper class in Java,

Uses of Wrapper Classes:


1. Conversion between primitives and objects: Wrapper classes allow you to convert
primitive data types into objects and vice versa (Autoboxing and Unboxing).
2. Collections: Java collections (like ArrayList, HashSet) store objects, not primitives.
Wrapper classes help in storing primitive values in collections.
3. Utility Methods: Wrapper classes provide several utility methods (e.g.,
Integer.parseInt(), Double.valueOf()).
4. Nullability: Wrapper objects can be null, but primitive types cannot.
5. Immutability: Wrapper objects are immutable, meaning their values cannot be changed
once they are created.
Example where Downcasting may Fail:
class Animal {
void sound() {
System.out.println("Some generic animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}

void fetch() {
System.out.println("Dog fetches the ball");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Cat(); // Upcasting - a Cat is stored as an Animal

// This downcasting may fail if not done carefully


if (myAnimal instanceof Dog) {
Dog myDog = (Dog) myAnimal; // This will throw ClassCastException
myDog.sound();
} else {
System.out.println("Downcasting failed! The object is not a Dog.");
}
}
}

Why Downcasting Can Fail:


Downcasting can fail because Java does not automatically check whether the object is
actually an instance of the subclass you're casting to. If it's not, you will get a
ClassCastException at runtime.

4. What is the use of interface over abstract class? How we can use anonymous inner
class?

Interface vs Abstract Class in Java


Both interfaces and abstract classes are used to achieve abstraction in Java, but they
have different use cases and characteristics. Here’s when and why you would prefer one
over the other:
When to Use an Interface:
• Multiple inheritance: A class can implement multiple interfaces, allowing Java to
overcome the limitations of single inheritance.
• Complete abstraction: Interfaces are used when you want to define a contract without
any concrete implementation.
• Loose coupling: Interfaces help define a clear separation between what a class should do
and how it does it. This enables a more flexible and decoupled design.
When to Use an Abstract Class:
• Partial abstraction: Use an abstract class when you need to provide a common base with
some shared implementation and some abstract methods to be overridden.
• Code reuse: Abstract classes allow you to include concrete methods that can be reused
by multiple subclasses.
• Shared state: If you want subclasses to inherit fields and methods with specific
functionality, an abstract class is the way to go.

Anonymous Inner Class with Abstract Class:


abstract class Animal {
abstract void makeSound();
}

public class Main {


public static void main(String[] args) {
// Anonymous inner class implementing abstract class Animal
Animal dog = new Animal() {
@Override
void makeSound() {
System.out.println("Bark from anonymous class!");
}
};

dog.makeSound(); // Output: Bark from anonymous class!


}
}

5. What are command line arguments ?Write a program to show the use of static
import.

Command-line arguments are parameters passed to the main method when running a Java
program. These arguments are stored in a String array (args) in the main() method and
can be used to customize the behavior of the program based on input provided at runtime.

Example of Command Line Arguments:


public class CommandLineExample {
public static void main(String[] args) {
// Check if any arguments are passed
if (args.length > 0) {
System.out.println("Command-line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i+1) + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments passed.");
}
}
}

6. What is the use of final keyword? Write a program to show the use of protected
keyword

Use of the final Keyword in Java:


The final keyword in Java can be used in three contexts:
1. Variables: A final variable cannot be reassigned once initialized. This is similar to
making the variable a constant.
2. Methods: A final method cannot be overridden by subclasses.
3. Classes: A final class cannot be subclassed.

Example of protected Keyword:


// In file ParentClass.java
package mypackage;

public class ParentClass {


protected String name = "ParentClass";

protected void display() {


System.out.println("This is a protected method from ParentClass.");
}
}

// In file ChildClass.java (within the same package)


package mypackage;

public class ChildClass extends ParentClass {


public void showName() {
System.out.println("Accessing protected member: " + name);
display();
}
}

// In file TestProtected.java (from a different package)


package otherpackage;
import mypackage.ParentClass;

public class TestProtected {


public static void main(String[] args) {
ParentClass obj = new ParentClass();
// obj.name; // Error! Cannot access protected member from a different package
// obj.display(); // Error! Cannot access protected method from a different package
}
}

7. Define and explain Thread life cycle Write a program to show the use of
synchronized keyword.

Thread Life Cycle in Java


The life cycle of a thread in Java consists of several states. These states represent the
various stages of a thread from its creation to its termination. The thread life cycle can be
described using the following states:
1. New:
oWhen a thread is created using the Thread class but not yet started, it is in the
"new" state.
o Example: Thread t = new Thread();
2. Runnable:
o After calling the start() method, the thread moves to the "runnable" state.
o In this state, the thread is ready to run but may not be currently executing due to
the availability of CPU.
3. Blocked/Waiting:
o A thread enters this state when it is waiting for a monitor lock (in case of
synchronized blocks) or waiting for a condition (e.g., using methods like wait(),
join(), or sleep()).
o It remains in this state until the condition is met or the lock is acquired.
4. Timed Waiting:
o A thread enters this state when it calls methods like sleep(long timeout) or
wait(long timeout), where the waiting time is specified. The thread will
automatically wake up after the specified time has elapsed.
5. Terminated (Dead):
o When a thread completes its execution, either by completing the run method or
encountering an exception, it enters the "terminated" state.
Diagram of Thread Life Cycle:
• New → Runnable → Running → Blocked/Waiting → Runnable → Terminated

class SharedResource {
private int count = 0;

// Synchronized method to increment count


public synchronized void increment() {
count++;
}

public int getCount() {


return count;
}
}

class WorkerThread extends Thread {


SharedResource resource;

WorkerThread(SharedResource resource) {
this.resource = resource;
}

public void run() {


for (int i = 0; i < 1000; i++) {
resource.increment(); // Synchronization ensures only one thread increments at a
time
}
}
}

public class SynchronizedExample {


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

// Two threads trying to access the same shared resource


WorkerThread t1 = new WorkerThread(resource);
WorkerThread t2 = new WorkerThread(resource);

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final count: " + resource.getCount());


}
}

8. What is difference between character and byte streams? Write a program to write
state of an object into a file

Difference Between Character and Byte Streams:


1. Byte Stream:
• Definition: Byte streams are used to handle raw binary data. They read and write data in
bytes.
• Classes:
o InputStream and OutputStream are the parent classes.
o Example: FileInputStream, FileOutputStream.
• Use: Byte streams are suitable for handling all types of data (image, audio, video) except
text files. They read and write data byte by byte.
• Encoding/Decoding: No character encoding is involved.
2. Character Stream:
• Definition: Character streams are used to handle character data. They read and write data
in characters.
• Classes:
o Reader and Writer are the parent classes.
o Example: FileReader, FileWriter.
• Use: Character streams are mainly used to handle text data (e.g., .txt, .csv).
• Encoding/Decoding: Character streams use character encoding, such as UTF-8, UTF-16.

Program to Write the State of an Object into a File

import java.io.*;

// A class must implement Serializable to allow its objects to be written to a file


class Employee implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for serialization
String name;
int age;

public Employee(String name, int age) {


this.name = name;
this.age = age;
}

public String toString() {


return "Employee Name: " + name + ", Age: " + age;
}
}

public class SerializeExample {


public static void main(String[] args) {
// Create an object of Employee
Employee employee = new Employee("John Doe", 30);
// Serialize the object and write it to a file
try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {

out.writeObject(employee); // Write object to file


System.out.println("Object has been serialized and written to employee.ser");

} catch (IOException e) {
e.printStackTrace();
}

// Deserialize the object from the file


try (FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {

Employee deserializedEmployee = (Employee) in.readObject(); // Read object


from file
System.out.println("Object has been deserialized: " + deserializedEmployee);

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}

9. What is the use of Object class in java? Write a program to remove all duplicate
characters from a string

Use of Object Class in Java:


The Object class in Java is the root of the class hierarchy. Every class in Java implicitly
or explicitly extends the Object class, meaning that all Java classes inherit the methods
defined in Object. Here are some commonly used methods provided by the Object class:

1. equals(): Compares two objects for equality. By default, it checks whether two references
point to the same memory location. Can be overridden to compare object properties.
2. hashCode(): Returns a hash code value for the object. It is used in hash-based collections
like HashMap, HashSet, etc.
3. toString(): Returns a string representation of the object. By default, it returns the class
name followed by the object's hash code. Often overridden to provide meaningful output.
4. clone(): Creates and returns a copy of the object.
5. finalize(): Called by the garbage collector before an object is destroyed.
6. getClass(): Returns the runtime class of the object.

Program to Remove All Duplicate Characters From a String:

import java.util.LinkedHashSet;

public class RemoveDuplicates {


public static String removeDuplicateChars(String input) {
// Use LinkedHashSet to maintain the order and remove duplicates
LinkedHashSet<Character> set = new LinkedHashSet<>();

// Add characters to the set


for (char c : input.toCharArray()) {
set.add(c);
}

// Build a string without duplicates


StringBuilder result = new StringBuilder();
for (char c : set) {
result.append(c);
}

return result.toString();
}

public static void main(String[] args) {


String input = "programming";
String output = removeDuplicateChars(input);

System.out.println("Original String: " + input);


System.out.println("String after removing duplicates: " + output);
}
}

10. What is the use of InetAddress class? Write a code to send you name from one
machine to another machine using socket class in order to receive your name in
uppercase.

Use of InetAddress Class in Java:


The InetAddress class in Java is used to represent an IP address, both IPv4 and IPv6. It
provides methods for determining the IP address of a host, resolving domain names to IP
addresses, and more.
Key uses of the InetAddress class:
1. Getting the IP Address of a Host: You can use InetAddress.getByName() to get the IP
address of a given hostname or InetAddress.getLocalHost() to get the local IP address.
2. DNS Resolution: InetAddress can resolve a domain name into its corresponding IP
address.
3. Working with IP Addresses: It can be used to perform network-related tasks such as
socket communication.

Code to Send and Receive Name using Socket Programming

import java.io.*;
import java.net.*;

public class NameServer {


public static void main(String[] args) {
try {
// Create a server socket listening on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server is running and waiting for a client...");

// Accept a connection from the client


Socket socket = serverSocket.accept();
System.out.println("Client connected!");

// Input stream to receive data from client


BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Output stream to send data to client


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Read the name sent by the client


String name = in.readLine();
System.out.println("Received name: " + name);

// Convert the name to uppercase and send it back to the client


String upperCaseName = name.toUpperCase();
out.println(upperCaseName);
System.out.println("Sent back uppercase name: " + upperCaseName);

// Close the connections


in.close();
out.close();
socket.close();
serverSocket.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}

11. What is the role of URL class in java? Write a program in support to show where we
can say StringBuffer is faster then String class

Role of URL Class in Java:


The URL class in Java represents a Uniform Resource Locator, which is a pointer to a
resource on the Internet. It provides methods for accessing and manipulating different
components of a URL, such as the protocol, host, port, path, and query parameters.
Key functionalities of the URL class:
1. Creating URLs: You can create a URL object using a string representation of a URL.
2. Accessing Components: The URL class allows you to retrieve components of the URL,
such as the protocol (e.g., HTTP, HTTPS), host, port, file path, and query.
3. Opening Connections: It provides methods to open a connection to the resource pointed
to by the URL using the openConnection() method.
4. Reading Data: You can read data from a URL, typically using input streams.

Example Program to Demonstrate StringBuffer vs. String

public class StringBufferVsString {


public static void main(String[] args) {
// Test with String
long startTime = System.nanoTime();
String str = "";
for (int i = 0; i < 10000; i++) {
str += "Hello"; // String concatenation
}
long endTime = System.nanoTime();
long durationString = endTime - startTime;
System.out.println("Time taken with String: " + durationString + " nanoseconds");

// Test with StringBuffer


startTime = System.nanoTime();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 10000; i++) {
stringBuffer.append("Hello"); // StringBuffer concatenation
}
endTime = System.nanoTime();
long durationStringBuffer = endTime - startTime;
System.out.println("Time taken with StringBuffer: " + durationStringBuffer + "
nanoseconds");

// Show the final lengths to demonstrate successful concatenation


System.out.println("Length of String: " + str.length());
System.out.println("Length of StringBuffer: " + stringBuffer.length());
}
}

12. What is the use of Collection Framework? Write a program to show the working of
Set interface.

Use of Collection Framework in Java


The Java Collection Framework (JCF) provides a set of classes and interfaces to handle
groups of objects. Its primary purposes include:
1. Data Structure Management: It offers standard data structures (like lists, sets, and
maps) that simplify data management.
2. Ease of Use: The framework provides a consistent and easy-to-use interface for
manipulating collections of objects.
3. Performance: It includes optimized algorithms and data structures, enhancing
performance for various operations.
4. Flexibility: It allows for easy swapping of different implementations (like using
ArrayList instead of LinkedList) without changing the code that uses the collection.
5. Thread-Safety: It provides ways to create synchronized (thread-safe) collections.

Example Program to Show the Working of the Set Interface

import java.util.HashSet;
import java.util.Set;

public class SetExample {


public static void main(String[] args) {
// Create a HashSet to store strings
Set<String> set = new HashSet<>();

// Adding elements to the set


set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // Duplicate entry

// Display the set


System.out.println("Set elements: " + set);

// Check if the set contains a specific element


if (set.contains("Banana")) {
System.out.println("Banana is in the set.");
}

// Remove an element from the set


set.remove("Cherry");
System.out.println("Set after removing Cherry: " + set);

// Iterate through the set


System.out.println("Iterating through the set:");
for (String fruit : set) {
System.out.println(fruit);
}

// Size of the set


System.out.println("Size of the set: " + set.size());
}
}

13. What are JDBC drivers? Write a program to insert your name into database table if
name does not exists
JDBC (Java Database Connectivity) drivers are software components that enable Java
applications to interact with databases. They provide the necessary functionality to
connect to a database, execute SQL queries, and retrieve results. There are four types of
JDBC drivers:
1. Type 1: JDBC-ODBC Bridge Driver:
o Uses ODBC drivers to connect to databases.
o Not recommended for production use due to performance issues.
2. Type 2: Native-API Driver:
o Converts JDBC calls into database-specific calls using the native API of the
database.
o Requires native libraries and is not portable across different databases.
3. Type 3: Network Protocol Driver:
o Uses a middleware server to translate JDBC calls into database-specific calls.
o More flexible and portable but requires a network server.
4. Type 4: Thin Driver:
o Pure Java driver that directly converts JDBC calls into the database-specific
protocol.
o Most widely used and recommended for production due to its performance and
portability.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class InsertName {


public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database"; // Replace with your
database URL
String username = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password

String nameToInsert = "John Doe"; // Replace with your name

try (Connection connection = DriverManager.getConnection(jdbcUrl, username,


password)) {
// Check if the name already exists
String checkQuery = "SELECT * FROM users WHERE name = ?";
try (PreparedStatement checkStmt = connection.prepareStatement(checkQuery)) {
checkStmt.setString(1, nameToInsert);
ResultSet resultSet = checkStmt.executeQuery();

if (!resultSet.next()) { // If no results, the name doesn't exist


// Insert the name into the table
String insertQuery = "INSERT INTO users (name) VALUES (?)";
try (PreparedStatement insertStmt =
connection.prepareStatement(insertQuery)) {
insertStmt.setString(1, nameToInsert);
insertStmt.executeUpdate();
System.out.println("Name inserted successfully: " + nameToInsert);
}
} else {
System.out.println("Name already exists: " + nameToInsert);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

14. Define and explain Serviet life cycle. How we can process get and post requests?
Explain by the help of proper example

A servlet is a Java class that handles HTTP requests and responses in a web application.
The life cycle of a servlet is managed by the servlet container (e.g., Apache Tomcat). It
consists of the following phases:
1. Loading and Instantiation:
o The servlet class is loaded into memory by the servlet container.
o An instance of the servlet is created.
2. Initialization:
o The init() method is called once to initialize the servlet.
o This method is used to perform tasks such as loading configuration data and
initializing resources.
3. Request Handling:
o The servlet container calls the service() method to handle requests.
o This method can process both GET and POST requests (and others like PUT,
DELETE) by delegating to specific methods (doGet(), doPost(), etc.).
o Each request is handled in a separate thread.
4. Destruction:
o When the servlet needs to be removed (e.g., when the server shuts down), the
destroy() method is called.
o This method is used to clean up resources (e.g., closing database connections).

Processing GET and POST Requests


In servlets, the doGet() method is used to handle GET requests, and the doPost() method
is used for POST requests.

15. What is the use of garbage collector? Write all the steps to create executable jar file.

The garbage collector (GC) in Java is an automatic memory management system


responsible for reclaiming memory by identifying and disposing of objects that are no
longer in use (i.e., unreachable).

Steps to Create an Executable JAR File:

Step 1: Write Your Java Program


// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Step 2: Compile Your Java Program

javac HelloWorld.java

Step 3: Create a Manifest File

Manifest-Version: 1.0
Main-Class: HelloWorld

Step 4: Package the JAR File

jar cfm HelloWorld.jar MANIFEST.MF HelloWorld.class


Step 5: Run the Executable JAR File

java -jar HelloWorld.jar

You might also like