OOPJ Sample Questions

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

OHM

LONG QUESTION
1. Demonstrate two Java programs to insert/add items (“Ram”,” Shayam”,” Hari”, “Gopal”, “ravi”) creating
ArrayList and LinkedList object. Iterate and display the items using Iterator class object.

ANS-

Program 1: Using ArrayList


Program 2: Using LinkedList

2. Differentiate between Byte stream and character stream in Java. Write a Java program to copy the
content of “First.txt” to “Second.txt” using FileInputStream and FileOutputStream.

ANS- Byte Stream:

• Byte stream is used to perform I/O operations on 8-bit bytes.


• It's used for handling binary data or raw data, like images or files.
• Example classes: FileInputStream, FileOutputStream.

Character Stream:

• Character stream is used to perform I/O operations on characters.


• It's used for handling text data.
• It converts the character data into byte data using a character encoding.
• Example classes: FileReader, FileWriter.
3. Given an integer array of size N, write a static method occurrenceK that returns the number of
occurrences of the integer at position k in that array, where 0≤ k <N. For example,
occurrenceK({0,1,1,1},0) returns 1, and occurrenceK({3,1,2,1},1) returns 2. Now write a second static
method maxOccurrence that returns the integer which has the highest number of occurrences in a
given integer array. Assume that the previous method has been correctly written and is in the same
class as maxOccurrence. Also assume there is always one such unique integer.
ANS-

