0% found this document useful (0 votes)
3 views

Java

The document covers various concepts in Java programming, including method overloading, constructor overloading, method overriding, inheritance types, and data types. It provides code examples and explanations for each concept, illustrating how they work in practice. Additionally, it discusses user-defined packages, file I/O streams, and the use of ArrayLists, along with exception handling techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java

The document covers various concepts in Java programming, including method overloading, constructor overloading, method overriding, inheritance types, and data types. It provides code examples and explanations for each concept, illustrating how they work in practice. Additionally, it discusses user-defined packages, file I/O streams, and the use of ArrayLists, along with exception handling techniques.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

### **Lab Internal 1**

---

### **1. Method Overloading**

**Theory**:

Method overloading allows a class to have **multiple methods with the


same name** but **different parameters** (number, type, or order). It
enables **compile-time polymorphism**, where the correct method is
selected based on the arguments passed during compilation.

- **Rules**:

1. Methods must have the same name.

2. Parameters must differ in type, number, or order.

3. Return type can be the same or different (return type alone cannot
differentiate overloaded methods).

**Program**:

```java

class Calculator {

// Method 1: Adds two integers

int add(int a, int b) {

return a + b;

// Method 2: Adds three integers (different number of parameters)

int add(int a, int b, int c) {

return a + b + c;

// Method 3: Adds two doubles (different parameter type)

double add(double a, double b) {


return a + b;

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println(calc.add(2, 3)); // 5 (calls Method 1)

System.out.println(calc.add(2, 3, 4)); // 9 (calls Method 2)

System.out.println(calc.add(2.5, 3.5)); // 6.0 (calls Method 3)

```

**Explanation**:

- The `add()` method is overloaded with different parameter lists.

- The compiler selects the appropriate method based on the arguments


passed.

---

### **2. Constructor Overloading**

**Theory**:

Constructors can be overloaded to initialize objects in different ways. Each


constructor must have a **unique parameter list**.

- **Use Case**: Initialize objects with default values or user-provided


values.

**Program**:

```java
class Student {

String name;

int age;

// Default constructor (no parameters)

Student() {

name = "Unknown";

age = 18;

// Constructor with one parameter

Student(String name) {

this.name = name;

age = 18;

// Constructor with two parameters

Student(String name, int age) {

this.name = name;

this.age = age;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

public class Main {

public static void main(String[] args) {


Student s1 = new Student();

Student s2 = new Student("Alice");

Student s3 = new Student("Bob", 20);

s1.display(); // Name: Unknown, Age: 18

s2.display(); // Name: Alice, Age: 18

s3.display(); // Name: Bob, Age: 20

```

**Explanation**:

- The `Student` class has three constructors with varying parameters.

- Objects are initialized differently based on the constructor called.

---

### **3. Method Overriding**

**Theory**:

Method overriding occurs when a subclass provides a **specific


implementation** of a method already defined in its superclass. It enables
**runtime polymorphism**.

- **Rules**:

1. Method name, return type, and parameters must match the superclass
method.

2. The `@Override` annotation is optional but recommended for clarity.

**Program**:

```java

class Animal {
void makeSound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

@Override

void makeSound() {

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.makeSound(); // Output: Dog barks (runtime polymorphism)

```

**Explanation**:

- The `Dog` class overrides the `makeSound()` method of `Animal`.

- The JVM determines which method to call at runtime based on the object
type.

---

### **4. Multilevel Inheritance**

**Theory**:
Multilevel inheritance involves a chain of classes where a subclass
becomes the superclass for another class.

- **Example**: `Grandparent → Parent → Child`.

**Program**:

```java

class Grandparent {

void grandparentMethod() {

System.out.println("Grandparent's method");

class Parent extends Grandparent {

void parentMethod() {

System.out.println("Parent's method");

class Child extends Parent {

void childMethod() {

System.out.println("Child's method");

public class Main {

public static void main(String[] args) {

Child child = new Child();

child.grandparentMethod(); // Inherited from Grandparent

child.parentMethod(); // Inherited from Parent


child.childMethod(); // Defined in Child

```

**Explanation**:

- The `Child` class inherits methods from both `Parent` and


`Grandparent`.

---

### **5. Multiple Inheritance (Using Interfaces)**

**Theory**:

Java does not support multiple inheritance with classes (due to the
"diamond problem"). However, it allows a class to implement **multiple
interfaces**.

- **Interface**: A contract with abstract methods (no implementation).

**Program**:

