Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

Java Exam Booklet

Uploaded by

mfaizancse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Java Exam Booklet

Uploaded by

mfaizancse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 204

Scanned by CamScanner

Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Notes on Arrays in Java

### Introduction to Arrays in Java ###

An array is a data structure that allows you to store multiple elements of the same type in a single

variable. It is a container object that holds a fixed number of values of a single type. The length of an

array is established when the array is created, and it cannot be changed.

Key Points about Arrays:

- Arrays are zero-indexed: the first element is stored at index 0.

- The size of an array is fixed once it is created.

- Elements in an array are accessed using their index.

Declaration and Initialization of Arrays


In Java, arrays are declared and initialized as follows:

1. Declaration:

`dataType[] arrayName;`

Example:

`int[] numbers;`

2. Allocation:

`arrayName = new dataType[size];`

Example:

`numbers = new int[5];`

3. Initialization:

`arrayName[index] = value;`

Example:
`numbers[0] = 10;`

Alternatively, you can combine all steps:

`int[] numbers = {10, 20, 30, 40, 50};`

Example 1: Simple Array


public class SimpleArray {

public static void main(String[] args) {

// Declare and initialize an array

int[] numbers = {1, 2, 3, 4, 5};

// Access elements in the array

for (int i = 0; i < numbers.length; i++) {

System.out.println("Element at index " + i + ": " + numbers[i]);

Multi-dimensional Arrays
Java supports multi-dimensional arrays, which are arrays of arrays.

The most common type is the two-dimensional array, often used to represent a matrix.

Declaration:

`dataType[][] arrayName = new dataType[rows][columns];`

Example:

`int[][] matrix = new int[3][3];`

Initialization:
`matrix[0][0] = 1; matrix[0][1] = 2;`

Alternatively:

`int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};`

Example 2: Multi-dimensional Array


public class MultiDimensionalArray {

public static void main(String[] args) {

// Declare and initialize a 2D array

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Access elements in the 2D array

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

Common Operations on Arrays


1. Finding the length of an array:

`arrayName.length`
Example:

`System.out.println("Length: " + numbers.length);`

2. Copying an array:

Using System.arraycopy:

`System.arraycopy(sourceArray, 0, destArray, 0, length);`

3. Sorting an array:

`Arrays.sort(arrayName);`

4. Searching for an element:

Using linear search or binary search:

`Arrays.binarySearch(arrayName, key);`
Notes on Strings in Java

### Introduction to Strings in Java ###

In Java, strings are objects that represent sequences of characters. The `String` class is used to

create and manipulate strings. Strings are immutable, meaning once a string is created, its value

cannot be changed.

Key Points about Strings:

- Strings are immutable.

- They are created using string literals or the `new` keyword.

- The `String` class provides numerous methods for string manipulation.

Declaration and Initialization of Strings


1. Using string literals:

`String str = "Hello World";`

2. Using the `new` keyword:

`String str = new String("Hello World");`

3. String concatenation:

`String fullName = firstName + " " + lastName;`

4. Using `String.format`:

`String message = String.format("%s is %d years old", name, age);`

Example 1: Basic String Operations


public class StringExample {

public static void main(String[] args) {


String str = "Hello World";

// String length

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

// Accessing characters

System.out.println("Character at index 0: " + str.charAt(0));

// Substring

System.out.println("Substring (0, 5): " + str.substring(0, 5));

// String concatenation

String greeting = str + "!";

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

Common String Methods


1. `length()`: Returns the length of the string.

2. `charAt(index)`: Returns the character at the specified index.

3. `substring(startIndex, endIndex)`: Extracts a substring from the string.

4. `indexOf(char/substring)`: Returns the index of the first occurrence of the specified character or

substring.

5. `toUpperCase()` and `toLowerCase()`: Converts the string to upper or lower case.

6. `trim()`: Removes leading and trailing whitespaces.

7. `equals()`: Compares two strings for equality.

8. `equalsIgnoreCase()`: Compares two strings, ignoring case differences.


9. `replace(oldChar, newChar)`: Replaces occurrences of a character with another character.

10. `split(delimiter)`: Splits the string into an array based on the given delimiter.

Example 2: Advanced String Manipulation


import java.util.Arrays;

public class AdvancedStringExample {

public static void main(String[] args) {

String sentence = "Java is fun";

// Convert to uppercase

System.out.println("Uppercase: " + sentence.toUpperCase());

// Replace characters

System.out.println("Replaced: " + sentence.replace("fun", "awesome"));

// Split into words

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

System.out.println("Words: " + Arrays.toString(words));

// Check equality

System.out.println("Equals 'Java is fun': " + sentence.equals("Java is

fun"));

StringBuilder and StringBuffer


Strings in Java are immutable, so every modification creates a new string object. For scenarios
where frequent modifications are needed, `StringBuilder` and `StringBuffer` are used:

1. `StringBuilder`: Non-synchronized, faster, used in single-threaded environments.

2. `StringBuffer`: Synchronized, thread-safe, slightly slower.

Example with StringBuilder:

`StringBuilder sb = new StringBuilder("Hello");`

`sb.append(" World");`

`System.out.println(sb.toString());`
Notes on Control Statements in Java

### Introduction to Control Statements in Java ###

Control statements are used to alter the flow of execution in a program. They allow the program to

take decisions, repeat actions, or jump to specific parts of the code. Java provides three types of

control statements:

1. **Decision-Making Statements**

- `if`, `if-else`, `if-else-if`, `switch`

2. **Looping Statements**

- `for`, `while`, `do-while`

3. **Jump Statements**

- `break`, `continue`, `return`

Decision-Making Statements
1. **if Statement**:

Executes a block of code if the condition is true.

Example:

```java

if (a > b) {

System.out.println("a is greater than b");

```

2. **if-else Statement**:
Executes one block if the condition is true, another if false.

Example:

```java

if (a > b) {

System.out.println("a is greater");

} else {

System.out.println("b is greater");

```

3. **switch Statement**:

Selects one of many blocks of code to execute.

Example:

```java

switch (day) {

case 1: System.out.println("Monday"); break;

case 2: System.out.println("Tuesday"); break;

default: System.out.println("Invalid day");

```

Looping Statements
1. **for Loop**:

Executes a block of code a fixed number of times.

Example:

```java

for (int i = 0; i < 5; i++) {


System.out.println(i);

```

2. **while Loop**:

Executes a block of code as long as the condition is true.

Example:

```java

int i = 0;

while (i < 5) {

System.out.println(i);

i++;

```

3. **do-while Loop**:

Executes a block of code at least once, then repeats as long as the condition is true.

Example:

```java

int i = 0;

do {

System.out.println(i);

i++;

} while (i < 5);

```

Example 1: Combining Decision-Making and Loops


public class ControlStatementsExample {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) {

System.out.println(i + " is even");

} else {

System.out.println(i + " is odd");

Jump Statements
1. **break Statement**:

Terminates the loop or switch statement.

Example:

```java

for (int i = 0; i < 10; i++) {

if (i == 5) {

break;

System.out.println(i);

```

2. **continue Statement**:

Skips the current iteration and continues with the next.


Example:

```java

for (int i = 0; i < 10; i++) {

if (i == 5) {

continue;

System.out.println(i);

```

3. **return Statement**:

Exits from the current method and optionally returns a value.

Example:

```java

public int add(int a, int b) {

return a + b;

```
Java Notes - Theory and Code Examples

Abstraction in Java

1. What is Abstraction?

Abstraction is a process of hiding the implementation details and showing only the essential features

of an object.

- Focus on "what an object does" instead of "how it does it."

- It is achieved in Java using abstract classes and interfaces.

2. Why Use Abstraction?

- To reduce code complexity and increase code reusability.

- Helps in designing systems where implementation details can change without affecting the code

that uses the abstraction.

3. Abstract Classes

- An abstract class is declared using the `abstract` keyword.

- It can have both abstract (without implementation) and concrete (with implementation) methods.

- Example:

```java

abstract class Vehicle {

abstract void startEngine();

void stopEngine() {

System.out.println("Engine stopped.");

Page 1
Java Notes - Theory and Code Examples

class Car extends Vehicle {

void startEngine() {

System.out.println("Car engine started.");

public class Main {

public static void main(String[] args) {

Vehicle myCar = new Car();

myCar.startEngine();

myCar.stopEngine();

```

4. Interfaces

- An interface is a reference type in Java, similar to a class, but it can contain only abstract methods

(prior to Java 8).

- Interfaces represent the purest form of abstraction.

- Example:

```java

interface Animal {

void sound();

class Dog implements Animal {

public void sound() {

Page 2
Java Notes - Theory and Code Examples

System.out.println("Barks");

public class Main {

public static void main(String[] args) {

Animal dog = new Dog();

dog.sound();

```

5. Key Differences Between Abstract Classes and Interfaces

- Abstract classes can have constructors, but interfaces cannot.

- A class can implement multiple interfaces but can extend only one abstract class.

6. Real-world Example

- Abstract Class Example:

```java

abstract class Shape {

abstract void draw();

class Circle extends Shape {

void draw() {

System.out.println("Drawing Circle");

Page 3
Java Notes - Theory and Code Examples

class Rectangle extends Shape {

void draw() {

System.out.println("Drawing Rectangle");

public class Main {

public static void main(String[] args) {

Shape s1 = new Circle();

Shape s2 = new Rectangle();

s1.draw();

s2.draw();

```

- Interface Example:

```java

interface Payment {

void pay();

class CreditCardPayment implements Payment {

public void pay() {

System.out.println("Payment using Credit Card.");

Page 4
Java Notes - Theory and Code Examples

class PayPalPayment implements Payment {

public void pay() {

System.out.println("Payment using PayPal.");

public class Main {

public static void main(String[] args) {

Payment p1 = new CreditCardPayment();

Payment p2 = new PayPalPayment();

p1.pay();

p2.pay();

```

Summary:

- Abstraction is a key OOP principle that simplifies complex systems.

- Java provides abstract classes and interfaces to implement abstraction.

Page 5
Java Notes - Theory and Code Examples

Inheritance in Java

1. What is Inheritance?

Inheritance is one of the key principles of Object-Oriented Programming (OOP) that allows a class to

inherit properties and methods from another class.

- The class that is inherited is called the **parent class** or **superclass**.

- The class that inherits is called the **child class** or **subclass**.

2. Why Use Inheritance?

- Code Reusability: Common code can be defined in the parent class and reused by child classes.

- Extensibility: New functionality can be added to an existing class without modifying it.

3. How to Implement Inheritance?

Inheritance is implemented using the `extends` keyword in Java.

Example:

```java

class Animal {

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

Page 1
Java Notes - Theory and Code Examples

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.eat(); // Inherited method

myDog.bark(); // Child class method

```

4. Types of Inheritance

- **Single Inheritance**: A child class inherits from one parent class.

- **Multilevel Inheritance**: A class inherits from another class, which in turn inherits from another

class.

```java

class Vehicle {

void start() {

System.out.println("Vehicle started.");

class Car extends Vehicle {

void drive() {

System.out.println("Car is being driven.");

Page 2
Java Notes - Theory and Code Examples

class ElectricCar extends Car {

void charge() {

System.out.println("Electric Car charging.");

public class Main {

public static void main(String[] args) {

ElectricCar myCar = new ElectricCar();

myCar.start();

myCar.drive();

myCar.charge();

```

5. Overriding in Inheritance

Child classes can modify (override) methods defined in the parent class.

Example:

```java

class Animal {

void sound() {

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

Page 3
Java Notes - Theory and Code Examples

class Cat extends Animal {

@Override

void sound() {

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

public class Main {

public static void main(String[] args) {

Animal myCat = new Cat();

myCat.sound(); // Outputs: "Cat meows."

```

6. The `super` Keyword

The `super` keyword refers to the parent class and is used to:

- Call the parent class's constructor.

- Access the parent class's methods or variables.

Example:

```java

class Animal {

String name = "Animal";

void sound() {

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

Page 4
Java Notes - Theory and Code Examples

class Dog extends Animal {

String name = "Dog";

void sound() {

super.sound(); // Call parent class method

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

void displayNames() {

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

System.out.println("Child name: " + name);

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.sound();

myDog.displayNames();

```

7. Final Keyword in Inheritance

- A `final` class cannot be extended by any other class.

- A `final` method cannot be overridden by subclasses.

Page 5
Java Notes - Theory and Code Examples

8. Real-world Example

```java

class Employee {

String name;

double salary;

void displayDetails() {

System.out.println("Name: " + name + ", Salary: " + salary);

class Manager extends Employee {

String department;

void displayDetails() {

super.displayDetails();

System.out.println("Department: " + department);

public class Main {

public static void main(String[] args) {

Manager mgr = new Manager();

mgr.name = "Alice";

mgr.salary = 75000;

mgr.department = "IT";

mgr.displayDetails();

Page 6
Java Notes - Theory and Code Examples

```

Summary:

- Inheritance helps in creating a hierarchical relationship between classes.

- Enables code reusability and makes the code easier to maintain and extend.

Page 7
Polymorphism in Java

Polymorphism in Java refers to the ability of a single interface or method to behave differently in

different contexts.

It allows objects to be treated as instances of their parent class rather than their actual class. This

promotes flexibility,

reusability, and maintainability in code.

Polymorphism is a core concept of Object-Oriented Programming (OOP) and is classified into two

main types:

1. Compile-Time Polymorphism (Static Binding)

2. Run-Time Polymorphism (Dynamic Binding)

1. Compile-Time Polymorphism

Also known as method overloading, Compile-Time Polymorphism occurs when multiple methods in

the same class share the same name but differ in:

- The number of parameters

- The type of parameters

- The order of parameters

Method overloading is resolved during compilation.

Example:

class Calculator {
// Method with two integer parameters

int add(int a, int b) {

return a + b;

// Method with three integer parameters

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

return a + b + c;

// Method with two double parameters

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("Sum of two integers: " + calc.add(10, 20));

System.out.println("Sum of three integers: " + calc.add(10, 20, 30));

System.out.println("Sum of two doubles: " + calc.add(10.5, 20.5));

2. Run-Time Polymorphism
Also known as method overriding, Run-Time Polymorphism occurs when a subclass provides a

specific implementation of a method that is already defined in its superclass.

Key Points:

- The method in the subclass must have the same name, return type, and parameters as the

method in the superclass.

- Method overriding is resolved during runtime.

Example:

class Animal {

void sound() {

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

class Dog extends Animal {

@Override

void sound() {

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

class Cat extends Animal {

@Override

void sound() {

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

public class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal();

Animal myDog = new Dog();

Animal myCat = new Cat();

myAnimal.sound();

myDog.sound();

myCat.sound();

Benefits of Polymorphism

1. Code Reusability: Common behavior can be reused in different parts of the application.

2. Flexibility: Code can be extended with minimal modifications.

3. Maintainability: Code is easier to read and maintain.

Polymorphism allows us to achieve clean and modular code.


Multithreading in Java

Multithreading in Java is a process of executing multiple threads simultaneously to achieve

multitasking.

A thread is a lightweight subprocess, the smallest unit of processing. Java provides built-in support

for

multithreading using the `Thread` class and the `Runnable` interface.

Multithreading enables efficient utilization of CPU resources, allowing multiple tasks to run

concurrently within a program.

Key Concepts of Multithreading

1. **Thread**: A thread is a lightweight subprocess that runs independently.

2. **Main Thread**: Every Java program starts with the main thread, which is created by the JVM.

3. **Creating Threads**: Threads can be created in two ways:

- By extending the `Thread` class

- By implementing the `Runnable` interface

4. **Lifecycle of a Thread**: A thread goes through the following states: New, Runnable, Running,

Blocked/Waiting, and Terminated.

1. Extending the Thread Class

To create a thread by extending the `Thread` class, you need to override its `run()` method, which

defines the task that the thread will execute.

Example:
class MyThread extends Thread {

public void run() {

System.out.println("Thread is running...");

public class Main {

public static void main(String[] args) {

MyThread thread = new MyThread();

thread.start(); // Starts the thread

2. Implementing the Runnable Interface

To create a thread by implementing the `Runnable` interface, you need to override its `run()` method

and pass an instance of the class to a `Thread` object.

Example:

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread is running...");

}
public class Main {

public static void main(String[] args) {

MyRunnable runnable = new MyRunnable();

Thread thread = new Thread(runnable);

thread.start(); // Starts the thread

Important Thread Methods

1. `start()`: Starts the execution of the thread.

2. `run()`: Contains the code to be executed by the thread.

3. `sleep(milliseconds)`: Causes the thread to pause for a specified time.

4. `join()`: Waits for a thread to finish its execution.

5. `isAlive()`: Checks if a thread is still running.

6. `setPriority(priority)`: Sets the priority of the thread.

7. `getName() / setName(name)`: Gets or sets the thread's name.

Example with Multiple Threads

Here is an example demonstrating multiple threads running concurrently.

class MyThread extends Thread {

private String threadName;

MyThread(String name) {

threadName = name;

}
public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(threadName + " - Count: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println("Thread interrupted: " + e);

public class Main {

public static void main(String[] args) {

MyThread thread1 = new MyThread("Thread 1");

MyThread thread2 = new MyThread("Thread 2");

thread1.start();

thread2.start();

Benefits of Multithreading

1. Improved Performance: Threads allow efficient use of CPU resources.

2. Concurrent Execution: Multiple tasks can run simultaneously, reducing execution time.
3. Simplified Model: Multithreading simplifies program structure for tasks like animations,

background tasks, etc.

4. Resource Sharing: Threads of the same process share resources, making inter-thread

communication easier.
File Handling in Java

File Handling in Java allows developers to create, read, write, and manipulate files in a structured

way.

Java provides the `java.io` and `java.nio` packages to work with files.

File handling is essential for applications that require persistent storage, configuration management,

or interaction with external systems.

Key Classes for File Handling

1. **File**: Represents a file or directory path in the file system.

2. **FileReader**: Used to read data from a file (character stream).

3. **FileWriter**: Used to write data to a file (character stream).

4. **BufferedReader**: Reads text from an input stream efficiently.

5. **BufferedWriter**: Writes text to an output stream efficiently.

6. **Scanner**: Reads data from a file using delimiters like spaces or newlines.

7. **PrintWriter**: Writes formatted text to a file.

1. Creating a File

To create a file, use the `File` class's `createNewFile()` method. It returns `true` if the file is created

successfully.

Example:

import java.io.File;
import java.io.IOException;

public class Main {

public static void main(String[] args) {

try {

File myFile = new File("example.txt");

if (myFile.createNewFile()) {

System.out.println("File created: " + myFile.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

2. Writing to a File

To write to a file, use the `FileWriter` class. You can write data character by character or as a string.

Example:

import java.io.FileWriter;

import java.io.IOException;
public class Main {

public static void main(String[] args) {

try {

FileWriter writer = new FileWriter("example.txt");

writer.write("Hello, world!\nThis is a test file.");

writer.close();

System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();

3. Reading from a File

To read data from a file, use the `Scanner` or `BufferedReader` class. You can read the file line by

line or character by character.

Example:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


try {

File myFile = new File("example.txt");

Scanner scanner = new Scanner(myFile);

while (scanner.hasNextLine()) {

String data = scanner.nextLine();

System.out.println(data);

scanner.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

4. Deleting a File

To delete a file, use the `delete()` method of the `File` class. It returns `true` if the file is successfully

deleted.

Example:

import java.io.File;

public class Main {

public static void main(String[] args) {

File myFile = new File("example.txt");


if (myFile.delete()) {

System.out.println("Deleted the file: " + myFile.getName());

} else {

System.out.println("Failed to delete the file.");

Benefits of File Handling

1. Data Persistence: Enables long-term storage of data.

2. File Manipulation: Supports operations like reading, writing, renaming, and deleting files.

3. Streamlined Input/Output: Makes it easier to manage input and output for applications.

4. Configuration Management: Allows external configuration files for flexibility in programs.


Swing Components in Java

Swing is a part of Java Foundation Classes (JFC) that is used to create window-based applications.

It is built on

top of the AWT (Abstract Window Toolkit) API and entirely written in Java, making it

platform-independent.

Swing provides a richer set of components and is more flexible compared to AWT.

1. **JFrame**:

- JFrame is the top-level container for a Swing application.

- It provides a window that can contain other Swing components.

2. **JPanel**:

- JPanel is a generic container for grouping components together.

3. **JLabel**:

- JLabel is used to display a short string or an image icon.

4. **JButton**:

- JButton is a push button used to perform actions when clicked.

5. **JTextField**:

- JTextField allows users to input a single line of text.

6. **JTextArea**:
- JTextArea allows users to input multiple lines of text.

7. **JCheckBox**:

- JCheckBox is a component that represents a check box that can be selected or deselected.

8. **JRadioButton**:

- JRadioButton is used to create radio buttons, which are part of a group where only one button

can be selected.

9. **JComboBox**:

- JComboBox provides a dropdown list of items to choose from.

10. **JList**:

- JList is used to display a list of items.

11. **JTable**:

- JTable is used to display tabular data.

12. **JMenu and JMenuBar**:

- JMenu is used to create menus, while JMenuBar acts as the menu bar container.

13. **JScrollBar**:

- JScrollBar provides a scrollable view of components.

Example Code: Creating a Simple Swing Application with JFrame, JLabel, JButton, and

JTextField
import javax.swing.*;

import java.awt.event.*;

public class SwingExample {

public static void main(String[] args) {

// Create a new JFrame

JFrame frame = new JFrame("Swing Example");

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(null);

// Create a JLabel

JLabel label = new JLabel("Enter your name:");

label.setBounds(50, 50, 150, 30);

frame.add(label);

// Create a JTextField

JTextField textField = new JTextField();

textField.setBounds(200, 50, 150, 30);

frame.add(textField);

// Create a JButton

JButton button = new JButton("Submit");

button.setBounds(150, 150, 100, 30);

frame.add(button);
// Add ActionListener to the button

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

String name = textField.getText();

JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");

});

// Make the frame visible

frame.setVisible(true);

Swing is a powerful GUI library in Java that provides the tools to create modern, cross-platform

graphical applications.

Its flexibility and extensibility make it a popular choice for desktop application development.
PRIME NUMBERS. Scanner scanner = new Scanner(System.in);
import java.util.Scanner; System.out.print("Enter the starting number (m): ");
int m = scanner.nextInt();
public class PrimeNumbers {
public static void main(String[] args) { System.out.print("Enter the ending number (n): ");
Scanner scanner = new Scanner(System.in); int n = scanner.nextInt();
System.out.print("Enter the starting number (m): "); for (int i = m; i <= n; i++) {
int m = scanner.nextInt(); int num = i;
int sum = 0;
System.out.print("Enter the ending number (n): "); int digits = String.valueOf(i).length();
int n = scanner.nextInt();
while (num != 0) {
for (int i = m; i <= n; i++) { int remainder = num % 10;
if (i <= 1) continue; sum += Math.pow(remainder, digits);
boolean isPrime = true; num /= 10;
}
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) { if (sum == i) {
isPrime = false; System.out.println(i);
break; }
} }
}
scanner.close();
if (isPrime) { }
System.out.println(i); }
}
}
Calculate the Volume of a Sphere
import java.util.*;
scanner.close();
} import java.math.*;
}
class Main
PERFECT NUMBERS.
{
import java.util.Scanner;
public static void main(String args[])
public class PerfectNumbers { {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); Scanner abc=new Scanner(System.in);
float r=abc.nextFloat();
System.out.print("Enter the starting number (m): ");
int m = scanner.nextInt(); double v=(4f/3f)* Math.PI*Math.pow(r,3);
System.out.print(String.format("%.2f",v));
System.out.print("Enter the ending number (n): ");
int n = scanner.nextInt(); }

for (int i = m; i <= n; i++) { }


int sum = 0; read size of two dimensional array (A) as M,N. read
for (int j = 1; j <= i / 2; j++) {
(M-1)*(N-1) elements e.
if (i % j == 0) { import java.util.Scanner;
sum += j;
} public class two_d_array_sum {
} public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (sum == i) {
System.out.println(i); System.out.print("Enter the number of rows (M): ");
} int M = scanner.nextInt();
} System.out.print("Enter the number of columns (N): ");
int N = scanner.nextInt();
scanner.close();
} int[][] array = new int[M][N];
} System.out.println("Enter " + (M - 1) * (N - 1) + " elements:");
ARMSTRONG NUMBERS. for (int i = 0; i < M - 1; i++) {
import java.util.Scanner; for (int j = 0; j < N - 1; j++) {
array[i][j] = scanner.nextInt();
public class ArmstrongNumbers { }
public static void main(String[] args) { }
public static int getMaxFrequency(int[] ages) {
for (int i = 0; i < M - 1; i++) { HashMap<Integer, Integer> ageFrequency = new
int rowSum = 0; HashMap<>();
for (int j = 0; j < N - 1; j++) { for (int age : ages) {
rowSum += array[i][j]; ageFrequency.put(age, ageFrequency.getOrDefault(age, 0)
} + 1);
array[i][N - 1] = rowSum; }
}
int maxFrequency = 0;
for (int j = 0; j < N; j++) { for (int freq : ageFrequency.values()) {
int colSum = 0; if (freq > maxFrequency) {
for (int i = 0; i < M - 1; i++) { maxFrequency = freq;
colSum += array[i][j]; }
} }
array[M - 1][j] = colSum; return maxFrequency;
} }
}
int totalSum = 0;
for (int i = 0; i < M; i++) { write a java program to calculate the following series
totalSum += array[i][N - 1]; 1+x+x2/2!+x3/3!+………..+xn/n!
}
array[M - 1][N - 1] = totalSum; import java.util.Scanner;

System.out.println("Resultant Matrix:"); public class SeriesCalculation {


for (int i = 0; i < M; i++) { public static void main(String[] args) {
for (int j = 0; j < N; j++) { Scanner scanner = new Scanner(System.in);
System.out.print(array[i][j] + " ");
} System.out.print("Enter the value of x: ");
System.out.println(); double x = scanner.nextDouble();
} System.out.print("Enter the value of n: ");
} int n = scanner.nextInt();
}
double result = calculateSeries(x, n);
write a java program to print 1 if maximum number of times System.out.println("The result of the series is: " + result);
repeated girls age is equal to the maximum number of times }
repeated boys , other wise print 0.
public static double calculateSeries(double x, int n) {
import java.util.HashMap; double sum = 1; // Start with the first term (1)
import java.util.Scanner; double term = 1; // This will store each term in the series

public class repeated_ages { for (int i = 1; i <= n; i++) {


public static void main(String[] args) { term *= x / i; // Update the term (x^i / i!)
Scanner scanner = new Scanner(System.in); sum += term; // Add the term to the sum
}
System.out.print("Enter the number of girls (N): ");
int N = scanner.nextInt(); return sum;
System.out.print("Enter the number of boys (M): "); }
int M = scanner.nextInt(); }

int[] girlsAges = new int[N]; b) write a java program to implement access specifiers with the
int[] boysAges = new int[M]; help of packages.

System.out.println("Enter the ages of girls:"); Step 1: Create the com.company package with a class Employee.
for (int i = 0; i < N; i++) {
girlsAges[i] = scanner.nextInt(); package com.company;
}
public class Employee {
System.out.println("Enter the ages of boys:"); public int employeeId;
for (int i = 0; i < M; i++) { public String employeeName;
boysAges[i] = scanner.nextInt();
} private double salary;

int maxGirlsFrequency = getMaxFrequency(girlsAges); protected String department;


int maxBoysFrequency = getMaxFrequency(boysAges);
String address;
System.out.println(maxGirlsFrequency ==
maxBoysFrequency ? 1 : 0); public Employee(int employeeId, String employeeName, double
} salary, String department, String address) {
this.employeeId = employeeId;
this.employeeName = employeeName;
this.salary = salary; class PerfectNumber {
this.department = department; public boolean isPerfect(int num) {
this.address = address; int sum = 0;
} for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
public double getSalary() { sum += i;
return salary; }
} }
return sum == num;
public void displayEmployeeDetails() { }
System.out.println("Employee ID: " + employeeId);
System.out.println("Employee Name: " + employeeName); public void printPerfectNumbers(int start, int end) {
System.out.println("Department: " + department); System.out.println("Perfect numbers in the range " + start + "
System.out.println("Address: " + address); to " + end + ":");
} for (int i = start; i <= end; i++) {
} if (isPerfect(i)) {
Step 2: Create another class EmployeeTest in the com.test System.out.print(i + " ");
package to test the Employee class. }
java }
Copy code System.out.println();
}
package com.test; }

import com.company.Employee; public class PrimePerfectTest {


public static void main(String[] args) {
public class EmployeeTest { PrimeNumber primeNumber = new PrimeNumber();
public static void main(String[] args) { primeNumber.printPrimes(1, 100); // Find prime numbers
Employee emp = new Employee(1, "John Doe", 50000, "HR", between 1 and 100
"123 Main St");
PerfectNumber perfectNumber = new PerfectNumber();
System.out.println("Employee ID: " + emp.employeeId); perfectNumber.printPerfectNumbers(1, 100); // Find perfect
System.out.println("Employee Name: " + numbers between 1 and 100
emp.employeeName); }
}
System.out.println("Salary: " + emp.getSalary());
write a java program to implement multiple inheritance using
System.out.println("Department: " + emp.department); packages.

emp.displayEmployeeDetails(); 1. Create a Package with Interfaces:


} package com.vehicle;
}
public interface Vehicle {
void start();
write a java program to find prime numbers and perfect void stop();
numbers in the given range using two different classes. }

class PrimeNumber { package com.machine;


public boolean isPrime(int num) {
if (num <= 1) return false; public interface Machine {
for (int i = 2; i <= Math.sqrt(num); i++) { void operate();
if (num % i == 0) { void shutdown();
return false; }
} 2. Create a Class Implementing Both Interfaces:
} package com.factory;
return true;
} import com.vehicle.Vehicle;
import com.machine.Machine;
public void printPrimes(int start, int end) {
System.out.println("Prime numbers in the range " + start + " to public class Robot implements Vehicle, Machine {
" + end + ":"); public void start() {
for (int i = start; i <= end; i++) { System.out.println("Vehicle started");
if (isPrime(i)) { }
System.out.print(i + " ");
} public void stop() {
} System.out.println("Vehicle stopped");
System.out.println(); }
}
} public void operate() {
System.out.println("Machine is operating"); }
}
NumberFormatException
public void shutdown() { import java.util.Scanner;
System.out.println("Machine is shutting down");
} public class BMICalculator {
} public static void main(String[] args) {
3. Main Class to Test the Implementation: Scanner scanner = new Scanner(System.in);
import com.factory.Robot;
double weight = 0;
public class Main { double height = 0;
public static void main(String[] args) {
Robot robot = new Robot(); while (true) {
System.out.print("Enter weight in kilograms: ");
robot.start(); // From Vehicle interface String weightInput = scanner.nextLine();
robot.operate(); // From Machine interface try {
robot.shutdown(); // From Machine interface weight = Double.parseDouble(weightInput);
robot.stop(); // From Vehicle interface if (weight <= 0) {
} System.out.println("Please enter a positive number for
} weight.");
continue;
}
OverFlow exception break; // valid input
} catch (NumberFormatException e) {
class OverFlowException extends Exception { System.out.println("Invalid input. Please enter a valid
public OverFlowException(String message) { number for weight.");
super(message); }
} }
}
while (true) {
class Room { System.out.print("Enter height in meters: ");
String roomName; String heightInput = scanner.nextLine();
int capacity; try {
int currentCount; height = Double.parseDouble(heightInput);
if (height <= 0) {
public Room(String roomName, int capacity, int currentCount) { System.out.println("Please enter a positive number for
this.roomName = roomName; height.");
this.capacity = capacity; continue;
this.currentCount = currentCount; }
} break; // valid input
} catch (NumberFormatException e) {
public void addMembers(int members) throws System.out.println("Invalid input. Please enter a valid
OverFlowException { number for height.");
if (currentCount + members > capacity) { }
throw new OverFlowException("No space in the room: " + }
roomName);
} else { double bmi = weight / (height * height);
currentCount += members; System.out.println("Your BMI is: " + bmi);
System.out.println("Added " + members + " members to " +
roomName + ". Current count: " + currentCount); if (bmi < 18.5) {
} System.out.println("BMI Category: Underweight");
} } else if (bmi >= 18.5 && bmi <= 24.9) {
} System.out.println("BMI Category: Normal weight");
} else if (bmi >= 25 && bmi <= 29.9) {
public class Building { System.out.println("BMI Category: Overweight");
public static void main(String[] args) { } else {
Room r1 = new Room("r1", 30, 20); System.out.println("BMI Category: Obesity");
Room r2 = new Room("r2", 40, 25); }
Room r3 = new Room("r3", 50, 45); }
}
try {
r1.addMembers(10); access modifiers with the help of packages.
r2.addMembers(20); Step 1: Define the Person class in the person package:
r3.addMembers(10); package person;
} catch (OverFlowException e) {
System.out.println(e.getMessage()); public class Person {
} private String name;
} private int age;
import java.util.*;
public Person(String name, int age) {
class Main
this.name = name;
this.age = age; {
}
public static void main(String args[])
public void displayDetails() { {
System.out.println("Name: " + name);
System.out.println("Age: " + age); int p,r,t;
} Scanner atz=new Scanner(System.in);

public String getName() { p=atz.nextInt();


return name; t=atz.nextInt();
}
r=atz.nextInt();
public int getAge() { System.out.print((p*t*r)/100);
return age;
} }
}
public void setName(String name) {
this.name = name; Sum of Two Numbers (handle both positive and
} negative integers, as well as zero)
public void setAge(int age) { import java.util.*;
this.age = age;
class Main
}
} {
Step 2: Define the TestPerson class in the test package:
public static void main(String args[])
package test; {

import person.Person; int a,b;


Scanner sc=new Scanner(System.in);
public class TestPerson {
public static void main(String[] args) { a=sc.nextInt();
Person person = new Person("John Doe", 25); b=sc.nextInt();

person.displayDetails(); System.out.print(a+b);
}
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge()); }
}
} Time taken for one harmonic motion
import java.util.*;
program that calculates the displacement (s) import java.math.*;
import java.util.*; class Main
class Main {
{ public static void main(String args[])
public static void main(String args[]) {
{ Scanner atz=new Scanner(System.in);
float u,a,t; double g=9.8;
Scanner atz=new Scanner(System.in); double L=atz.nextDouble();
u=atz.nextFloat(); double t=2 * Math.PI * Math.sqrt(L/g);
a=atz.nextFloat(); System.out.printf("%.2f",t);
t=atz.nextFloat(); }
float s=(u*t)+(0.5f *a*(t*t)); }
System.out.print(s);
electricity bill (taking input from the keyboard)
}
import java.util.*;
}
class Main
Simple Interest {
public static void main(String args[]) System.out.print("Hot Weather");
{ }
Scanner sc=new Scanner(System.in); else if(n>=40)
double b=0d; {
int id=sc.nextInt(); System.out.print("Very hot Weather");
int u=sc.nextInt(); }
if(u<=199)
b=u*1.20; else{
else if(u>=200 && u<=399) System.out.print("Invalid input");
b=u*1.50; }
else if(u>=400 && u<=599) scn.close();
b=u*1.80; }
else }
b=u*2.00; Arithmetic Progression(taking input from the
if(b>400) keyboard)
b+=(0.15*b); import java.util.*;
if(b<100) class Main
b=100; {
System.out.print(b); public static void main(String args[])
} {
} Scanner scn=new Scanner(System.in);

weather condition (reads the temperature in int n;


degrees centigrade from the user and displays a int n1=scn.nextInt();
message) int n2=scn.nextInt();
import java.util.*; int n3=scn.nextInt();
class Main n=(n2*(2*n1+(n2-1)*n3))/2;
{ System.out.print(n);
public static void main(String args[]) scn.close();
{ }
Scanner scn=new Scanner(System.in); }
int n=scn.nextInt();
Atm Operations(taking input from the
if(n<0) keyboard)
{ import java.util.*;
System.out.print("Freezing Weather"); class Main
} {
else if(n>=0 && n<10) public static void main(String args[])
{ {
System.out.print("Very Cold Weather"); Scanner sc=new Scanner(System.in);
} int b=10000;
else if(n>=20 && n<30) boolean contbank=true;
{ while(contbank)
System.out.print("Normal Weather"); {
} int v=sc.nextInt();
else if(n>=30 && n<40) switch(v)
{ {
case 1: for(i=1;i<n;i++)
int wd=sc.nextInt(); {
if(wd>b) if(max<t[i])
System.out.print("Insufficient Balance"); max=t[i];
else{ }
b=b-wd; double min=t[0];
System.out.print("Withdraw Success, Your for(i=1;i<n;i++)
account balance is : "+b);
{
}
if(min>t[i])
break;
min=t[i];
case 2:
}
int dm=sc.nextInt();
double avg=sum/7;
b+=dm;
System.out.printf("Highest Temperature: %.1f\n",max);
System.out.print("Deposit Success, Your Current
Balance is : "+b); System.out.printf("Lowest Temperature: %.1f\n",min);

break; System.out.printf("Average Temperature: %.2f",avg);

case 3: }

System.out.print("Your Account Balance is: "+b); }

break; Grade-wise Student List (Use two-dimensional


array to hold student's)
case 4: import java.util.*;

contbank=false; public class Main

break; {

default: public static void main(String args[])

System.out.print("Invalid Choice"); {

} Scanner s=new Scanner(System.in);

} int i,n=s.nextInt();

sc.close(); String[][] arr=new String[n][2];

} for(i=0;i<n;i++)

} {
arr[i][0]=s.next();
Weekly Temperature Analysis (storing arrays)
arr[i][1]=s.next();
import java.util.*;
}
class Main
char[] grades={'A','B','C','D','E'};
{
for(char grade:grades)
public static void main(String args[])
{
{
System.out.println("");
int n=7,i;
System.out.print(grade+":");
double[] t=new double[7];
for(i=0;i<n;i++)
double sum=0.00;
{
Scanner s=new Scanner(System.in);
boolean first=true;
for(i=0;i<n;i++)
if(arr[i][1].charAt(0)==grade)
{
{
t[i]=s.nextDouble();
if(!first)
sum+=t[i];
System.out.print(" ");
}
System.out.print(" "+arr[i][0]);
double max=t[0];
first=false; }
} }
} Employee details (Creating Class & Creating
} ,Implementing Method)
} import java.util.*;
}

Employee Login System(storing details in class Main


arrays) {
import java.util.Scanner; public static void main(String args[])
public class Main {
{ Scanner s=new Scanner(System.in);
public static void main(String[] args) int i;
{ int[] eid=new int[10];
Scanner s=new Scanner(System.in); String[] en=new String[15];
try int[] ea=new int[10];
{ String[] ed=new String[15];
int n=Integer.parseInt(s.nextLine().trim()); double[] es=new double[10];
String[][] employees=new String[n][3]; for(i=0;i<1;i++)
for(int i=0;i<n;i++) {
{ eid[i]=s.nextInt();
String[] input=s.nextLine().trim().split(" ",3); s.nextLine();
if(input.length!=3) en[i]=s.nextLine();
throw new IllegalArgumentException("Invalid ea[i]=s.nextInt();
input format");
s.nextLine();
employees[i]=input;
ed[i]=s.nextLine();
}
es[i]=s.nextDouble();
String id=s.nextLine().trim();
}
String password=s.nextLine().trim();
for(i=0;i<1;i++)
boolean isLoggedIn=false;
System.out.println("Employee ID: "+eid[i]+", Name:
for(String[] employee:employees) "+en[i]+", Age: "+ea[i]+", Department: "+ed[i]+", Salary: "+es[i]);
{ s.close();
}
if(employee[0].equals(id)&&employee[2].equals(password))
}
{
Searching Record (Creating Class & Creating
System.out.println("Welcome "+employee[1]);
,Implementing Method)
isLoggedIn=true;
import java.util.*;
break;
}
public class Main
}
{
if(!isLoggedIn)
static String cn;
System.out.println("Failed to login");
static int ns;
}
static int[] rn;
catch(Exception e){
static String[] name;
System.out.println("Invalid input");}
static int[] marks;
finally{
s.close();}
public static void find_rn(int rollno) if(totalstock==0)
{ throw new
ArithmeticException("Cannot calculate stock percentage. No stock
boolean found=false; available.");
for(int i=0;i<ns;i++) double
{ stockpercentage=(double)itemsold/totalstock*100;

if(rn[i]==rollno) System.out.print("Stock
Percentage:"+stockpercentage+"%");
{
}
System.out.println("Roll Number: "+rn[i]+", Name:
"+name[i]+", Marks: "+marks[i]); catch(ArithmeticException e){

found=true; System.out.print(e.getMessage());

break; }

} }

} }

if(!found) Array Index OutOfBounds Exception


System.out.println("Record Does Not Exist"); import java.util.Scanner;
} public class Main
{
public static void main(String args[]) public static void main(String args[])
{ {
Scanner s=new Scanner(System.in); int[] scores={85, 90, 78, 92, 88};
cn=s.nextLine(); Scanner s=new Scanner(System.in);
ns=s.nextInt(); System.out.print("Enter the index of the student's score you
want to retrieve: ");
rn=new int[ns];
int in=s.nextInt();
name=new String[ns];
System.out.print(scores.length);
marks=new int[ns];
System.out.println();
for(int i=0;i<ns;i++)
try{
{
if(in<0 || in>=scores.length)
rn[i]=s.nextInt();
throw new
s.nextLine();
ArrayIndexOutOfBoundsException("Invalid index. Please enter a
name[i]=s.nextLine(); valid index between 0 and "+(scores.length-1));
marks[i]=s.nextInt(); System.out.print("Student's score: "+scores[in]);
} }
int rollno=s.nextInt(); catch(ArrayIndexOutOfBoundsException e){
find_rn(rollno); System.out.println("Error: "+e.getMessage());
} }
} s.close();

Handling ArithmeticException in Inventory }


Management System }
public class Main Throw keyword Exception Example code
{ import java.util.*;
public static void main(String args[])
{ class wle extends Exception{
int itemsold=10; public wle(String msg)
int totalstock=0; {
try { super(msg);
} }
} if (!found)
class Main throw new empnfexp("Employee Missing..");
{ else
private static final int mw=15; System.out.println("Employee " + eid + " found.");
public static void luggagecheckin(int w) throws wle{ }
if(w>mw) }
throw new wle((w-mw)+" kg :"+"
WeightLimitExceeded");
public class Main
else
{
System.out.println("You are ready to fly!");
public static void main(String[] args)
}
{
public static void main(String args[])
String eid = "e7";
{
empnfexp empcheck = new empnfexp("");
Scanner s=new Scanner(System.in);
try
for(int i=0;i<2;i++){
{
int w=s.nextInt();
empcheck.empfind(eid);
try{
}
luggagecheckin(w);
catch (empnfexp e)
}
{
catch(wle e){
System.out.println(e.getMessage());
System.out.println(e.getMessage());
}
}
}
}
}
}
Banking System (class with synchronized
}
methods)
custom exception or user-defined exception class BankAccount
import java.io.*;
{
private int bal;
class empnfexp extends Exception
public BankAccount(int initbal) {
{
this.bal = initbal;
public empnfexp(String message) {
}
super(message);
public synchronized void deposit(int amount, String
}
acholdername) {
public void empfind(String eid) throws empnfexp
if (amount > 0) {
{
bal += amount;
String[] empids = {"e1", "e3", "e5"};
System.out.println(acholdername + " deposited " +
boolean found = false; amount + ", Current Balance: " + bal);
for (String id : empids)
}
{
}
if (id.equals(eid))
public synchronized void withdraw(int amount, String
{ acholdername) {
found = true; if (amount > 0 && amount <= bal) {
break;
bal -= amount;
}
System.out.println(acholdername + " withdrew " +
amount + ", Current Balance: " + bal);
try {
} else {
user1.start();
System.out.println(acholdername + " attempted to
withdraw " + amount + " but insufficient funds."); user1.join();

} user2.start();

} user2.join();
user3.start();

public int getbalance() { user3.join();

return bal; }

} catch (InterruptedException e) {

} e.printStackTrace();
}

class User implements Runnable { }

private BankAccount acc; }

private int depositamt; Producer-Consumer Problem (Food Delivery


Simulation) ( shared OrderQueue)
private int withdrawamt;
class Order {
private String acholdername;
private static int idCounter = 0;
private final int id;
public User(BankAccount acc, int depositamt, int
withdrawamt, String acholdername) {
this.acc = acc; public Order() {
this.depositamt = depositamt; this.id = ++idCounter;
this.withdrawamt = withdrawamt; }
this.acholdername = acholdername; public int getid() {
} return id;
}
@Override }
public void run() {
acc.deposit(depositamt, acholdername); class OrderQueue {
acc.withdraw(withdrawamt, acholdername); public synchronized void placeOrder() {
} Order order = new Order();
} System.out.println("Restaurant placed order " +
order.getid());
deliverOrder(order);
public class Main{
}
public static void main(String[] args) {
BankAccount sharedac = new BankAccount(1000);
private void deliverOrder(Order order) {
System.out.println("Delivery driver delivered order "
Thread user1 = new Thread(new User(sharedac, 200, + order.getid());
500, "User1"));
}
Thread user2 = new Thread(new User(sharedac, 200,
500, "User2")); }
Thread user3 = new Thread(new User(sharedac, 200,
500, "User3"));
public class Main {
public static void main(String[] args) { System.out.println(userName + ": Seat " +
seatNumber + " already booked.");
OrderQueue order = new OrderQueue();
}
catch (Exception e)
for (int i = 0; i < 5; i++) {
{
try{
System.out.println("Error: " + e.getMessage());
order.placeOrder();
}
}
}
catch(Exception e){
}
System.out.print("Error occured in the main
process"+e.getMessage());
} class User implements Runnable
} {
} private final SeatManager seatManager;
} private final int seatNumber;
private final String userName;
Ticket Booking System (class with synchronized
methods) public User(SeatManager seatManager, String
userName, int seatNumber)
{
class SeatManager {
this.seatManager = seatManager;
private final boolean[] seats;
this.userName = userName;
public SeatManager(int totalSeats)
this.seatNumber = seatNumber;
{
}
seats = new boolean[totalSeats];
}
@Override
public void run()
public synchronized void bookSeat(String userName,
int seatNumber) {
{ seatManager.bookSeat(userName, seatNumber);
try { }
if (seatNumber < 1 || seatNumber > seats.length) }
{
System.out.println(userName + ": Invalid seat public class Main {
number " + seatNumber);
public static void main(String[] args)
return;
{
}
SeatManager seatManager = new SeatManager(10);
int seatIndex = seatNumber - 1;
Thread user1 = new Thread(new User(seatManager,
if (!seats[seatIndex]) "User1", 2));
{ Thread user2 = new Thread(new User(seatManager,
"User2", 2));
seats[seatIndex] = true;
Thread user3 = new Thread(new User(seatManager,
System.out.println(userName + " booked seat " "User3", 1));
+ seatNumber);
try {
}
user1.start();
else
user1.join();
user2.start(); for (String message : messagesToSend)
user2.join(); {
user3.start(); chatRoom.sendMessage(userName, message);
user3.join(); try {
} Thread.sleep(100);
catch (InterruptedException e) { }
System.out.println("Thread interrupted: " + catch (InterruptedException e) {
e.getMessage());
System.out.println("Thread interrupted: " +
} e.getMessage());
} }
} }
Multithreaded Chat Application }
import java.util.ArrayList; }
import java.util.List;
public class Main {
class ChatRoom { public static void main(String[] args) {
private final List<String> messages = new ChatRoom chatRoom = new ChatRoom();
ArrayList<>(); String[] messages = {"Hello!", "How's it going?"};
public synchronized void sendMessage(String Thread user1 = new Thread(new User(chatRoom,
userName, String message) "Aarya", messages));
{ Thread user2 = new Thread(new User(chatRoom,
String formattedMessage = "New Message: " + "Charan", messages));
userName + ": " + message; Thread user3 = new Thread(new User(chatRoom,
messages.add(formattedMessage); "Kiran", messages));
System.out.println(formattedMessage);
} try {
} user1.start();
user1.join();
class User implements Runnable { user2.start();
private final ChatRoom chatRoom; user2.join();
private final String userName; user3.start();
private final String[] messagesToSend; user3.join();
}
public User(ChatRoom chatRoom, String userName, catch (InterruptedException e) {
String[] messagesToSend) System.out.println("Thread interrupted: " +
{ e.getMessage());
this.chatRoom = chatRoom; }
this.userName = userName; }
this.messagesToSend = messagesToSend; }
} Counting Lines, Words, and
Characters(BufferedReader & FileReader)
@Override import java.io.BufferedReader;

public void run() import java.io.FileReader;

{ import java.io.IOException;
outputStream.write(byteData);
public class Main { }
public static void main(String[] args) { System.out.println("File Copied Successfully");
String filePath = "input.txt"; }
int lineCount = 0; catch (IOException e) {
int wordCount = 0; System.out.println("Error: " + e.getMessage());
int charCount = 0; }
}
try (BufferedReader reader = new }
BufferedReader(new FileReader(filePath))) {
reads a file and displays the file on the screen
String line; (BufferedReader)
while ((line = reader.readLine()) != null) { import java.io.BufferedReader;
lineCount++; import java.io.FileReader;
charCount += line.replaceAll("\\s", "").length(); import java.io.IOException;
String[] words = line.trim().split("\\s+");
wordCount += words.length; public class Main {
} public static void main(String[] args) {
System.out.println("Lines: " + lineCount); String filePath = "input.txt";
System.out.println("Words: " + wordCount); try (BufferedReader reader = new
System.out.println("Characters: " + charCount); BufferedReader(new FileReader(filePath))) {
} String line;
catch (IOException e) { int lineNumber = 1;
System.out.println("Error reading file: " + while ((line = reader.readLine()) != null) {
e.getMessage()); System.out.println(lineNumber + ": " + line);
} lineNumber++;
} }
} }
Copying File Contents (FileInputStream & catch (IOException e) {
FileOutputStream)
System.out.println("Error reading file: " +
import java.io.FileInputStream; e.getMessage());
import java.io.FileOutputStream; }
import java.io.IOException; }
}
public class Main { Calculator Using Swings
public static void main(String[] args) { import javax.swing.*;
String sourceFile = "source.txt"; import java.awt.*;
String destinationFile = "destination.txt"; class Main {
public static void main(String[] args) {
try (FileInputStream inputStream = new JFrame frame = new JFrame("Calculator");
FileInputStream(sourceFile);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL
FileOutputStream outputStream = new OSE);
FileOutputStream(destinationFile)) {
frame.setSize(300, 400);
int byteData;
JPanel panel = new JPanel();
while ((byteData = inputStream.read()) != -1) {
panel.setLayout(new GridLayout(4, 4, 5, 5)); genderGroup.add(femaleButton);
String[] buttons = {
"7", "8", "9", "*", gbc.gridx = 0; gbc.gridy = 0; formPanel.add(new
JLabel("Name:"), gbc);
"4", "5", "6", "/",
gbc.gridx = 1; formPanel.add(nameField, gbc);
"1", "2", "3", "+",
gbc.gridx = 0; gbc.gridy = 1; formPanel.add(new
"0", ".", "=", "-" JLabel("Address:"), gbc);
}; gbc.gridx = 1; formPanel.add(addressField, gbc);
for (String text : buttons) { gbc.gridx = 0; gbc.gridy = 2; formPanel.add(new
JButton button = new JButton(text); JLabel("Gender:"), gbc);
panel.add(button); gbc.gridx = 1; formPanel.add(new JPanel(new
FlowLayout(FlowLayout.LEFT)) {{
}
add(maleButton); add(femaleButton);
frame.add(panel);
}}, gbc);
frame.setVisible(true);
}
add(formPanel, BorderLayout.CENTER);
}
Student details using swings
JPanel buttonPanel = new JPanel();
import javax.swing.*;
JButton saveButton = new JButton("Save"),
import java.awt.*; cancelButton = new JButton("Cancel");
buttonPanel.add(saveButton);
public class Main extends JFrame { buttonPanel.add(cancelButton);
public Main() { add(buttonPanel, BorderLayout.SOUTH);
setTitle("Student Detail");
setSize(300, 200); saveButton.addActionListener(e ->
setDefaultCloseOperation(EXIT_ON_CLOSE); JOptionPane.showMessageDialog(null,

setLocationRelativeTo(null); "Saved details:\nName: " + nameField.getText()


+ "\nAddress: " + addressField.getText() +
setLayout(new BorderLayout());
"\nGender: " + (maleButton.isSelected() ?
"Male" : "Female")));
add(new JLabel("Student Detail", JLabel.CENTER), cancelButton.addActionListener(e -> {
BorderLayout.NORTH);
nameField.setText("");
addressField.setText("");
JPanel formPanel = new JPanel(new
GridBagLayout()); genderGroup.clearSelection();

GridBagConstraints gbc = new });


GridBagConstraints(); }
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL; public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new
JTextField nameField = new JTextField(15), Main().setVisible(true));
addressField = new JTextField(15); }
JRadioButton maleButton = new }
JRadioButton("Male"), femaleButton = new
JRadioButton("Female"); Employee Grading (Class with different
ButtonGroup genderGroup = new ButtonGroup();
members, different methods)
genderGroup.add(maleButton); import java.util.*;
System.out.println("Employee Name="+e.ename);
class Employee System.out.println("Designation="+e.edesig);
{ System.out.println("Salary="+e.esal);
int eid; }
String ename;
String edesig; public static void main(String args[])
int esal; {
char grade; Employee emp=new Employee();
} getemployee(emp);
showgrade(emp);
class Main showemployee(emp);
{ }
public static void getemployee(Employee e) }
{ Fan (Default constructor & Parameterized
Scanner s=new Scanner(System.in); constructor)
e.eid=s.nextInt(); import java.util.*;
s.nextLine();
e.ename=s.nextLine(); public class Main
e.edesig=s.nextLine(); {
e.esal=s.nextInt(); static class fan
} {
private int speed;
public static void showgrade(Employee e) private boolean fon;
{ private int radius;
if(e.esal>-1 && e.esal<20001) private String color;
e.grade='D';
else if(e.esal>20000 && e.esal<=50000) public fan()
e.grade='C'; {
else if(e.esal>50000 && e.esal<=100000) this.speed=1;
e.grade='B'; this.fon=false;
else if(e.esal>100000) this.radius=4;
e.grade='A'; this.color="blue";
else }
System.out.println("Invalid Output");
} public fan(int speed,boolean fon,int radius,String
color)
{
public static void showemployee(Employee e)
this.speed=speed;
{
this.fon=fon;
System.out.println("Employee grade is:");
this.radius=radius;
System.out.println(e.grade+" Grade");
this.color=color;
System.out.println("Employee details are:");
}
System.out.println("Employee ID="+e.eid);
public void updatefan(String color,int radius,boolean import java.util.*;
fon,int speed)
{
public class Main
this.color=color;
{
this.radius=radius;
static class prod
this.fon=fon;
{
this.speed=speed;
int id;
}
String name;
String cat;
public void display()
float price;
{
if(fon)
public void getprod()
System.out.println("ON "+speed+" "+color+"
"+""+radius); {

else Scanner s=new Scanner(System.in);


id=s.nextInt();
System.out.println("OFF "+color+"
"+""+radius); s.nextLine();
} name=s.nextLine();
} cat=s.nextLine();
price=s.nextFloat();
public static void main(String args[]) }
{
Scanner s=new Scanner(System.in); public void showdisc()
int c=s.nextInt(); {
String color=s.next(); System.out.println("Product discount is:");
int radius=s.nextInt(); if(price>=0 && price<51)
boolean ison=s.nextBoolean(); System.out.println("No Discount");
int speed=s.nextInt(); else if(price>50 && price<101)
fan f; System.out.println("10% Off");
if(c==1) else if(price>100 && price<201)
{ System.out.println("20% Off");
f=new fan(); else if(price>200 && price<501)
f.updatefan(color,radius,ison,speed); System.out.println("30% Off");
} else
else System.out.println("40% Off");
f=new fan(speed,ison,radius,color); }
f.display();
s.close(); public void showprod()
} {
} System.out.println("Product details are:");
Product (Class with different members, System.out.println("Product ID="+id);
different methods) System.out.println("Product Name="+name);
System.out.println("Category="+cat);
System.out.printf("Price=%.2f",price); public void showfueleff()
} {
} System.out.println("Vehicle fuel efficiency is:");
if(mil>=0 && mil<16)
public static void main(String args[]) System.out.println("Poor");
{ else if(mil>15 && mil<26)
prod p=new prod(); System.out.println("Average");
p.getprod(); else if(mil>25 && mil<36)
p.showdisc(); System.out.println("Good");
p.showprod(); else if(mil>35 && mil<51)
} System.out.println("Very Good");
} else
Vehicle(Class with different members, different System.out.println("Excellent");
methods) }

import java.util.*; public void showdep()


{
public class Main System.out.println("Vehicle depreciation status
is:");
{
if(year>=0 && year<6)
static class vehicle
System.out.println("New");
{
else if(year>5 && year<11)
int id;
System.out.println("Slightly Used");
String name;
else if(year>10 && year<21)
String type;
System.out.println("Used");
float mil;
else
int year;
System.out.println("Old");
double price;
}

public void getveh()


public void showveh()
{
{
Scanner s=new Scanner(System.in);
System.out.println("Vehicle details are:");
id=s.nextInt();
System.out.println("Vehicle ID="+id);
s.nextLine();
System.out.println("Model Name="+name);
name=s.nextLine();
System.out.println("Type="+type);
type=s.nextLine();
System.out.println("Mileage="+mil);
mil=s.nextFloat();
System.out.println("Year="+year);
s.nextLine();
System.out.printf("Price=%.2f",price);
year=s.nextInt();
}
s.nextLine();
}
price=s.nextDouble();
}
public static void main(String args[])
{
vehicle v=new vehicle(); String
p=String.format("%.1f",Math.floor(this.price*10)/10);
v.getveh();
System.out.println("Book"+n+" Price: "+p);
v.showfueleff();
}
v.showdep();
}
v.showveh();
}
public class Main
}
{
default constructor and two parameterized
constructors: public static void main(String args[])

import java.util.*; {
Book b1=new Book();

class Book b1.display(1);

{ Book b2=new Book("Amatka","Karin Tidbeck");

private String title; b2.display(2);

private String author; Book b3=new Book("Altered Carbon","Richard K.


Morgan",18.99);
private Double price;
b3.display(3);
}
public Book()
}
{
abstract class & abstract methods
this.title="Unknown";
import java.util.*;
this.author="Unknown";
this.price=0.0;
abstract class Geo
}
{
abstract double area();
public Book(String title,String author)
abstract double perimeter();
{
}
this.title=title;
this.author=author;
class triangle extends Geo
this.price=0.0;
{
}
private double s1,s2,s3;
public triangle(double s1,double s2,double s3)
public Book(String title,String author,double price)
{
{
this.s1=s1;
this.title=title;
this.s2=s2;
this.author=author;
this.s3=s3;
this.price=price;
}
}
public double area()
{
public void display(int n)
double s=(s1+s2+s3)/2;
{
return Math.sqrt(s*(s-s1)*(s-s2)*(s-s3));
System.out.println("Book"+n+" Title: "+this.title);
}
System.out.println("Book"+n+" Author:
"+this.author);
public double perimeter() protected double b;
{ public BankAccount(double initialBalance)
return s1+s2+s3; {
} this.b = initialBalance;
} }
public void deposit(double amount)
class square extends Geo {
{ b += amount;
private double s; }
public square(double s) public void withdraw(double amount)
{ {
this.s=s; if (amount <= b)
} b -= amount;
}
public double area()
{ public double getBalance()
return s*s; {
} return b;
}
public double perimeter() }
{
return 4*s; class SavingsAccount extends BankAccount
} {
} private double withdrawLimit;
public SavingsAccount(double initialBalance, double
withdrawLimit)
public class Main
{
{
super(initialBalance);
public static void main(String args[])
this.withdrawLimit = withdrawLimit;
{
}
Geo t=new triangle(4,5,6);
System.out.println("Triangle Area: "+t.area());
public void withdraw(double amount)
System.out.println("Triangle Perimeter:
"+t.perimeter()); {
if (amount <= withdrawLimit)
Geo s=new square(6); super.withdraw(amount);
System.out.println("Square Area: "+s.area()); else
System.out.println("Square Perimeter: System.out.println("Exceeds withdrawal limit for
"+s.perimeter()); SavingsAccount.");
} }
} }
Override
class CheckingAccount extends BankAccount
class BankAccount { {
private double overdraftFee; private String lname;
public CheckingAccount(double initialBalance, double
overdraftFee)
public Person(String fname,String lname)
{
{
super(initialBalance);
this.fname=fname;
this.overdraftFee = overdraftFee;
this.lname=lname;
}
}
public void withdraw(double amount)
{
public String f_name()
if (amount <= getBalance())
{
super.withdraw(amount);
return fname;
else
}
super.withdraw(amount + overdraftFee);
}
public String l_name()
}
{
return lname;
public class Main
}
{
}
public static void withdrawFromAccount(BankAccount
account, double amount)
{
account.withdraw(amount); class Employee extends Person

} {
private int eid;

public static void main(String[] args) private String job;

{ public Employee(String fname,String lname,int


eid,String job)
SavingsAccount sa = new SavingsAccount(2000,
650); {

CheckingAccount ca = new CheckingAccount(1000, super(fname,lname);


100); this.eid=eid;
withdrawFromAccount(sa, 300); this.job=job;
withdrawFromAccount(ca, 250); }
System.out.println("Savings Account Balance: " + public int e_id()
sa.getBalance());
{
System.out.println("Checking Account Balance: " +
ca.getBalance()); return eid;

} }

} public String e_job()


{
Private and override code
return job;
import java.util.*;
}
@Override
class Person
public String toString()
{
{
private String fname;
return f_name()+" "+l_name()+", "+job+"
"+"("+eid+")";
for(i=0;i<c;i++)
}
{
}
for(j=0;j<r;j++)
{
public class Main
System.out.print(tran[i][j]+" ");
{
}
public static void main(String args[])
System.out.println();
{
}
Employee p1=new Employee("Kranthi", "Kiran",
4451, "HR Manager"); s.close();

Employee p2=new Employee("Junior", "Shilpa", }


4452, "Software Manager"); }
System.out.println(p1); Employees of a company (inheritance,
System.out.print(p2); encapsulation, polymorphism, overriding,
} constructors, abstraction, hierarchy, OOP
principles, dynamic dispatch, method
} overloading, encapsulation of behavior, instance
Tranpose of Matrix variables, default implementations, object
import java.util.*;
creation, code reusability, and method
visibility.)
class Employee {
class Main
private String name, address, jobTitle;
{
private double salary;
public static void main(String args[])
{
public Employee(String name, String address, double
Scanner s=new Scanner(System.in); salary, String jobTitle) {
int i,j,r=3,c=3; this.name = name; this.address = address; this.salary
int[][] arr=new int[r][c]; = salary; this.jobTitle = jobTitle;

for(i=0;i<r;i++) }

{
for(j=0;j<c;j++) public String getName() {

{ return name;

arr[i][j]=s.nextInt(); }

} public double getSalary() {

} return salary;
}

int[][] tran=new int[r][c];


for(i=0;i<r;i++) public double calculateBonus() {

{ return 0.0;

for(j=0;j<c;j++) }

{ public String generatePerformanceReport() {

tran[j][i]=arr[i][j]; return "No performance";

} }

} }
public Programmer(String name, String address, double
salary, String language) {
class Manager extends Employee {
super(name, address, salary, language);
public Manager(String name, String address, double
salary) { }
super(name, address, salary, "Manager");
} @Override
@Override public double calculateBonus() {
public double calculateBonus() { return getSalary() * 0.12;
return getSalary() * 0.15; }
} @Override
@Override public String generatePerformanceReport() {
public String generatePerformanceReport() { return "Performance report for Programmer " +
getName() + ": Excellent";
return "Performance report for Manager " +
getName() + ": Excellent"; }
} public void debugCode() {
public void manageProject() { System.out.println("Programmer " + getName() + "
is debugging code in Python");
System.out.println("Manager " + getName() + " is
managing a project."); }
} }
}
public class Main {
class Developer extends Employee { public static void main(String[] args) {
private String language; Manager m = new Manager("Raju Dev", "1 ABC St",
80000);
public Developer(String name, String address, double
salary, String language) { Developer d = new Developer("Neeraj Gupta", "2
PQR St", 72000, "Java");
super(name, address, salary, "Developer");
this.language = language; Programmer p = new Programmer("Sujay Raj", "3
ABC St", 76000, "Python");
}
System.out.println("Manager's Bonus: $" +
m.calculateBonus());
@Override public double calculateBonus() { System.out.println("Developer's Bonus: $" +
return getSalary() * 0.10; d.calculateBonus());
} System.out.println("Programmer's Bonus: $" +
p.calculateBonus());
@Override
public String generatePerformanceReport() { System.out.println(m.generatePerformanceReport());
return "Performance report for Developer " + System.out.println(d.generatePerformanceReport());
getName() + ": Good";
System.out.println(p.generatePerformanceReport());
}
m.manageProject();
public void writeCode() {
d.writeCode();
System.out.println("Developer " + getName() + " is
writing code in " + language); p.debugCode();
} }
} }
Parent share to sons and daughter (Inheritance,
class Programmer extends Developer { Encapsulation, Constructor Chaining,
Polymorphism, Aggregation, Arithmetic
Operations, Modularity, Abstraction, Code public Son1(double amt) {
Reusability, Overriding, Scanner, Type Casting, super(amt);
Input Handling, Resource Management, Output }
Formatting, Design Principles.)
}

import java.util.Scanner;
class Son2 extends FM {
public Son2(double amt) {
class FM {
super(amt);
double amt;
}
public FM(double amt) {
this.amt = amt;
public void giveToSister(Daughter daughter) {
}
double toDaughter = this.amt * 0.10;
daughter.addAmount(toDaughter);
public void addAmount(double add) {
this.deductAmount(toDaughter);
this.amt += add;
}
}
}

public void deductAmount(double ded) {


class Daughter extends FM {
this.amt -= ded;
public Daughter(double amt) {
}
super(amt);
}
public double getAmount() {
}
return this.amt;
}
public class Main
}
{
public static void main(String[] args) {
class Father extends FM {
Scanner s = new Scanner(System.in);
public Father(double amt) {
double fatherAmount = s.nextDouble();
super(amt);
double son1Amount = s.nextDouble();
}
double son2Amount = s.nextDouble();
double daughterAmount = s.nextDouble();
public void distributeAmount(Son1 son1, Son2 son2) {
Father f = new Father(fatherAmount);
double toSon1 = this.amt * 0.20;
Son1 s1 = new Son1(son1Amount);
son1.addAmount(toSon1);
Son2 s2 = new Son2(son2Amount);
this.deductAmount(toSon1);
Daughter d = new Daughter(daughterAmount);
f.distributeAmount(s1, s2);
double toSon2 = this.amt * 0.20;
s2.giveToSister(d);
son2.addAmount(toSon2);
System.out.println("FATHER AMOUNT:" + (int)
this.deductAmount(toSon2); f.getAmount());
} System.out.println("SON1 AMOUNT:" + (int)
} s1.getAmount());
System.out.println("SON2 AMOUNT:" + (int)
s2.getAmount());
class Son1 extends FM {
System.out.println("DAUGHTER AMOUNT:" + {
(int) d.getAmount());
n[i]=s.nextInt();
s.close();
}
}
Arrays.sort(n);
}
for(i=0;i<n.length;i++)
all duplicate elements in an array System.out.println(n[i]);
import java.util.*; s.close();
class Main }
{ }
public static void main(String args[])
remove duplicate elements from an array.
{
import java.util.*;
Scanner s=new Scanner(System.in);
int x=7;
class Main
int[] n=new int[x];
{
for(int i=0;i<n.length;i++)
public static void main(String args[])
{
{
n[i]=s.nextInt();
Scanner s=new Scanner(System.in);
}
int i,j=0,x=7;
for(int i=0;i<n.length;i++)
int[] n=new int[x];
{
for(i=0;i<n.length;i++)
for(int j=i+1;j<n.length;j++)
n[i]=s.nextInt();
{
int[] t=new int[x];
if(n[i]==n[j])
for(i=0;i<n.length;i++)
System.out.println(n[j]);
{
}
boolean dup=false;
}
for(int k=0;k<j;k++)
s.close();
{
}
if(n[i]==n[k])
}
{
sort an array of integers in ascending and dup=true;
descending order( with pre bulit array
break;
functions)
}
import java.util.*;
}
import java.util.Arrays;
if(!dup)
n[j++]=n[i];
class Main
}
{
for(i=0;i<j;i++)
public static void main(String args[])
System.out.print(n[i]+" ");
{
s.close();
Scanner s=new Scanner(System.in);
}
int i,x=5;
}
int[] n=new int[x];
for(i=0;i<n.length;i++) vector Collection
import java.util.Vector; productName = sc.nextLine();
reviewerName = sc.nextLine();
public class Main1 { rating = sc.nextInt();
public static void main(String[] args) { sc.nextLine(); // Consume newline
Vector<Integer> vector = new Vector<>(); reviewDate = sc.nextLine();
vector.add(10); comments = sc.nextLine();
vector.add(20); }
vector.add(30); public void showRatingCategory() {
vector.add(40); if (rating == 5) {
System.out.println("Vector elements: " + vector); System.out.println("Review rating
is:\nExcellent");
vector.remove(Integer.valueOf(20));
} else if (rating == 4) {
System.out.println("Vector elements after removal: "
+ vector); System.out.println("Review rating is:\nVery
Good");
int element = vector.get(1);
} else if (rating == 3) {
System.out.println("Element at index 1: " + element);
System.out.println("Review rating is:\nGood");
}
} else if (rating == 2) {
}
System.out.println("Review rating is:\nFair");
Movie_details_week 5_5 (Class, Object,
Attributes, Methods, Encapsulation, Input } else if (rating == 1) {
Handling, Conditional Statements, Scanner, System.out.println("Review rating is:\nPoor");
String Operations, Integer Operations, Code }
Reusability, Modularity, Control Flow,
}
Resource Management, Output Formatting,
Main Method.)
import java.util.Scanner; public void showReview() {
System.out.println("Review details are:");
public class Main { System.out.println("Review ID=" + reviewId);
int reviewId; System.out.println("Product Name=" +
productName);
String productName;
System.out.println("Reviewer Name=" +
String reviewerName; reviewerName);
int rating; System.out.println("Rating=" + rating);
String reviewDate; System.out.println("Review Date=" + reviewDate);
String comments; System.out.println("Comments=" + comments);
}
// Method to get the review details
public void getReview() { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Main review = new Main();
review.getReview();
// Input for review details review.showRatingCategory();
// System.out.print("Enter Review ID: "); review.showReview();
reviewId = sc.nextInt(); }
sc.nextLine(); // Consume newline }
Student_details_7_2 (Class, Object, Attributes,
//System.out.print("Enter Product Name: "); Constructor, Static Variable, Static Method,
Encapsulation, Method Overloading, Code System.out.println("Student Details:");
Reusability, Access Modifiers, Print Statements, s1.displayStudentDetails();
Main Method, Modularity, Parameterized s2.displayStudentDetails();
Constructor, String Handling, Double
Operations.) s3.displayStudentDetails();

public class Main { System.out.println("Total Students: " +


Student.getTotalStudents());
public static class Student {
}
private int rollNumber;
}
private String name;
GeometricShape 8_1_1 (Abstract Class,
private int age;
Abstract Method, Method Overriding,
private String course; Encapsulation, Constructor, Private Attributes,
private double marks; Inheritance, Polymorphism, Area Calculation,
Perimeter Calculation, Main Method, Object
private static int totalStudents = 0;
Creation, Print Statements, Code Reusability,
public Student(int rollNumber, String name, int age, Double Operations, Modularity.)
String course, double marks) {
abstract class geometricshape{
this.rollNumber = rollNumber;
abstract double area();
this.name = name;
abstract double perimeter();
this.age = age;
}
this.course = course;
class triangle extends geometricshape{
this.marks = marks;
private double base;
totalStudents++;
private double height;
}
private double s1;
private double s2;
public static int getTotalStudents() {
private double s3;
return totalStudents;
public triangle(double base,double height,double
} s1,double s2,double s3){
this.base=base;
public void displayStudentDetails() { this.height=height;
System.out.println("Roll Number: " + this.s1=s1;
rollNumber);
this.s2=s2;
System.out.println("Name: " + name);
this.s3=s3;
System.out.println("Age: " + age);
System.out.println("Course: " + course);
}
System.out.println("Marks: " + marks);
System.out.println();
double area(){
}
return 0.5*base*height;
}
}
double perimeter(){
public static void main(String[] args) {
return s1+s2+s3;
Student s1 = new Student(1, "Prabhas Raj", 20,
"Computer Science", 85.5); }
Student s2 = new Student(2, "Vishwa Tej", 22,
"Mechanical Engineering", 90.0); }
Student s3 = new Student(3, "Vishal Shekar", 21,
"Biotechnology", 88.75);
class square extends geometricshape{ public Bank(double amount,double rate){
private double side; this.amount=amount;
this.rate=rate;
public square(double side){ }
this.side=side; @Override
} double fee(){
return (rate/100)*amount;
double area(){ }
return side*side; @Override
} public String details(){
double fee=fee();
double perimeter(){ return String.format("Bank Transfer of %.2f with a
fee rate of %.2f%%. Transaction fee: %.2f ",amount,rate,fee);
return 4*side;
}
}
}
}
class Creditcard extends Financial{
private double amount;
public class Main{
private double fixedfee;
public static void main(String args[]){
private double pfee;
triangle t1=new triangle(5,6,5,4,3);
public Creditcard(double amount,double
fixedfee,double pfee){
System.out.println("Triangle area: "+t1.area()); this.amount=amount;
System.out.println("Triangle perimeter: this.fixedfee=fixedfee;
"+t1.perimeter());
this.pfee=pfee;
}
square s1=new square(4);
@Override
System.out.println("Square area: "+s1.area());
double fee(){
System.out.println("Square perimeter:
"+s1.perimeter()); return fixedfee+(pfee/100)*amount;
} }
} @Override
Bank_Finacial_8_1_2 (Abstract Class, Abstract public String details(){
Method, Method Overriding, Inheritance, double fee=fee();
Constructor, Encapsulation, String Formatting, return String.format("Credit Card Payment of %.2f
Polymorphism, Fee Calculation, Method with a fixed fee of %.2f and percentage fee rate of %.2f%%.
Implementation, Double Operations, Print Total transaction fee: %.2f",amount,fixedfee,pfee,fee);
Statements, Code Reusability, Transaction }
Calculation, Parameters Passing.)
}
abstract class Financial{
public class Main{
abstract double fee();
public static void main(String[] args){
abstract String details();
Bank bank=new Bank(1000.00,1.5);
}
System.out.println(bank.details());
class Bank extends Financial{
System.out.println("Calculated Bank Transfer fee:
private double amount; "+bank.fee());
private double rate; System.out.println();
Creditcard card=new Creditcard(1000.00,2.50,2.0); public class Main {
System.out.println(card.details()); public static void main(String[] args) {
System.out.println("Calculated Credit Card Payment PercentageDiscount percentageDiscount = new
fee: "+card.fee()); PercentageDiscount(10.0);
} double totalAmount1 = 200.00;
}
System.out.println(percentageDiscount.discountDetails());
Abstarct_class_Discount 8_1_3 (Abstract Class,
Abstract Method, Method Overriding, System.out.println("Final amount after discount: $" +
percentageDiscount.applyDiscount(totalAmount1));
Inheritance, Constructor, Encapsulation, String
Formatting, Polymorphism, Discount FixedAmountDiscount fixedAmountDiscount = new
Calculation, Method Implementation, FixedAmountDiscount(30.00);
Parameters Passing, Double Operations, Code double totalAmount2 = 200.00;
Reusability, Print Statements, Tax Calculation.)
abstract class Discount { System.out.println(fixedAmountDiscount.discountDetails());

abstract double applyDiscount(double totalAmount); System.out.println("Final amount after discount: $" +


fixedAmountDiscount.applyDiscount(totalAmount2));
abstract String discountDetails();
}
}
}
class PercentageDiscount extends Discount {
Abstarct_Bank_Account_9_2_1 (Abstract
private double discountRate;
Class, Abstract Method, Inheritance, Method
public PercentageDiscount(double discountRate) { Overriding, Constructor, Encapsulation, String
this.discountRate = discountRate; Formatting, Interest Calculation, Account
}
Types, Polymorphism, Balance Deduction, Fee
Calculation, Print Statements, Overridden
Methods.)
double applyDiscount(double totalAmount) { abstract class BankAccount {
return totalAmount - (totalAmount * (discountRate / protected double balance;
100));
public BankAccount(double balance) {
}
this.balance = balance;
String discountDetails() {
}
return String.format("Percentage Discount of
%.2f%%",discountRate); abstract double calculateInterest();
} abstract String accountDetails();
} }
class FixedAmountDiscount extends Discount { class SavingsAccount extends BankAccount {
private double fixedAmount; private double annualInterestRate;
public FixedAmountDiscount(double fixedAmount) { public SavingsAccount(double balance, double
annualInterestRate) {
this.fixedAmount = fixedAmount;
super(balance);
}
this.annualInterestRate = annualInterestRate;
double applyDiscount(double totalAmount) {
}
return totalAmount - fixedAmount;
@Override
}
double calculateInterest() {
String discountDetails() {
return balance * (annualInterestRate / 100);
return String.format("Fixed Discount of
%.2f",fixedAmount); }
} @Override
} public String accountDetails() {
double interestEarned = calculateInterest(); Return, Conditionals, Load Weight Adjustment,
return String.format("Savings Account\nBalance: Print Statements.)
$%.1f\nAnnual Interest Rate: %.1f%%\nInterest Earned: abstract class Vehicle {
$%.1f",
protected double milesDriven;
balance, annualInterestRate,
interestEarned); protected double fuelUsed;
} public Vehicle(double milesDriven, double fuelUsed) {
} this.milesDriven = milesDriven;
class CheckingAccount extends BankAccount { this.fuelUsed = fuelUsed;
private double monthlyFee; }
public CheckingAccount(double balance, double abstract double calculateFuelEfficiency();
monthlyFee) {
abstract String getVehicleType();
super(balance);
}
this.monthlyFee = monthlyFee;
class Car extends Vehicle {
}
public Car(double milesDriven, double fuelUsed) {
@Override
super(milesDriven, fuelUsed);
double calculateInterest() {
}
return 0.0;
@Override
}
double calculateFuelEfficiency() {
@Override
return milesDriven / fuelUsed;
public String accountDetails() {
}
double finalBalance = balance - monthlyFee;
@Override
return String.format("Checking Account\nBalance:
public String getVehicleType() {
$%.1f\nMonthly Maintenance Fee: $%.1f\nInterest Earned:
$%.1f\nAfter deducting monthly fee: $%.1f", return "Car";
balance, monthlyFee, }
calculateInterest(), finalBalance);
}
}
class Truck extends Vehicle {
}
private double loadWeight;
public class Main {
public Truck(double milesDriven, double fuelUsed,
public static void main(String[] args) { double loadWeight) {
SavingsAccount savingsAccount = new super(milesDriven, fuelUsed);
SavingsAccount(1000.00, 5.0);
this.loadWeight = loadWeight;

System.out.println(savingsAccount.accountDetails()); }

System.out.println(); @Override

CheckingAccount checkingAccount = new double calculateFuelEfficiency() {


CheckingAccount(1500.00, 12.00); double efficiency = milesDriven / fuelUsed;
if (loadWeight > 1000) {
System.out.println(checkingAccount.accountDetails());
efficiency -= efficiency * 0.08;
}
}
}
return efficiency;
Abstarct_class_Vehicle_9_2_2 (Abstract Class, }
Abstract Method, Inheritance, Method
Overriding, Constructor, Polymorphism, Fuel @Override
Efficiency Calculation, Vehicle Types, String public String getVehicleType() {
return "Truck";
} }
} }
public class Main {
public static void main(String[] args) {
Car car = new Car(300.0, 15.0);
System.out.println("Vehicle Type: " +
car.getVehicleType());
System.out.println("Fuel Efficiency: " +
car.calculateFuelEfficiency() + " MPG");
System.out.println();
Truck truck = new Truck(400.0, 20.0, 2000.0);
System.out.println("Vehicle Type: " +
truck.getVehicleType());
System.out.println("Fuel Efficiency: " +
truck.calculateFuelEfficiency() + " MPG");

You might also like