java pyq
java pyq
1. Platform Dependency:
a. C++ is platform-dependent (compiled into machine code).
b. Java is platform-independent (compiled to bytecode and runs on JVM).
2. Memory Management:
a. C++ uses manual memory management (via new and delete).
b. Java has automatic garbage collection.
3. Multiple Inheritance:
a. C++ supports multiple inheritance directly.
b. Java does not support multiple inheritance with classes (uses interfaces
instead).
4. Pointers:
a. C++ supports pointers explicitly.
b. Java does not support explicit pointers for security and simplicity.
🔹 What is a Constructor?
1. Default Constructor
a. Takes no arguments.
b. Java provides it automatically if no constructor is defined.
2. Parameterized Constructor
a. Takes arguments to initialize fields with specific values.
3. Copy Constructor (Custom)
a. Copies values from one object to another (manually created, not built-in like
C++).
🔹 Example Program:
java
CopyEdit
class Student {
String name;
int age;
// Default Constructor
Student() {
name = "Unknown";
age = 0;
}
// Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
s1.display();
s2.display();
}
}
🔹 Key Features:
• A static member (variable or method) belongs to the class, not to any specific
object.
• It can be accessed without creating an object of the class.
• Static members are shared among all instances of a class.
🔹 Types of Static Members:
1. Static Variable
a. Shared across all objects.
b. Useful for constants or counting objects.
2. Static Method
a. Can be called using the class name.
b. Cannot access non-static (instance) variables directly.
3. Static Block
a. Executes once when the class is loaded.
b. Used for static initialization.
🔹 Example Program:
java
CopyEdit
class Student {
int rollNo;
static String college = "ABC College"; // Static variable
Student(int r) {
rollNo = r;
}
void display() {
System.out.println("Roll No: " + rollNo + ", College: " +
college);
}
}
s1.display();
s2.display();
s1.display();
s2.display();
}
}
🔹 Key Points:
🔹 Definition:
The Java Virtual Machine (JVM) is a part of the Java Runtime Environment (JRE) that runs
Java programs. It converts Java bytecode into machine code and executes it on the host
system. JVM makes Java platform-independent, meaning the same code can run on any
OS that has a JVM.
1. Class Loader:
a. Loads .class files (bytecode) into memory.
b. Performs loading, linking, and initialization.
2. Method Area:
a. Stores class-level data like method code, field info, and static variables.
3. Heap:
a. Stores all objects and class instances.
b. Shared memory area.
4. Stack:
a. Stores method calls and local variables.
b. Each thread has its own stack.
5. Program Counter (PC) Register:
a. Stores the address of the current instruction being executed.
6. Execution Engine:
a. Interpreter: Reads and executes bytecode line by line.
b. JIT Compiler: Converts frequently used bytecode to native code for better
performance.
7. Native Method Interface:
a. Allows JVM to interact with native libraries (like C/C++).
8. Native Method Libraries:
a. Contains platform-specific native code used via JNI (Java Native Interface).
✅ Diagram (Text-based):
pgsql
CopyEdit
+-------------------------+
| Class Loader |
+-----------+-------------+
|
+-----------v-------------+
| Method Area |
+-----------+-------------+
| | |
+-------v-----+ +---v---+ +-------v------+
| Heap | | Stack | | PC Register |
+-------------+ +-------+ +--------------+
|
+-------v-------+
| Execution Engine |
+--------+--------+
|
+--------v--------+
| Native Interface |
+--------+--------+
| Native Libraries |
+------------------+
🔹 Conclusion:
Java achieves platform independence through its compilation process and the use of the
Java Virtual Machine (JVM).
1. Compilation to Bytecode: Java source code (.java files) is compiled into bytecode
(.class files) by the Java compiler (javac). This bytecode is platform-neutral and not
specific to any operating system or hardware architecture.
2. Role of the JVM: The JVM is responsible for interpreting or compiling the bytecode
into native machine code that the host system can execute. Since JVM
implementations exist for various platforms (e.g., Windows, Linux, macOS), the
same bytecode can run on any system that has the appropriate JVM
installed .javatpoint.com
This combination of compiling to bytecode and interpreting it via the JVM allows Java
applications to be written once and run anywhere, embodying the "Write Once, Run
Anywhere" (WORA) philosophy.
• Java's syntax is clean and easy to learn, especially for those familiar with C/C++. It
eliminates complex features like pointers and multiple inheritance.
geeksforgeeks.org+1codejava.net+1
2. Object-Oriented
3. Platform Independent
• Java code is compiled into bytecode, which can run on any platform with a
compatible Java Virtual Machine (JVM), embodying the "Write Once, Run Anywhere"
philosophy.
4. Secure
5. Robust
• Java emphasizes early error checking, runtime checking, and garbage collection,
making it a reliable language for developing error-free applications. scholarhat.com
6. Multithreaded
7. High Performance
• Java provides a set of APIs that make it easy to develop distributed applications,
facilitating file sharing, communication, and more. javatpoint.com
Conclusion
While Java adheres to many OOP principles, its inclusion of primitive data types, static
members, and the use of wrapper classes and the static main method prevent it from
being considered a 100% object-oriented language.
UNIT 2
java
CopyEdit
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // Overloaded
method
}
✅ Example of Overriding:
java
CopyEdit
class Animal {
void sound() { System.out.println("Animal sound"); }
}
• An abstract class is a class that cannot be instantiated (no object can be created
directly).
• It can have abstract methods (without a body) and concrete methods (with body).
• It is used to provide a base for subclasses to implement or override specific
methods.
• Declared using the abstract keyword.
🔹 Key Features:
🔹 Example Program:
java
CopyEdit
// Abstract class
abstract class Animal {
// Abstract method (no body)
abstract void makeSound();
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
🔹 Output:
CopyEdit
Bark!
Sleeping...
🔹 Conclusion:
• Abstract classes are useful when you want to define a common template for all
subclasses.
• They provide partial abstraction and enforce implementation of specific methods
A Singleton class in Java is a class that allows only one instance to be created throughout
the lifetime of the application.
It is used when:
🔹 Example:
java
CopyEdit
class Singleton {
private static Singleton instance;
// Private constructor
private Singleton() {
System.out.println("Singleton Instance Created");
}
🔹 Output:
nginx
CopyEdit
Singleton Instance Created
true
🔹 Conclusion:
Use this for 4 marks (briefly) or expand with explanation and use-cases for 8 marks.
4. explain exception handle in java ? give one example in user define exception?
8marks
✅ Exception Handling in Java with User-Defined Exception (8 Marks)
🔹 Keywords:
java
CopyEdit
// Creating a custom exception class
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
🔹 Output:
pgsql
CopyEdit
Exception Caught: Age must be 18 or above to vote.
🔹 Conclusion:
Can have only abstract methods Can have both abstract and
Methods (before Java 8); from Java 8 onwards, concrete (implemented)
can have default and static methods methods
All variables are public static Can have instance variables with
Variables
final (constants) by default any access modifier
UNIT 3
1. Purpose:
a. Input Stream: Used to read data from a source (e.g., file, keyboard).
b. Output Stream: Used to write data to a destination (e.g., file, console).
2. Direction of Data Flow:
a. Input Stream: Data flows into the program.
b. Output Stream: Data flows out of the program.
3. Base Classes:
a. Input Stream: java.io.InputStream (for byte streams).
b. Output Stream: java.io.OutputStream (for byte streams).
4. Common Methods:
a. Input Stream: read() to read bytes.
b. Output Stream: write() to write bytes.
5. Usage:
a. Input Stream: Used to get input from files, network, etc.
b. Output Stream: Used to send output to files, network, etc.
java
CopyEdit
import java.io.*;
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
input.close();
output.close();
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✅ Explanation:
✅ Summary Points:
✅ Definition:
• To protect shared data from corruption when multiple threads try to read/write it at
the same time.
• To ensure thread safety in multithreaded applications.
✅ Synchronized Method:
• A method declared with the synchronized keyword ensures that only one thread
can execute it at a time for a given object.
Example
class Counter {
int count = 0;
count++;
}
});
});
t1.start(); t2.start();
t1.join(); t2.join();
4.define and explain wrapper class and string class with java program? 8marks
✅ 1. Wrapper Class
Definition:
Wrapper classes in Java are used to wrap primitive data types (int, float, char, etc.)
into objects.
Java provides a wrapper class for each primitive type:
• int → Integer
• char → Character
• float → Float
• etc.
Use Cases:
• Required when working with collections (like ArrayList, HashMap) which store
objects only.
• Enables features like autoboxing (automatic conversion of primitive to object) and
unboxing (object to primitive).
✅ 2. String Class
Definition:
The String class in Java is used to represent sequences of characters.
Strings are immutable, meaning once created, they cannot be changed.
Common Methods:
java
CopyEdit
import java.util.*;
✅ Summary:
5. write a java program to explain the concept of reading and writing from to disk?
8 mraks
🔸 Objective:
To demonstrate how to write data to a file and read it back from disk using Java I/O
streams.
✅ Java Program:
java
CopyEdit
import java.io.*;
try {
// Step 1: Write data to file
FileWriter writer = new FileWriter("sample.txt");
writer.write(data);
writer.close(); // Always close writer
System.out.println("Data written to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " +
e.getMessage());
}
}
}
✅ Explanation:
✅ Output:
pgsql
CopyEdit
Data written to file successfully.
Data read from file: This is a file writing and reading example.
✅ Summary:
2) write class
✅ Introduction:
In Java, Reader and Writer classes are part of the java.io package. They are used for
handling character streams, i.e., reading and writing text data (not binary).
🔹 1. Reader Class
Common Subclasses:
🔹 2. Writer Class
Common Subclasses:
🔹 Example:
java
CopyEdit
import java.io.*;
✅ Summary Table:
Example
Reading text files Writing text files
Uses
🔹 Definition:
Multithreading is a feature in Java that allows the execution of two or more threads
concurrently within a program.
Each thread is a lightweight, independent path of execution, running within a single
process.
🔹 Key Points:
🔹 Example:
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
8. what is mutable and immutable in java also explain string and string buffer class?
8marks
• String objects are immutable, meaning their content cannot be changed once
created.
• Any operation like concat() or replace() returns a new String.
Example:
java
CopyEdit
public class ImmutableExample {
public static void main(String[] args) {
String s = "Java";
s.concat(" Programming");
System.out.println(s); // Output: Java (not changed)
}
}
• StringBuffer is mutable, meaning you can modify the content without creating
a new object.
• Used when you need to manipulate strings frequently (e.g., in loops).
Example:
java
CopyEdit
public class MutableExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb); // Output: Java Programming
}
}
✅ Summary:
UNIT 4
• The <applet> tag is used to embed a Java applet (a small Java program) inside an
HTML page.
• It allows Java programs to run inside web browsers.
Attribute Description
Specifies the name of the Java class file (the applet) to run. Example:
code
code="MyApplet.class"
width Specifies the width of the applet display area in pixels. Example: width="300"
height Specifies the height of the applet display area in pixels. Example: height="200"
Specifies the base URL for the applet code, if not in the same directory as the
codebase
HTML file.
alt Provides an alternative text when the applet cannot be loaded or run.
name Assigns a name to the applet for identification.
Specifies a JAR file containing the applet class and related files to reduce
archive
downloads.
align Specifies the alignment of the applet in the HTML page (e.g., left, right).
• The life cycle of an applet defines the sequence of methods invoked during its
execution.
• There are five main methods that control an applet’s life from loading to unloading.
Method Purpose
init() Called once when the applet is first loaded; used for initialization.
Called after init() and whenever the applet is restarted (e.g., when user returns to
start()
the page).
paint(Graphi
Called whenever the applet needs to redraw itself. Used for displaying graphics/text.
cs g)
Called when the applet is no longer visible or user leaves the page; used to pause
stop()
activities.
destroy() Called when the applet is being removed from memory; used for cleanup.
scss
CopyEdit
init() → start() → paint() → stop() → destroy()
java
CopyEdit
import java.applet.Applet;
import java.awt.Graphics;
✅ Summary:
• The applet life cycle ensures proper initialization, running, pausing, and cleanup.
• Each method plays a specific role in managing the applet’s state.
• Understanding this helps in writing efficient applets.
What is JDBC?
• JDBC (Java Database Connectivity) is an API in Java that allows Java programs to
connect and interact with databases.
• It provides methods to connect to a database, execute SQL queries, and retrieve
results.
• JDBC makes Java applications database-independent, allowing them to work with
different databases using standard interfaces.
✅ What is ServerSocket?
• ServerSocket is a Java class used to create a server that listens for client
connection requests over the network.
• It waits for clients to connect and establishes a communication link.
• Commonly used in network programming for TCP connections.
✅ How it works:
java
CopyEdit
import java.net.*;
import java.io.*;
// Close connections
input.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
✅ Summary:
1. Platform Dependent:
AWT components are heavyweight; they rely on the native OS GUI components.
2. Components:
Provides basic GUI elements like Button, Label, TextField, Frame, Checkbox,
etc.
3. Layout Managers:
Helps arrange components automatically using managers like FlowLayout,
BorderLayout, GridLayout.
4. Package:
AWT is part of the java.awt package in Java.
🔹 Example Code:
java
CopyEdit
Frame f = new Frame("AWT Frame");
Label l = new Label("Hello AWT");
f.add(l);
f.setSize(300, 200);
f.setVisible(true);
UNIT 5
🔹 1. Definition:
Interface Description
Ordered collection (allows duplicates). Example: ArrayList,
List
LinkedList
Set Unordered collection (no duplicates). Example: HashSet, TreeSet
Queue For holding elements before processing. Example: PriorityQueue
Map Stores key-value pairs. Example: HashMap, TreeMap
java
CopyEdit
import java.util.*;
Output:
mathematica
CopyEdit
Java
Python
C++
✅ Summary:
✅ 1. Introduction
java
CopyEdit
import java.util.*;
✅ 4. Output:
yaml
CopyEdit
Keys in the HashMap:
1
2
3
✅ Summary:
✅ 1. Definition:
• The Event Delegation Model is a design pattern used in Java's AWT and Swing to
handle events efficiently.
• Instead of each component handling its own events, events are delegated to a
single event listener.
• The listener is registered with a source component and listens for specific events
(like mouse clicks, key presses).
• Event Source: The GUI component (e.g., Button) that generates an event.
• Event Object: Contains information about the event (like which button was
clicked).
• Event Listener: An object that implements a specific listener interface (e.g.,
ActionListener).
• When an event occurs, the source notifies the registered listener by calling its
callback method (e.g., actionPerformed()).
✅ 3. Advantages of EDM:
✅ 4. Example:
java
CopyEdit
import java.awt.*;
import java.awt.event.*;
public EDMExample() {
b = new Button("Click Me");
b.setBounds(50, 100, 80, 30);
add(b);
setSize(200, 200);
setLayout(null);
setVisible(true);
}
• The Event Delegation Model delegates event handling from GUI components to
listener objects.
• It improves performance and code organization.
• Widely used in Java GUI programming with AWT and Swing.
4.explain with code the concept of genric classes & method ? 8marks
• Generics enable classes and methods to operate on objects of various types while
providing compile-time type safety.
• Avoids casting and ClassCastException at runtime.
• Uses type parameters (like <T>) to specify the data type.
✅ 2. Generic Class
✅ 3. Generic Method
Usage Example:
java
CopyEdit
Box<Integer> intBox = new Box<>();
intBox.setItem(10);
System.out.println(intBox.getItem()); // Output: 10
1. Hashtable:
2. HashSet:
1) hashtable
2)treeset
3)arraylist
4)linkedlist
1. Hashtable
2. TreeSet
3. ArrayList
4. LinkedList