```java

interface Flyable {

void fly();

interface Swimmable {

void swim();

class Duck implements Flyable, Swimmable {

public void fly() {


System.out.println("Duck flies");

public void swim() {

System.out.println("Duck swims");

public class Main {

public static void main(String[] args) {

Duck duck = new Duck();

duck.fly(); // Duck flies

duck.swim(); // Duck swims

```

**Explanation**:

- The `Duck` class implements two interfaces, `Flyable` and


`Swimmable`.

---

### **6. Hierarchical Inheritance**

**Theory**:

Multiple subclasses inherit from a single superclass.

- **Example**: `Animal → Dog`, `Animal → Cat`.

**Program**:
```java

class Animal {

void eat() {

System.out.println("Animal eats");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

class Cat extends Animal {

void meow() {

System.out.println("Cat meows");

public class Main {

public static void main(String[] args) {

Dog dog = new Dog();

Cat cat = new Cat();

dog.eat(); // Inherited from Animal

dog.bark(); // Defined in Dog

cat.eat(); // Inherited from Animal

cat.meow(); // Defined in Cat


}

```

**Explanation**:

- Both `Dog` and `Cat` inherit `eat()` from `Animal` but have their own
unique methods.

---

### **7. `equals()` vs `==`**

**Theory**:

- **`==`**: Compares **memory addresses** (object references).

- **`equals()`**: Compares **content** (overridden in classes like


`String`).

**Program**:

```java

public class Main {

public static void main(String[] args) {

String s1 = "Java";

String s2 = new String("Java");

String s3 = "Java";

System.out.println(s1 == s2); // false (different objects)

System.out.println(s1 == s3); // true (same string pool)

System.out.println(s1.equals(s2)); // true (content matches)

```
**Explanation**:

- `s1` and `s3` point to the same string in the pool, while `s2` is a new
object.

---

### **8. Decimal to Binary Conversion**

**Program**:

```java

public class Main {

public static void main(String[] args) {

int decimal = 10;

String binary = Integer.toBinaryString(decimal);

System.out.println("Binary: " + binary); // 1010

```

**Alternative (Manual Conversion)**:

```java

public class Main {

public static void main(String[] args) {

int decimal = 10;

StringBuilder binary = new StringBuilder();

while (decimal > 0) {

binary.insert(0, decimal % 2);

decimal /= 2;
}

System.out.println("Binary: " + binary); // 1010

```

---

### **9. Java Data Types**

**Theory**:

Java has **primitive** and **non-primitive** data types.

**Primitive Types**:

| Type | Size | Example |

|---------|---------|------------------|

| `byte` | 1 byte | `byte b = 100;` |

| `short` | 2 bytes | `short s = 200;` |

| `int` | 4 bytes | `int i = 1000;` |

| `long` | 8 bytes | `long l = 5000L;`|

| `float` | 4 bytes | `float f = 3.14f;` |

| `double`| 8 bytes | `double d = 3.14;` |

| `char` | 2 bytes | `char c = 'A';` |

| `boolean`| 1 bit | `boolean flag = true;` |

**Program**:

```java

public class Main {

public static void main(String[] args) {


byte b = 100;

short s = 200;

int i = 300;

long l = 400L;

float f = 5.75f;

double d = 19.99;

char c = 'A';

boolean flag = true;

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("int: " + i);

System.out.println("long: " + l);

System.out.println("float: " + f);

System.out.println("double: " + d);

System.out.println("char: " + c);

System.out.println("boolean: " + flag);

```

---

### **10. Types of Variables**

**Theory**:

1. **Local Variable**: Declared inside a method (lives only during method


execution).

2. **Instance Variable**: Declared in a class, outside methods (object-


specific).
3. **Static Variable**: Declared with `static` (class-level, shared across
objects).

**Program**:

```java

class VariablesExample {

static int staticVar = 10; // Static variable

int instanceVar = 20; // Instance variable

void method() {

int localVar = 30; // Local variable

System.out.println("Local variable: " + localVar);

public class Main {

public static void main(String[] args) {

VariablesExample obj1 = new VariablesExample();

VariablesExample obj2 = new VariablesExample();

System.out.println("Static variable: " +


VariablesExample.staticVar); // 10

System.out.println("Instance variable (obj1): " + obj1.instanceVar); //


20

obj1.instanceVar = 50; // Changes only obj1's instanceVar

System.out.println("Instance variable (obj2): " + obj2.instanceVar); //


20
obj1.method(); // Local variable: 30

```

**Explanation**:

- `staticVar` is shared across all objects.

- `instanceVar` is unique to each object.

---

### **11. `this` and `super` Keywords**

**Theory**:

- **`this`**: Refers to the current object (used to resolve name conflicts).

- **`super`**: Refers to the immediate parent class (used to call parent


methods/constructors).

**Program**:

```java

class Parent {

String name = "Parent";

void display() {

System.out.println("Parent's method");

class Child extends Parent {

String name = "Child";


void display() {

System.out.println("Child's method");

void print() {

System.out.println("Child's name: " + this.name); // Child

System.out.println("Parent's name: " + super.name); // Parent

this.display(); // Calls Child's display()

super.display(); // Calls Parent's display()

public class Main {

public static void main(String[] args) {

Child child = new Child();

child.print();

```

**Output**:

```

Child's name: Child

Parent's name: Parent

Child's method

Parent's method

```
---

### **12. Anagram Check**

**Theory**:

Anagrams are words formed by rearranging letters (e.g., "listen" and


"silent").

**Program**:

```java

import java.util.Arrays;

public class Main {

static boolean isAnagram(String s1, String s2) {

// Remove spaces and convert to lowercase

s1 = s1.replaceAll("\\s", "").toLowerCase();

s2 = s2.replaceAll("\\s", "").toLowerCase();

// Check length

if (s1.length() != s2.length()) return false;

// Convert to char arrays and sort

char[] arr1 = s1.toCharArray();

char[] arr2 = s2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

// Compare sorted arrays

return Arrays.equals(arr1, arr2);


}

public static void main(String[] args) {

String s1 = "listen";

String s2 = "silent";

System.out.println(isAnagram(s1, s2)); // true

```

**Explanation**:

- Sorting both strings and comparing the sorted arrays ensures they are
anagrams.

---

### **Lab Internal 2**

---

### **13. User-Defined Packages**

**Theory**:

Packages organize classes into namespaces.

- **Steps**:

1. Declare `package mypackage;` at the top of the class.

2. Save the file in a directory named `mypackage`.

3. Import using `import mypackage.MyClass;`.

**Program**:

1. Create `mypackage/MyClass.java`:
```java

package mypackage;

public class MyClass {

public void display() {

System.out.println("Inside mypackage!");

```

2. Create `Main.java`:

```java

import mypackage.MyClass;

public class Main {

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.display(); // Inside mypackage!

```

**Compilation**:

```

javac -d . mypackage/MyClass.java

javac Main.java

java Main

```

---
### **14. File IO Streams**

**Theory**:

Java uses streams for file I/O:

- **Character Streams**: `FileReader`, `FileWriter` (text files).

- **Byte Streams**: `FileInputStream`, `FileOutputStream` (binary files).

**Program**:

```java

import java.io.*;

public class Main {

public static void main(String[] args) {

// Write to a file

try (FileWriter writer = new FileWriter("test.txt")) {

writer.write("Hello, File IO!");

} catch (IOException e) {

e.printStackTrace();

// Read from a file

try (BufferedReader reader = new BufferedReader(new


FileReader("test.txt"))) {

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line); // Hello, File IO!

} catch (IOException e) {

e.printStackTrace();
}

```

**Explanation**:

- `try-with-resources` ensures streams are closed automatically.

---

### **15. ArrayList**

**Theory**:

`ArrayList` is a resizable array implementation of the `List` interface.

**Program**:

```java

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<>();

// Add elements

list.add("Apple");

list.add("Banana");

list.add(1, "Mango"); // Insert at index 1

// Remove elements

list.remove("Apple");
// Iterate

for (String fruit : list) {

System.out.println(fruit); // Mango, Banana

```

**Common Methods**:

- `add()`, `remove()`, `get()`, `size()`, `contains()`.

---

### **16. Multi-Catch and Nested Try**

**Theory**:

- **Multi-Catch**: Handle multiple exceptions in a single `catch` block.

- **Nested Try**: A `try` block inside another `try` block.

**Program**:

```java

public class Main {

public static void main(String[] args) {

// Multi-Catch

try {

int[] arr = {1};

System.out.println(arr[2]); // Throws
ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {


System.out.println("Exception: " + e);

// Nested Try

try {

try {

int x = 10 / 0; // Throws ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Inner catch");

} catch (Exception e) {

System.out.println("Outer catch");

```

**Output**:

```

Exception: java.lang.ArrayIndexOutOfBoundsException: Index 2 out of


bounds for length 1

Inner catch

```

---

### **17. Multithreading and Thread Priorities**

**Theory**:

- **Thread**: A lightweight sub-process.


- **Priorities**: Range from `1` (MIN_PRIORITY) to `10` (MAX_PRIORITY).

**Program**:

```java

class MyThread extends Thread {

public void run() {

System.out.println("Thread: " + Thread.currentThread().getName());

public class Main {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

t1.setPriority(Thread.MIN_PRIORITY); // 1

t2.setPriority(Thread.MAX_PRIORITY); // 10

t1.start();

t2.start();

```

**Explanation**:

- Higher-priority threads get more CPU time (output order may vary).

---
### **18. Applet Lifecycle and Graphics**

**Theory**:

Applet lifecycle methods:

1. `init()`: Initialization.

2. `start()`: After `init()` or applet is revisited.

3. `paint()`: Draw graphics.

4. `stop()`: When the applet is minimized or closed.

5. `destroy()`: When the browser closes.

**Program**:

```java

import java.applet.Applet;

import java.awt.Graphics;

public class MyApplet extends Applet {

public void init() { System.out.println("init() called"); }

public void start() { System.out.println("start() called"); }

public void paint(Graphics g) { g.drawString("Hello Applet", 50, 50); }

public void stop() { System.out.println("stop() called"); }

public void destroy() { System.out.println("destroy() called"); }

```

**HTML File**:

```html

<applet code="MyApplet.class" width=300 height=300></applet>

```

**Note**: Applets are deprecated in Java 11+.


---

### **19. Font, Color, and GUI Components**

**Program**:

```java

import java.awt.*;

public class Main extends Frame {

Main() {

Label label = new Label("Hello Java!");

label.setFont(new Font("Arial", Font.BOLD, 24));

label.setForeground(Color.RED);

add(label);

setSize(300, 200);

setVisible(true);

public static void main(String[] args) {

new Main();

```

**Explanation**:

- Sets font style, size, and color for a label.

---
### **20. Mouse and Keyboard Events**

**Program**:

```java

import java.awt.*;

import java.awt.event.*;

public class Main extends Frame implements MouseListener, KeyListener {

Main() {

addMouseListener(this);

addKeyListener(this);

setSize(300, 300);

setVisible(true);

public void mouseClicked(MouseEvent e) {

System.out.println("Mouse clicked at (" + e.getX() + ", " + e.getY() +


")");

public void keyPressed(KeyEvent e) {

System.out.println("Key pressed: " + e.getKeyChar());

// Other methods (empty implementations)

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}


public void keyTyped(KeyEvent e) {}

public void keyReleased(KeyEvent e) {}

public static void main(String[] args) {

new Main();

```

---

### **21. Add Two Numbers Using AWT**

**Program**:

```java

import java.awt.*;

import java.awt.event.*;

public class Main extends Frame implements ActionListener {

TextField tf1, tf2;

Button btn;

Label result;

Main() {

tf1 = new TextField(10);

tf2 = new TextField(10);

btn = new Button("Add");

result = new Label("Result: ");

btn.addActionListener(this);
setLayout(new FlowLayout());

add(tf1);

add(tf2);

add(btn);

add(result);

setSize(300, 200);

setVisible(true);

public void actionPerformed(ActionEvent e) {

int num1 = Integer.parseInt(tf1.getText());

int num2 = Integer.parseInt(tf2.getText());

result.setText("Result: " + (num1 + num2));

public static void main(String[] args) {

new Main();

```

**Explanation**:

- Uses `TextField` for input, `Button` to trigger addition, and `Label` to


display the result.

---

### **22. Checkbox, CheckboxGroup, List, Choice**


**Program**:

```java

import java.awt.*;

public class Main extends Frame {

Main() {

// Checkbox (single)

Checkbox cb1 = new Checkbox("Java");

Checkbox cb2 = new Checkbox("Python");

// CheckboxGroup (radio buttons)

CheckboxGroup cg = new CheckboxGroup();

Checkbox male = new Checkbox("Male", cg, false);

Checkbox female = new Checkbox("Female", cg, true);

// List (multiple selection)

List list = new List(3);

list.add("Red");

list.add("Green");

// Choice (dropdown)

Choice choice = new Choice();

choice.add("Apple");

choice.add("Banana");

add(cb1);

add(cb2);

add(male);

add(female);
add(list);

add(choice);

setLayout(new FlowLayout());

setSize(300, 300);

setVisible(true);

public static void main(String[] args) {

new Main();

```

**Explanation**:

- `CheckboxGroup` creates radio buttons.

- `List` allows multiple selections.

- `Choice` creates a dropdown menu.

---

This covers all questions with detailed theory and code. Let me know if
you need further clarification!

You might also like