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

Java PDF

Uploaded by

Vani R Kattimani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java PDF

Uploaded by

Vani R Kattimani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

JAVA MAIN ASSIGNMENT

1. Write a Java program to sort the elements using a for loop.

Answer:

public class SortUsingForLoop {

public static void main(String[] args) {

int[] array = {5, 2, 8, 7, 1};

for (int i = 0; i < array.length - 1; i++) {

for (int j = i + 1; j < array.length; j++) {

if (array[i] > array[j]) {

int temp = array[i];

array[i] = array[j];

array[j] = temp;

System.out.println("Sorted Array in Ascending Order:");

for (int num : array) {

System.out.print(num + " ");

Aman Navalur Page 1


JAVA MAIN ASSIGNMENT

2. Write a recursive program to find nth Fibonacci number.

Answer:

public class FibonacciRecursive {

public static int fibonacci(int n) {

if (n <= 1)

return n;

return fibonacci(n - 1) + fibonacci(n - 2);

public static void main(String[] args) {

int n = 5;

System.out.println("Fibonacci number at position " + n + " is: " +


fibonacci(n));

Aman Navalur Page 2


JAVA MAIN ASSIGNMENT

3. Write a program to perform Stack operations using proper class and Methods.

Answer:

class Stack {

private int maxSize;

private int[] stackArray;

private int top;

public Stack(int size) {

maxSize = size;

stackArray = new int[maxSize];

top = -1;

public void push(int value) {

if (top == maxSize - 1) {

System.out.println("Stack is full!");

} else {

stackArray[++top] = value;

public int pop() {

Aman Navalur Page 3


JAVA MAIN ASSIGNMENT

if (top == -1) {

System.out.println("Stack is empty!");

return -1;

} else {

return stackArray[top--];

public void display() {

if (top == -1) {

System.out.println("Stack is empty!");

} else {

System.out.print("Stack elements: ");

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

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

System.out.println();

public class StackOperations {

public static void main(String[] args) {

Aman Navalur Page 4


JAVA MAIN ASSIGNMENT

Stack stack = new Stack(5);

stack.push(10);

stack.push(20);

stack.push(30);

stack.display();

System.out.println("Popped element: " + stack.pop());

stack.display();

4. Java Program to sort the elements of an array in ascending & disascending


order.

Answer:

import java.util.Arrays;

import java.util.Collections;

public class ArraySortAscDesc {

public static void main(String[] args) {

Integer[] array = {5, 2, 8, 7, 1};

Aman Navalur Page 5


JAVA MAIN ASSIGNMENT

Arrays.sort(array);

System.out.println("Array in Ascending Order:");

for (int num : array) {

System.out.print(num + " ");

Arrays.sort(array, Collections.reverseOrder());

System.out.println("\nArray in Descending Order:");

for (int num : array) {

System.out.print(num + " ");

5. Write a Java Program to Create an Interface.


Answer:

interface Animal {

void makeSound();

class Dog implements Animal {

public void makeSound() {

System.out.println("Bark");

Aman Navalur Page 6


JAVA MAIN ASSIGNMENT

public class InterfaceExample {

public static void main(String[] args) {

Dog dog = new Dog();

dog.makeSound();

6. Write a Java Program to Show Encapsulation in Class.


Answer:
class Employee {

private String name;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

}
Aman Navalur Page 7
JAVA MAIN ASSIGNMENT

public class EncapsulationExample {

public static void main(String[] args) {

Employee emp = new Employee();

emp.setName("John Doe");

System.out.println("Employee Name: " + emp.getName());

7. Write a Java Program to Show Inheritance in Class.


Answer:
class Animal {

void eat() {

System.out.println("Eating...");

class Dog extends Animal {

void bark() {

System.out.println("Barking...");
Aman Navalur Page 8
JAVA MAIN ASSIGNMENT

public class InheritanceExample {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat();

dog.bark();

8. Write a Java Program to Show Data Hiding in Class .


Answer:
class BankAccount {

private double balance;

public BankAccount(double balance) {

this.balance = balance;

public double getBalance() {

Aman Navalur Page 9


JAVA MAIN ASSIGNMENT

return balance;

public class DataHidingExample {

public static void main(String[] args) {

BankAccount account = new BankAccount(1000.00);

System.out.println("Account Balance: " + account.getBalance());

9. Write a Java Program to Show Overloading of Methods in Class.


Answer:
class Calculator {

int add(int a, int b) {

return a + b;

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

return a + b + c;

Aman Navalur Page 10


JAVA MAIN ASSIGNMENT

double add(double a, double b) {

return a + b;

public class OverloadingExample {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println("Sum of 2 and 3: " + calc.add(2, 3));

System.out.println("Sum of 2, 3, and 4: " + calc.add(2, 3, 4));

System.out.println("Sum of 2.5 and 3.5: " + calc.add(2.5, 3.5));

10. Write a Java Program to Show Overriding of Methods in Classes.


Answer:
class Animal {

void makeSound() {

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

Aman Navalur Page 11


JAVA MAIN ASSIGNMENT

class Dog extends Animal {

@Override

void makeSound() {

System.out.println("Bark");

public class OverridingExample {

public static void main(String[] args) {

Animal myDog = new Dog();

myDog.makeSound();

11. Write a Java Program to Show Use of Super Keyword in Class.


Answer:
class Vehicle {

String type;

Vehicle(String type) {

this.type = type;

Aman Navalur Page 12


JAVA MAIN ASSIGNMENT

class Car extends Vehicle {

Car(String type) {

super(type);

void displayType() {

System.out.println("Car type: " + type);

public class SuperKeywordExample {

public static void main(String[] args) {

Car car = new Car("Sedan");

car.displayType();

Aman Navalur Page 13


JAVA MAIN ASSIGNMENT

12. Write a Java Program to Show Use of This Keyword in Class.


Answer:
class Person {

String name;

Person(String name) {

this.name = name;

void display() {

System.out.println("Name: " + this.name);

public class ThisKeywordExample {

public static void main(String[] args) {

Person person = new Person("Alice");

person.display();

Aman Navalur Page 14


JAVA MAIN ASSIGNMENT

13. Write a Java Program to Show Usage of Static keyword in Class.


Answer:
class Counter {

static int count = 0;

Counter() {

count++;

static void displayCount() {

System.out.println("Number of objects created: " + count);

public class StaticKeywordExample {

public static void main(String[] args) {

new Counter();

new Counter();

new Counter();

Counter.displayCount();

Aman Navalur Page 15


JAVA MAIN ASSIGNMENT

14. Write a Java Program to Show Usage of Access Modifier.


Answer:
class AccessModifierExample {

private String privateVariable = "Private Variable";

public String publicVariable = "Public Variable";

protected String protectedVariable = "Protected Variable";

String defaultVariable = "Default Variable";

void display() {

System.out.println(privateVariable);

System.out.println(publicVariable);

System.out.println(protectedVariable);

System.out.println(defaultVariable);

public class AccessModifierDemo {

public static void main(String[] args) {

AccessModifierExample example = new AccessModifierExample();

example.display();

System.out.println(example.publicVariable);

}
Aman Navalur Page 16
JAVA MAIN ASSIGNMENT

Assignment 2:

1. Write a Java Program to Handle the Exception Methods.

Answer:

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

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

System.out.println(numbers[3]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Error: " + e.getMessage());

} finally {

System.out.println("This block executes regardless of exception.");

Aman Navalur Page 17


JAVA MAIN ASSIGNMENT

2. Write a Java program to Handle the Checked exceptions.

Answer:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class CheckedExceptionExample {

public static void main(String[] args) {

try {

File file = new File("nonexistentfile.txt");

Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {

System.out.println(scanner.nextLine());

scanner.close();

} catch (FileNotFoundException e) {

System.out.println("Error: File not found. " + e.getMessage());

Aman Navalur Page 18


JAVA MAIN ASSIGNMENT

3. Write a Java Program to Handle the Unchecked Exceptions.

Answer:

public class UncheckedExceptionExample {

public static void main(String[] args) {

try {

String str = null;

System.out.println(str.length());

catch (NullPointerException e) {

System.out.println("Error: " + e.getMessage());

Aman Navalur Page 19


JAVA MAIN ASSIGNMENT

4. Write a Java Program to Show Thread interface and memory consistency


errors.

Answer:

class Counter implements Runnable {

private int count = 0;

public void run() {

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

count++;

public int getCount() {

return count;

public class ThreadInterfaceExample {

public static void main(String[] args) throws InterruptedException {

Counter counter = new Counter();

Thread thread1 = new Thread(counter);

Thread thread2 = new Thread(counter);

Aman Navalur Page 20


JAVA MAIN ASSIGNMENT

thread1.start();

thread2.start();

thread1.join();

thread2.join();

System.out.println("Final Count: " + counter.getCount());

Aman Navalur Page 21


JAVA MAIN ASSIGNMENT

5. Write a Java Program to Check the Thread Status.

Answer:

public class ThreadStatusExample {

public static void main(String[] args) throws InterruptedException {

Thread thread = new Thread(() -> {

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

});

System.out.println("Thread status before starting: " + thread.getState());

thread.start();

System.out.println("Thread status after starting: " + thread.getState());


thread.join();

System.out.println("Thread status after completion: " + thread.getState());

Aman Navalur Page 22


JAVA MAIN ASSIGNMENT

5. Write a Java Program to Suspend a thread.

Answer:

class SuspendResumeThread implements Runnable {

private volatile boolean suspended = false;

public void run() {

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

while (suspended) {

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println(i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

Aman Navalur Page 23


JAVA MAIN ASSIGNMENT

public void suspend() {

suspended = true;

public void resume() {

suspended = false;

public class SuspendResumeExample {

public static void main(String[] args) throws InterruptedException {

SuspendResumeThread task = new SuspendResumeThread();

Thread thread = new Thread(task);

thread.start();

Thread.sleep(2000);

task.suspend();

System.out.println("Thread suspended.");

Thread.sleep(2000);

task.resume();

System.out.println("Thread resumed.");

thread.join();

Aman Navalur Page 24


JAVA MAIN ASSIGNMENT

6. Write a Java Program The values( ) and valueOf( ) Methods in enum.

Answer:

enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY;

public class EnumMethodsExample {

public static void main(String[] args) {

Day[] days = Day.values();

System.out.println("Days of the week:");

for (Day day : days) {

System.out.println(day);

Day day = Day.valueOf("MONDAY");

System.out.println("Selected day: " + day);

Aman Navalur Page 25


JAVA MAIN ASSIGNMENT

7. Write a Java program for enumeration.

Answer:

enum Color {

RED, GREEN, BLUE;

public class EnumerationExample {

public static void main(String[] args) {

Color favoriteColor = Color.GREEN;

System.out.println("Favorite color: " + favoriteColor);

System.out.println("All colors:");

for (Color color : Color.values()) {

System.out.println(color);

Aman Navalur Page 26

You might also like