4. You are given a text file (registration.txt) that contains lines of pairs of student IDs and course names.
[(2381, Java), ( 1812, ML), (1812, DS), (2381, DB). Each bracket represents a separate instance of a
student registration for a particular course. The course is a String; the student ID is an int. The
delimiter is a comma. You do not know the length of the file before you read all of it. You are to write
a program that: 1. reads the file, 2. counts the number of students registered in each course, and 3.
prints a list of all courses with their enrollment to the console.
ANS-

5. Thread Life cycle

ANS- A thread's life cycle refers to the various stages it goes through during its execution.
These stages are typically represented by states, and a thread can only be in one state at a
time. Here's a breakdown of the common thread states:

• New: A thread is freshly created and hasn't begun execution yet.


• Runnable: The thread is ready to run, but it might be waiting for resources like the
CPU or I/O operations to complete.
• Running: The thread has been allocated the CPU and is actively executing
instructions.
• Blocked: The thread is temporarily suspended because it's waiting for an event to
occur, such as acquiring a lock, I/O completion, or another thread to perform an
action.
• Waiting: Similar to blocked, but with no specific time limit for the event to happen.
This might involve waiting for user input or notification from another thread.
• Terminated: The thread has finished executing its task or has been terminated
forcefully. It can no longer be restarted.
Understanding thread states is crucial for effective multithreaded programming, as it allows
you to manage and synchronize threads properly.

6. CRUD operation

ANS- CRUD stands for Create, Read, Update, and Delete. These are fundamental operations
used in data persistence and management:

• Create: Adds a new record to a database or storage system.


• Read: Retrieves existing data from a database or storage system.
• Update: Modifies existing data in a database or storage system.
• Delete: Removes a record from a database or storage system.

CRUD operations form the basis of interacting with various data sources in applications.
They are often implemented using database libraries or APIs provided by the storage system.

7. Constructor overloading

ANS- Constructor overloading allows a class to have multiple constructors with different
parameter lists. This enables you to create objects of the same class in various ways,
depending on the data you want to provide during initialization.

Here's an example:

Java
class Person {
String name;
int age;

// Default constructor
public Person() {
name = "John Doe";
age = 25;
}

// Constructor with parameters


public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Use code with caution.
content_copy

In this example, you can create a Person object with the default values using the default
constructor or provide a custom name and age using the constructor with parameters.

8. Java Keywords

ANS- Java keywords are reserved words that have specific meanings within the Java
programming language. You cannot use them as variable names, method names, or class
names. Here are some common Java keywords:
• class: Defines a new class
• public: Access modifier for variables and methods
• private: Access modifier for variables and methods
• static: Keyword to declare class-level variables and methods
• void: Denotes a method that doesn't return a value
• int: Data type for integers
• String: Data type for representing text
• if: Conditional statement
• for: Looping construct
• while: Looping construct
• return: Keyword used to return a value from a method

There are many more Java keywords, and you can find a comprehensive list in the official
Java language documentation.

9. Program on exception handling

ANS- Exception handling is a mechanism to manage errors and unexpected situations that
might occur during program execution. It allows you to write more robust and reliable code.
Here's an example program that demonstrates exception handling:

Java
public class ExceptionExample {

public static void main(String[] args) {


try {
int num = Integer.parseInt("hello"); // This line will cause
an exception
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Error: Input string is not a valid
integer.");
System.out.println("Exception details: " + e.getMessage());
}
}
}

In this example:

• The try block attempts to execute the code that might throw an exception.
• The catch block intercepts the exception if it occurs.
• You can handle the exception gracefully within the catch block, such as providing an
error message or taking corrective actions.

This is a simple example, but it illustrates the basic principles of exception handling in Java.

10. Program on string

ANS- public class StringOperations {

public static void main(String[] args) {


// 1. Creating strings

String str1 = "Hello";

String str2 = new String("World");

// 2. Concatenation

String result = str1 + " " + str2;

System.out.println("Concatenated String: " + result);

// 3. Length

System.out.println("Length of str1: " + str1.length());

// 4. Comparison

if (str1.equals(str2)) {

System.out.println("Strings are equal");

} else {

System.out.println("Strings are not equal");

// 5. Substring

String sub = str1.substring(2);

System.out.println("Substring of str1: " + sub);

// 6. Uppercase and lowercase

String upperCaseStr = str1.toUpperCase();

String lowerCaseStr = str2.toLowerCase();

System.out.println("Uppercase of str1: " + upperCaseStr);

System.out.println("Lowercase of str2: " + lowerCaseStr);

// 7. IndexOf

int index = result.indexOf("World");

System.out.println("Index of 'World' in result: " + index);

// 8. Replace
String replaced = result.replace("World", "Universe");

System.out.println("After replacement: " + replaced);

// 9. Split

String sentence = "Java is a programming language";

String[] words = sentence.split(" ");

System.out.println("Words in sentence:");

for (String word : words) {

System.out.println(word);

// 10. Trim

String padded = " Hello ";

String trimmed = padded.trim();

System.out.println("Trimmed string: '" + trimmed + "'");

SHORT QUESTION
1. Justify the problem arises without using “synchronized” keyword for thread synchronization in
Multithreaded program in Java.

ANS- Justification for not using "synchronized" keyword:


Without synchronization, multiple threads accessing shared resources may lead to data inconsistency
due to race conditions. This can result in incorrect program behavior and unpredictable outcomes.

2. Illustrate collection framework in Java. List out some collection frame work.

ANS- Collection frameworks provide a unified architecture to manipulate collections of objects.


Some common frameworks are:
ArrayList
LinkedList
HashSet
TreeSet
HashMap
TreeMap

3. Define marshaling. State the significance of Serialization.

ANS- Marshaling is converting an object into a data format suitable for storage or transmission.
Serialization, a part of marshaling, converts objects into byte streams. Serialization is significant for
saving object states, allowing data to be stored in files or transmitted over networks
.

4. Explain toArray() and contains() methods in List Interface.

ANS- toArray(): Converts a list into an array. It returns an array containing all elements of the list.
contains(): Checks if a specific element exists in the list. It returns true if the element is found,
otherwise false.

5. Name some common implementations of the Java Set interface in the Java Collections Framework.

ANS- Common implementations of the Set interface include HashSet, TreeSet, and LinkedHashSet.

6. Differentiate between StringBuffer and StringBuilder class.

ANS - StringBuffer is synchronized and thread-safe, whereas StringBuilder is not synchronized, making it
faster but not thread-safe.

7. Super keyword

ANS- "super" keyword refers to the superclass instance. It's used to access superclass methods and
constructors, especially when overridden in subclasses.

8. Thread Priority

ANS- Thread priority determines the importance of a thread. Higher priority threads are scheduled before
lower ones. Priority is a hint to the scheduler, not a strict rule.

9. Polymorphism

ANS- Polymorphism allows objects to be treated as instances of their superclass or interface. It enables
methods to be defined by their superclass or interface and overridden by subclasses, enhancing code
flexibility and reusability.

10. Checked vs unchecked

ANS- Checked Exceptions: Checked at compile time, like IOException, need handling.Unchecked
Exceptions: Not checked at compile time, like NullPointerException, don't necessarily need handling.

11. Wait , nofify, yield, resume,sleep methods

ANS- wait(): Waits for a signal from another thread.

notify(): Notifies a waiting thread.

yield(): Temporarily gives up the CPU.

resume(): Resumes a suspended thread.

sleep(): Pauses the current thread for a specified duration.

12. Super keywords

ANS- "super" refers to the superclass object. It's used to access superclass members from subclass
methods or constructors.

13. This keywords

ANS- "this" refers to the current object. It's used to differentiate between instance variables
andparameters with the same name, and to call instance methods.

You might also like