Java 3rd Semester Exam Questions Guide
Java 3rd Semester Exam Questions Guide
An abstract class in Java is a class that cannot be instantiated on its own and is meant to be
• 2 MARKS
subclassed by other classes. It can contain abstract methods (methods without a body) as
1) Define oop.
well as concrete methods (methods with a body). Abstract classes are used to provide a
Object-Oriented Programming (OOP) in Java is a programming paradigm that organizes
common base and define common behaviors for subclasses.
software design around data, or objects, rather than functions and logic. It involves four
Example:
main principles:
abstract class Animal {
1. Encapsulation - Bundling data (variables) and methods that operate on the data into
abstract void sound(); // Abstract method
a single unit (class) and restricting access to some of the object's components.
void eat() { // Concrete method
2. Inheritance - A mechanism where one class (subclass) inherits the properties and
[Link]("Eating...");
behaviors (fields and methods) of another class (superclass).
}
3. Polymorphism - The ability of different classes to respond to the same method call in
}
different ways, based on their specific implementation.
4. Abstraction - Hiding the complex implementation details and showing only the
5)What is an Exception in java?
essential features of an object.
An Exception in Java is an event that disrupts the normal flow of a program's execution. It is
an object that represents an error or an abnormal condition that occurs during the
2)What is data type? Mention numeric data types.
program's runtime, such as division by zero or attempting to access a null object. Exceptions
A data type in Java defines the type of data a variable can hold, such as integers, floating-
are handled using try, catch, throw, and throws keywords to ensure that the program can
point numbers, characters, or boolean values. It determines the operations that can be
continue running or fail gracefully.
performed on the variable and the memory size allocated for it.
The numeric data types in Java are:
6)Define Thread.
1. byte - 8-bit integer.
In Java, a Thread is a single path of execution within a program. It allows for multitasking
2. short - 16-bit integer.
and concurrent execution of code. Threads are created by either extending the Thread class
3. int - 32-bit integer.
or implementing the Runnable interface. Each thread runs independently and can perform
4. long - 64-bit integer.
tasks simultaneously with other threads in the program.
5. float - 32-bit floating-point number.
6. double - 64-bit floating-point number.
• 5 MARKS
3)what do you mean by variable? How to define instance variable? 7)Define Array. How to define array in java. Explain with example.
A variable in Java is a named storage location that holds data which can be changed during Definition of Array:
the execution of a program. It is associated with a data type that determines what kind of An array is a data structure that stores a fixed-size sequence of elements of the same type.
data it can store, such as integers, floating-point numbers, or strings. The elements of an array are stored in contiguous memory locations and can be accessed
using indices, with the first element having index 0. Arrays help in storing multiple values in
An instance variable is a variable that is declared inside a class but outside any methods, a single variable, making it easier to manage and manipulate collections of data.
constructors, or blocks. It is associated with an instance (object) of the class, and each How to Define an Array in Java:
object has its own copy of the instance variable. In Java, an array is an object, and you can define it in the following ways:
Defining an Instance Variable: 1. Declaration of an Array: You specify the type of elements and the array variable:
To define an instance variable in Java, you declare it inside a class but outside any method. dataType[] arrayName; // Example: int[] numbers;
Example: class Car { 2. Creating an Array: To allocate memory and create the array, you use the new keyword:
// Instance variable arrayName = new dataType[size]; // Example: numbers = new int[5];
String color; 3. Alternative Syntax for Declaration and Creation: You can combine both declaration and
} creation in a single line:
dataType[] arrayName = new dataType[size]; // Example: int[] numbers = new 1. Built-in Packages: These are pre-defined packages provided by Java, like [Link],
int[5]; [Link], [Link], etc.
4. Initializing an Array with Values: You can initialize an array with predefined values: 2. User-defined Packages: These are packages created by the developer to organize
dataType[] arrayName = {value1, value2, value3, ...}; // Example: int[] numbers = related classes and interfaces.
{1, 2, 3, 4, 5}; Example of a User-defined Package:
Example: Step 1: Create a Package
public class ArrayExample { Let's create a package called [Link] and define a class MyClass inside it.
public static void main(String[] args) { // File: [Link]
// Define and initialize an array of integers with predefined values package [Link];
int[] numbers = {10, 20, 30, 40, 50};
public class MyClass {
// Print all elements of the array public void display() {
[Link]("Array elements:"); [Link]("Hello from MyClass in [Link]!");
for (int i = 0; i < [Link]; i++) { }
[Link](numbers[i]); }
} In this example:
} • The class MyClass is placed inside the package [Link].
} • The package keyword is used to define the package.
Explanation:
Step 2: Using the Package in Another Class
1. Array Declaration and Initialization: The array numbers is declared and initialized
Now, let's create another class, TestPackage, in a different file, and use the MyClass from
with 5 integer values: {10, 20, 30, 40, 50}.
the [Link] package.
2. Accessing Array Elements: Using a for loop, we access each element of the array by
// File: [Link]
its index (starting from 0) and print the values.
import [Link];
8) What is package? Explain with example.
public class TestPackage {
In Java, a package is a mechanism for organizing and grouping related classes and interfaces
public static void main(String[] args) {
together. It helps in avoiding class name conflicts, enhancing code modularity, and providing
MyClass obj = new MyClass();
access control. Packages can be either built-in (predefined by Java) or user-defined (created
[Link]();
by developers).
}
Key Features of Packages:
}
1. Organization: Packages provide a structured way to organize code, making it easier to
Here:
manage large projects.
• We use the import statement to bring MyClass from the [Link]
2. Avoiding Name Conflicts: Classes with the same name can exist in different packages
package into the TestPackage class.
without conflict.
• We create an instance of MyClass and invoke its display method.
3. Access Control: Packages can help control the visibility of classes, methods, and
Compiling and Running the Code:
variables using access modifiers such as public, protected, private, and package-
To compile and run the code, you need to ensure the proper directory structure is followed.
private (default).
The com/example/mypackage/ directory structure should be created on your system.
4. Reusability: Classes and interfaces within a package can be reused across different
• First, compile the [Link] file:
parts of an application or even in different projects.
javac com/example/mypackage/[Link]
Types of Packages:
• Then, compile the [Link] file:
javac [Link]
• Finally, run the TestPackage class Life Cycle of a Thread in Java:
java TestPackage The life cycle of a thread is controlled by the JVM and can be divided into various states. The
Output: following are the states in the life cycle of a thread:
Hello from MyClass in [Link]! 1. New (Born) State:
o A thread is in the New state when it is created but has not yet started.
9) Explain the following: o In this state, the thread object is created using the Thread class, but it has not
(i) Check boxes: (ii) Radio buttons: (iii) Text fields. started execution yet.
1. Check Boxes: o Example: Thread t = new Thread();
• A checkbox is a graphical user interface (GUI) component that allows users to select 2. Runnable State:
one or more options from a set of choices. o A thread enters the Runnable state after the start() method is called.
• In Java, JCheckBox class is used to create checkboxes. o In this state, the thread is ready for execution, but it may not be executing
• It can either be in a checked or unchecked state. immediately due to the thread scheduler’s behavior.
• Multiple checkboxes can be selected at the same time, making it ideal for multiple o The thread is eligible for CPU time and can be either running or waiting for the
choice options. CPU.
• Example: o Example: [Link]();
JCheckBox checkBox = new JCheckBox("Accept Terms and Conditions"); 3. Blocked/Waiting State:
2. Radio Buttons: o A thread enters the Blocked state when it is waiting for a resource or a lock,
• A radio button is a GUI component that allows the user to select only one option such as a synchronized block.
from a group of choices, unlike checkboxes where multiple selections are allowed. o A thread enters the Waiting state when it is waiting indefinitely for another
• Java uses the JRadioButton class to create radio buttons. thread to perform a particular action (e.g., join(), wait()).
• Radio buttons are typically grouped together in a ButtonGroup to enforce single 4. Timed Waiting State:
selection behavior. o A thread enters the Timed Waiting state when it is waiting for a specific period,
• Example: such as with methods like sleep() or join(time).
JRadioButton radioButton = new JRadioButton("Male"); o Example: [Link](1000);
ButtonGroup group = new ButtonGroup(); 5. Terminated (Dead) State:
[Link](radioButton); o A thread enters the Terminated state when it completes its execution or when
3. Text Fields: it is stopped by an exception or manually.
• A text field is a GUI component that allows users to input a single line of text. o Once in the Dead state, the thread cannot be restarted.
• In Java, JTextField is used to create text fields. o Example: When the run() method finishes executing.
• It allows users to type input and retrieve the text entered by the user.
• It is commonly used for collecting user inputs such as names, addresses, and search
queries.
• Example:
JTextField textField = new JTextField("Enter your name");
11) Explain any three string class methods with syntax. • Description: Compares two strings for equality. It returns true if the strings are
In Java, the String class provides a variety of methods that help in manipulating strings. Here identical (case-sensitive).
are ten commonly used string methods, their descriptions, syntax, and examples: • Syntax:
1. length() boolean isEqual = [Link](string2);
• Description: Returns the length of the string (the number of characters in the string). • Example:
• Syntax: String str1 = "hello";
int length = [Link](); String str2 = "hello";
• Example: boolean isEqual = [Link](str2);
String str = "Hello"; [Link](isEqual); // Output: true
int len = [Link]();
[Link](len); // Output: 5 6. substring(int beginIndex, int endIndex)
• Description: Returns a substring starting from beginIndex (inclusive) to endIndex
2. charAt(int index) (exclusive).
• Description: Returns the character at the specified index in the string. • Syntax:
• Syntax: String subStr = [Link](int beginIndex, int endIndex);
char ch = [Link](int index); • Example:
• Example: String str = "Hello, World!";
String str = "Hello"; String subStr = [Link](7, 12);
char ch = [Link](1); [Link](subStr); // Output: World
[Link](ch); // Output: e
7. replace(char oldChar, char newChar)
3. toUpperCase() • Description: Replaces all occurrences of the specified character oldChar with
• Description: Converts all characters of the string to uppercase. newChar.
• Syntax: • Syntax:
String upperCaseStr = [Link](); String newString = [Link](char oldChar, char newChar);
• Example: • Example:
String str = "hello"; String str = "banana";
String result = [Link](); String result = [Link]('a', 'o');
[Link](result); // Output: HELLO [Link](result); // Output: bonono
Visibility modifiers in Java are used to control the accessibility of classes, methods, and
variables. They define the scope or visibility of these members from other classes. Java Types of Inheritance in Java
provides four types of visibility modifiers: Java supports four main types of inheritance:
[Link]: 1. Single Inheritance
• The public modifier makes a class, method, or variable accessible from anywhere 2. Multilevel Inheritance
in the program, including other packages. 3. Hierarchical Inheritance
• It offers the widest level of accessibility. 4. Multiple Inheritance (via interfaces)
Example:
public class MyClass { } 1. Single Inheritance:
public void myMethod() { In single inheritance, a subclass inherits from one superclass. It is the simplest form of
2. Private: inheritance in which the derived class has only one parent class.
• The private modifier restricts the accessibility to the defining class only. No other Example:
class, not even subclasses, can access private members. // Superclass (Base class)
class Animal {
• It provides the highest level of encapsulation. void eat() {
Example: [Link]("Eating...");
}
private int myVar; }
private void myMethod() { }
3. Protected: // Subclass (Derived class)
class Dog extends Animal {
• The protected modifier allows access to the members by the defining class, void bark() {
subclasses (even in different packages), and classes in the same package. [Link]("Barking...");
}
• It strikes a balance between private and public.
}
Example:
protected int myVar; public class Main {
public static void main(String[] args) {
protected void myMethod() { } Dog dog = new Dog();
4. Default (Package-Private): [Link](); // Inherited from Animal
[Link](); // Dog's own method
• When no modifier is used, it’s known as the default access modifier. Members
}
with default access are accessible only within the same package and not from }
classes in other packages. Explanation:
Example: • The Dog class inherits the eat() method from the Animal class.
int myVar; // default access • The Dog class also has its own method, bark(), which is not part of the Animal class.
void myMethod() { }
2. Multilevel Inheritance:
13) Define inheritance. Explain all types of inheritance with example. In multilevel inheritance, a class derives from a class that is already derived from another
Inheritance in Java: class. This forms a chain of inheritance where each class inherits from the one above it.
Definition: Inheritance is a fundamental concept in Object-Oriented Programming (OOP) Example:
that allows a class to acquire properties and behaviors (fields and methods) from another // Superclass (Base class)
class Animal {
class. It enables the creation of a new class (subclass or derived class) based on an existing void eat() {
class (superclass or base class). The subclass can reuse, extend, or modify the behavior of [Link]("Eating...");
}
the superclass, making the code more modular and reusable. }
Java supports single, multilevel, hierarchical, and multiple inheritance (through interfaces)
to create relationships between classes. // Subclass 1 (Derived class)
class Dog extends Animal {
void bark() { [Link](); // Dog's own method
[Link]("Barking...");
} Cat cat = new Cat();
} [Link](); // Inherited from Animal
[Link](); // Cat's own method
// Subclass 2 (Grandchild class) }
class Puppy extends Dog { }
void play() { Explanation:
[Link]("Playing...");
} • Both Dog and Cat inherit the eat() method from the Animal class.
} • Each subclass also defines its own unique methods like bark() and meow().
(a) 4. stop():
An applet is a small Java program designed to run in a web browser. Unlike traditional o This method is called when the applet is no longer visible or when the browser
applications, applets are designed to be embedded in web pages and run within the context is navigating away from the page containing the applet.
of the browser's Java Virtual Machine (JVM). Applets can be used to create interactive web- o It is used to suspend activities like animations or to release any resources (e.g.,
based applications such as games, calculators, or data visualization tools. threads) that the applet may have been using.
Life Cycle of an Applet: o Syntax
The life cycle of an applet consists of several stages, which are defined by methods that the public void stop()
applet's parent class, [Link], provides. Here are the key stages:
{
1. init():
// To stop the applet code
o This method is called when the applet is first loaded into the browser or applet
}
viewer.
5. destroy():
o It is used for one-time initialization, such as setting up GUI components
o This method is called when the applet is being unloaded from memory,
(buttons, text fields), and initializing any resources required for the applet.
typically when the browser or applet viewer is closed.
o Syntax
o It is used to release any resources (e.g., open files, database connections) and
public void init()
perform any necessary clean-up tasks.
{ o Syntax
// To initialize objects public void destroy()
}
{
// To destroy the applet
2. start():
}
o This method is called after init() and every time the applet becomes visible
(e.g., when the user navigates to a new page containing the applet).
o The start() method is typically used to start or resume animation or any other
ongoing tasks, such as reading data.
o Syntax
public void start()
{
// To start the applet code
}
3. paint():
o This method is called whenever the applet needs to be repainted (e.g., after
being resized or when the window becomes visible again).
o The paint() method is where you perform custom drawing, such as rendering
images or graphics on the applet's canvas.
o Syntax
public void paint(Graphics graphics)
{ 15) Explain various methods of random access files class.
// Any shape's code Random Access Files in Java
}
Java provides the RandomAccessFile class for handling files where you can read and write int byteRead = [Link]();
data at any position (random access). Unlike the FileInputStream and FileOutputStream if (byteRead != -1) {
classes, which allow sequential access, RandomAccessFile allows for non-sequential reading [Link]("Byte read: " + byteRead);
and writing. It is especially useful when dealing with large files or when you need to modify }
data at specific locations in the file. 5. int read(byte[] b)
Here’s an explanation of the various methods provided by the RandomAccessFile class: • Description: Reads multiple bytes into a byte array. The method returns the number
1. RandomAccessFile(File file, String mode) of bytes actually read, or -1 if the end of the file is reached.
• Description: This constructor is used to create a RandomAccessFile object. It takes a • Parameters:
File object and a String that specifies the access mode for the file. o b: A byte array where the data will be stored.
• Parameters: • Returns: The number of bytes read.
o file: The file to be opened. • Example:
o mode: The mode in which to open the file. Valid modes are: byte[] buffer = new byte[100];
▪ "r": Open the file for reading. int bytesRead = [Link](buffer);
▪ "rw": Open the file for both reading and writing. [Link]("Bytes read: " + bytesRead);
▪ "rwd": Open for reading and writing, with immediate disk 6. void write(int b)
synchronization after each write operation. • Description: Writes a single byte to the file. This is useful for appending data or
▪ "rws": Open for reading and writing, and updates are immediately overwriting existing data at the current file pointer position.
reflected in file metadata. • Parameters:
• Example: o b: The byte to write.
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw"); • Example:
2. long getFilePointer() [Link](65); // Writes byte value of 'A'
• Description: This method returns the current file pointer position, which is the byte 7. void write(byte[] b)
offset from the beginning of the file. The file pointer moves automatically as data is • Description: Writes an array of bytes to the file starting from the current position of
read or written. the file pointer.
• Returns: The current file pointer position as a long. • Parameters:
• Example: o b: The byte array to write.
long position = [Link](); • Example:
[Link]("Current pointer position: " + position); byte[] data = {65, 66, 67}; // Represents 'ABC'
3. void seek(long pos) [Link](data);
• Description: Moves the file pointer to a specific position in the file. This allows you to 8. void writeBytes(String s)
skip ahead or go back to any part of the file. • Description: Writes a string to the file as a sequence of bytes. This method writes
• Parameters: each character as a byte (without encoding it as characters).
o pos: The byte position where the file pointer should move. Position 0 refers to • Parameters:
the beginning of the file. o s: The string to write.
• Example: • Example:
[Link](50); // Move the file pointer to byte 50 [Link]("Hello");
4. int read() 9. void writeChar(int v)
• Description: Reads a single byte from the file and returns it. The return value is an • Description: Writes a single character to the file, encoded as 2 bytes in Unicode.
integer representing the byte read, or -1 if the end of the file is reached. • Parameters:
• Returns: The byte read, or -1 if the end of the file is reached. o v: The character (as an integer) to write.
• Example: • Example: