Java Programming: Essential Concepts and Techniques
Notes Block 1
Question 1: What are the Key Features of Object-Oriented Programming?
Key Features of OOP:
- Encapsulation: Combines data and methods within a class.
- Inheritance: Derives new classes from existing ones.
- Polymorphism: Allows methods to operate differently based on the object.
- Abstraction: Simplifies complex reality by modeling classes appropriate to the problem.
- Classes and Objects: Blueprints (classes) create specific instances (objects).
Question 2: How do Data Abstraction and Encapsulation Relate?
Data Abstraction: Hides complex details, showing only necessary parts.
Encapsulation: Bundles data and methods, restricting access to certain components.
Example:
public class Car {
private String model;
private int speed;
public void accelerate(int increment) {
speed += increment;
}
public void brake(int decrement) {
speed -= decrement;
}
}
Question 3: What is a Class and an Object in Java?
Class: Blueprint for objects.
Object: Instance of a class.
Benefits:
- Modularity: Organized code.
- Reusability: Reusable classes.
- Scalability: Handles large applications.
Creating an Object:
class Dog {
String breed;
Dog(String breed) {
this.breed = breed;
}
}
Dog myDog = new Dog("Labrador");
Question 4: What is Polymorphism?
Polymorphism: One interface, multiple implementations.
Method Overloading: Same method name, different parameters.
class MathOperation {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding: Subclass method overrides superclass method.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Question 5: What is Byte Code and Why is it Important?
Byte Code:
- Platform Independence: Runs on any JVM.
- Security: JVM checks byte code.
- Efficiency: JVM optimizes execution.
Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Question 6: What is JVM? What are its Advantages?
JVM (Java Virtual Machine): Executes Java byte code.
Advantages:
- Platform Independence: Run anywhere with JVM.
- Memory Management: Automatic garbage collection.
- Security: Byte code verification.
- Performance: Just-In-Time (JIT) compilation.
- Multithreading: Supports concurrent execution.
Notes Block 2
Question 1: Explain Constructor Overloading.
Constructor Overloading: Having multiple constructors in a class with different parameters.
Example:
class Box {
int width, height;
Box() {
width = height = 0;
}
Box(int w, int h) {
width = w;
height = h;
}
}
Question 2: What do you Understand by the “this” Keyword?
“this” keyword: Refers to the current instance of the class.
Example:
class Car {
String model;
Car(String model) {
this.model = model;
}
}
Question 3: How are Objects Passed as Parameters in Java?
Passing Objects as Parameters:
class Car {
String model;
Car(String model) {
this.model = model;
}
void displayModel(Car car) {
System.out.println("Model: " + car.model);
}
}
Car myCar = new Car("Tesla");
myCar.displayModel(myCar);
Question 4: Differentiate Constructor and Method Overloading.
Constructor Overloading: Multiple constructors with different parameters.
Method Overloading: Multiple methods with the same name but different parameters.
Example:
class Example {
Example() {}
Example(int x) {}
void display(int x) {}
void display(double x) {}
}
Question 5: Explain the Term “FINALIZE” Statements.
finalize() method: A method called by the garbage collector before destroying an object.
Example:
class Example {
protected void finalize() {
System.out.println("Object is garbage collected");
}
}
Question 6: What is Inheritance?
Inheritance: Mechanism where a new class inherits properties and methods from an existing class.
Forms of Inheritance:
- Single Inheritance: One class inherits from one superclass.
- Multiple Inheritance (through interfaces): One class inherits from multiple interfaces.
- Multilevel Inheritance: A class is derived from another derived class.
- Hierarchical Inheritance: Multiple classes inherit from one superclass.
- Hybrid Inheritance: Combination of two or more types of inheritance.
Advantages:
- Code Reusability: Use existing code for new classes.
- Simplicity: Simplifies the creation and maintenance of code.
- Extensibility: Easier to extend functionalities.
Diagram:
Single Inheritance: Class A -> Class B
Multilevel Inheritance: Class A -> Class B -> Class C
Hierarchical Inheritance: Class A <-> Class B, Class A <-> Class C
Notes Block 3
1. Multithreading in Java
Definition: Multithreading allows concurrent execution of two or more threads for maximum utilization of CPU.
Example:
public class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
Question 2: What is Synchronization?
Synchronization: It controls the access of multiple threads to shared resources to prevent data inconsistency.
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
class MyThread extends Thread {
Table t;
MyThread(Table t) {
this.t = t;
}
public void run() {
t.printTable(5);
}
}
public class TestSync {
public static void main(String[] args) {
Table obj = new Table();
MyThread t1 = new MyThread(obj);
t1.start();
}
}
Question 3: Explain Inter-thread Communication.
Inter-thread Communication: Allows synchronized threads to communicate with each other using wait(), notify(), and notifyAll().
class Chat {
synchronized void Question(String msg) throws InterruptedException {
System.out.println(msg);
wait();
}
synchronized void Answer(String msg) {
System.out.println(msg);
notify();
}
}
public class Test {
public static void main(String[] args) {
Chat c = new Chat();
new Thread(() -> {
try {
c.Question("How are you?");
} catch (InterruptedException e) {}
}).start();
new Thread(() -> {
c.Answer("I am fine");
}).start();
}
}
Question 4: What are Input and Output Stream Classes?
InputStream: Abstract class representing input operations.
- read(): Reads the next byte of data.
- close(): Closes the input stream.
OutputStream: Abstract class representing output operations.
- write(int b): Writes the specified byte.
- flush(): Flushes the output stream, forcing any buffered output bytes to be written out.
Question 5: Write a Program to Write Keyboard Input to a File.
import java.io.*;
import java.util.Scanner;
public class InputToFile {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in);
FileWriter fw = new FileWriter("output.txt")) {
System.out.println("Enter text:");
fw.write(sc.nextLine());
System.out.println("Data written to file.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Notes Block 4
Question 1: What is an Applet?
Applet: A small Java program that runs in a web browser.
Life Cycle of an Applet:
- init(): Initializes the applet.
- start(): Starts the applet execution.
- stop(): Stops the applet execution.
- destroy(): Destroys the applet.
Question 2: How Does Java Handle Events?
Event Handling in Java: Java uses a delegation event model to handle events. An event is an object that describes a state change in a source.
Components of an Event:
- Event Source: The component that generates an event.
- Event Object: Encapsulates the information about the event.
- Event Listener: Handles the event.
Program to capture keyboard event:
import java.awt.event.*;
import java.awt.*;
public class KeyEventDemo extends KeyAdapter {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
public static void main(String[] args) {
Frame f = new Frame("Key Event Example");
f.addKeyListener(new KeyEventDemo());
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
Question 3: Differentiate AWT and Swing Components.
AWT (Abstract Window Toolkit):
- Platform Dependent: Heavyweight components.
- Look and Feel: Native to the operating system.
Swing:
- Platform Independent: Lightweight components.
- Look and Feel: Customizable with a pluggable look and feel.
Question 4: What is a Layout Manager?
Layout Manager: Manages the layout of components in a container.
Flow Layout: Arranges components in a left-to-right flow.
Example:
setLayout(new FlowLayout());
Grid Layout: Arranges components in a grid of cells.
Example:
setLayout(new GridLayout(2, 2));
Question 5: Write the Steps of JDBC for a Dynamic Website.
- Load Driver:
Class.forName("com.mysql.jdbc.Driver");
- Establish Connection:
Connection con = DriverManager.getConnection(url, user, password);
- Create Statement:
Statement stmt = con.createStatement();
- Execute Query:
ResultSet rs = stmt.executeQuery("SELECT * FROM table");
- Process Results: Process the ResultSet.
- Close Connection:
con.close();
Question 7: What is Public Access Specifier?
Public access specifier: Members are accessible from any other class.
Private access specifier: Members are accessible only within the same class.
Question 8: Abstract Class and Polymorphism in Java
An abstract class cannot be instantiated and can have both abstract (no body) and non-abstract methods. It is used for polymorphism by defining common methods in the abstract class and implementing them differently in subclasses.
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.makeSound();
a2.makeSound();
}
}
Question 9: Final Keyword in Java
Final Variable: Cannot be changed once initialized.
Final Method: Cannot be overridden by subclasses.
Final Class: Cannot be subclassed.
final int MAX_VALUE = 100;
final class FinalClass { }
Question 10: Classpath
Classpath specifies locations to find user-defined classes and libraries at runtime.
java -cp .;C:\myfolder\myclasses.jar MyProgram
Question 11: Interface and Implementation
An interface can contain method signatures and constants. A class that implements an interface must provide implementations for all methods.
interface Animal {
void eat();
}
class Dog implements Animal {
public void eat() {
System.out.println("Dog eats bone.");
}
}
Question 12: Finally Block
The finally block executes important code like closing resources, regardless of exceptions.
try {
int data = 25 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught.");
} finally {
System.out.println("Finally block executed.");
}
Question 13: Exception Handling
An exception is an error event during program execution. Handled using try, catch, finally, and throw.
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught.");
}
Question 14: Checked vs. Unchecked Exceptions
Checked: Checked at compile-time (e.g., IOException).
Unchecked: Not checked at compile-time (e.g., ArithmeticException).
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
System.out.println("Exception caught.");
}
Index
Block 1 Notes (Page 1-1)
- Features of OOP vs Procedural Programming
- Data Abstraction vs Encapsulation (Example)
- Class and Object in Java (Advantage and Creation)
- Polymorphism, Method Overloading, and Overriding (Example)
- Byte Code Uses and Importance (Examples)
- JVM (Advantages)
Block 2 Notes (Page 1-3, 1-4)
- Constructor Overloading (Example)
- “this” Keyword Usage (Example)
- Passing Objects as Parameters (Program Example)
- Constructor vs Method Overloading
- “FINALIZE” Statements (Examples)
- Inheritance (Forms, Diagrams, Advantages)
- Public vs Private Access Specifiers (Example)
- Abstract Class and Polymorphism in Java
- “FINAL” Keyword (Examples)
- Classpath Utility (Example)
- Interface in Java, Implementation Interfaces (Examples)
- “FINALLY” Statements (Examples)
- Exception Handling in Java (Code Example)
- Checked vs Unchecked Exceptions
Block 3 Notes (Page 1-5, 1-6)
- Multithreading (Program Example)
- Synchronization and Methods (Program Example)
- Interthread Communication using wait() and notify() (Example)
- Input Stream and Output Stream Classes (Methods)
- Writing Keyboard Input to a File (Program)
- StringBuffer vs String (Uppercase Program)
- StreamTokenizer (Program Example)
Block 4 Notes (Page 1-7)
- Applet Lifecycle (Methods)
- Java Event Handling (Components, Keyboard Event Program)
- AWT vs Swing Components
- Layout Managers (Flow and Grid Layout Examples)
- JDBC Connection Steps for Dynamic Website
- Java RMI Architecture (Diagram)
- Cookies and Session Objects (Usage)
- JavaBean Features
Question 6: How does StringBuffer Differ from a String?
String vs. StringBuffer:
- String: Immutable, cannot be changed after creation.
- StringBuffer: Mutable, can be modified.
Program to print name in uppercase:
import java.util.Scanner;
public class NameToUpper {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter your name:");
System.out.println(sc.nextLine().toUpperCase());
}
}
}
Question 7: Explain the StreamTokenizer with a Program.
StreamTokenizer: Breaks an input stream into tokens for parsing.
Example:
import java.io.*;
public class TokenizerExample {
public static void main(String[] args) throws IOException {
try (FileReader fr = new FileReader("file.txt")) {
StreamTokenizer st = new StreamTokenizer(fr);
while (st.nextToken() != StreamTokenizer.TT_EOF) {
if (st.ttype == StreamTokenizer.TT_WORD)
System.out.println(st.sval);
else if (st.ttype == StreamTokenizer.TT_NUMBER)
System.out.println(st.nval);
}
}
}
}