JAVA College programs till 23

Java Lab Heads-Up! 🚀

Hey friends, got some cool Java lab stuff here! Check it out, get ideas, but no copy-pasting, cool? Teachers can spot doubles! 🧐

Let's rock these labs together! 💻✨

Cheers, 




Date: 06/10/2024

PROGRAM – 1

 

AIM: Write a java Program to accept a String as a command-line argument and print a Welcome message as given below:- “Welcome yourname”.

 

THEORY:

In Java, command-line arguments provide a convenient way for users to input data when executing a program from the command line. These arguments are passed to the `main` method of the Java application as an array of strings. By accessing this array, developers can retrieve the values provided by the user during program execution. Command-line arguments are commonly used to configure or customize the behavior of a Java program dynamically. For example, a user might provide filenames, options, or parameters, and the program can respond accordingly. The `args` parameter in the `main` method captures these command-line arguments, enabling developers to build more flexible and versatile applications that can adapt to different input scenarios. Proper handling of command-line arguments enhances the usability and versatility of Java programs by allowing users to interact with the application in a straightforward and customizable manner.

 

CODE:

public class WelcomeMessage {

    public static void main(String[] args) {

        if (args.length > 0) {

            System.out.println("Welcome " + args[0] + " " + args[1]);

        } else {

            System.out.println("Please provide names as command-line arguments.");

        }

    }

}



Date: 06/10/2024

PROGRAM – 2

 

AIM: Write a java Program to find ASCII code of a character.

 

THEORY:

ASCII (American Standard Code for Information Interchange) is a character encoding standard used in computing that assigns numerical values to various characters, including letters, digits, and special symbols. Each character is represented by a unique 7-bit or 8-bit binary code, allowing computers to store and exchange textual information. The ASCII code for a character provides a standardized way to represent and communicate text across different systems and platforms.

Uppercase Letters (A-Z):                        

  • Range: 65 to 90                        

Lowercase Letters (a-z):

  • Range: 97 to 122

Numbers (0-9):

  • Range: 48 to 57

 

CODE:

import java.util.Scanner;

public class AsciiCode {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");

        char ch = scanner.next().charAt(0);

        int asciiCode = (int) ch;

        System.out.println("ASCII code of '" + ch + "' is: " + asciiCode);

    }

}



Date: 06/10/2024

PROGRAM – 3

 

AIM: Write a java Program to accept two integers as inputs and print their sum.

 

THEORY:

The Scanner class in Java simplifies keyboard input by providing methods to read different data types. To use it, one needs to instantiate a Scanner object, typically associated with the System.in stream, which represents the standard input (keyboard). The next() method reads a single word, nextInt() reads an integer, nextDouble() reads a double, and so on. For reading an entire line, nextLine() is used. The class provides robust error handling, allowing developers to check for input mismatches or exceptions. Always remember to close the Scanner object after use to prevent resource leaks.

 

CODE:

import java.util.Scanner;

 

public class SumOfIntegers {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first integer: ");

        int num1 = scanner.nextInt();

        System.out.print("Enter second integer: ");

        int num2 = scanner.nextInt();

        int sum = num1 + num2;

        System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

    }

}



Date: 06/10/2024

PROGRAM – 4

 

AIM: Write a java program for Swapping two numbers using bitwise operator.

 

THEORY:

Swapping two numbers using bitwise operators is a technique that avoids using a temporary variable and leverages bitwise XOR (exclusive OR) operation. XOR is a bitwise operation that returns 1 for bits that are different and 0 for bits that are the same. The key property of XOR is that it is reversible, meaning if you XOR a value with another and then XOR the result with one of the original values, you get the other original value.

In the context of swapping two numbers, let's say `a` and `b`, the steps are as follows:

1. Initialize `a = a ^ b`. At this point, `a` holds the XOR of both `a` and `b`.

2. Initialize `b = a ^ b`. Now, `b` holds the original value of `a`.

3. Initialize `a = a ^ b`. Finally, `a` holds the original value of `b`.

After these operations, the values of `a` and `b` are effectively swapped without using an additional temporary variable.

 

CODE:

public class SwapNumbers {

    public static void main(String[] args) {

        int a = 5, b = 10;

        System.out.println("Before swapping: a = " + a + ", b = " + b);

        a = a ^ b;

        b = a ^ b;

        a = a ^ b;

        System.out.println("After swapping: a = " + a + ", b = " + b);

    }

}



Date: 13/02/2024

PROGRAM – 5

 

AIM: Initialize two-character variables in a program and display the characters in alphabetical order.

 

THEORY:

- Concepts Used: Comparison operators (<), conditional statements (if-else).

- Explanation: The program compares two characters using the less than operator (<) and prints them in alphabetical order using a conditional statement.

 

CODE:

public class CharacterOrder {

 

    public static void main(String[] args) {

 

        char char1 = 'A';

        char char2 = 'B';

 

        System.out.println(

                "Characters in alphabetical order: " + (char1 < char2 ? char1 + " " + char2 : char2 + " " + char1));

 

    }

 

}



Date: 13/02/2024

PROGRAM – 6

 

AIM: Write a program to receive a colour code from the user (an Alphabet).

 

THEORY:

- Concepts Used: User input (Scanner), data types (char).

- Explanation: The program uses the Scanner class to get input from the user, and it utilizes the char data type to store and display a single character.

 

CODE:

import java.util.Scanner;

 

public class ColorCode {

 

    public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a color code (an alphabet): ");

        char colorCode = scanner.next().charAt(0);

 

        System.out.println("Entered color code: " + colorCode);

 

    }

}



Date: 13/02/2024

PROGRAM – 7

 

AIM: Write a program to print even numbers between 23 and 57. Each number should be printed in a separate row.

 

THEORY:

- Concepts Used: Looping (for loop), conditional statements (if).

- Explanation: The program uses a for loop to iterate through the range of numbers and prints only the even ones by checking the condition using an if statement.

 

CODE:

public class EvenNumbers {

 

    public static void main(String[] args) {

        for (int i = 24; i <= 56; i += 2) {

            System.out.println(i);

        }

    }

}



Date: 13/02/2024

PROGRAM – 8

 

AIM: Write a program to print * in Floyd's format (using for and while loop).

 

THEORY:

Floyd's Triangle is a sequence of natural numbers arranged in the shape of a right-angled triangle. Each row represents a line of consecutive numbers, starting from 1. It is a visual pattern frequently used for educational purposes in programming to teach concepts related to nested loops and pattern printing. Floyd's format involves nested loops where the outer loop controls the rows, and the inner loop controls the number of * printed in each row.

 

CODE:

public class FloydsFormat {

    public static void main(String[] args) {

        int n = 5;

 

        System.out.println("Using for loop: ");

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

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

                System.out.print("* ");

            }

            System.out.println();

        }

 

        System.out.println("Using while loop: ");

        int i = 1;

        while (i <= n) {

            int j = 1;

            while (j <= i) {

                System.out.print("* ");

                j++;

            }

            System.out.println();

            i++;

        }

    }

}



Date: 13/02/2024

PROGRAM – 9

 

AIM: Write a Java program to find if the given number is palindrome or not.

 

THEORY:

A palindrome number is a numerical value that remains the same when its digits are reversed. In other words, a palindrome number reads the same backward as forward. For example, 121, 1331, and 454 are palindrome numbers. Checking whether a number is a palindrome often involves reversing its digits and comparing the original and reversed forms.

 

CODE:

import java.util.Scanner;

 

public class PalindromeCheck {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int num = scanner.nextInt();

 

        int originalNum = num;

        int reversedNum = 0;

 

        while (num != 0) {

            int digit = num % 10;

            reversedNum = reversedNum * 10 + digit;

            num /= 10;

        }

 

        if (originalNum == reversedNum) {

            System.out.println("The number is a palindrome.");

        } else {

            System.out.println("The number is not a palindrome.");

        }

 

        scanner.close();

    }

}



Date: 20/02/2024

PROGRAM – 10

 

AIM: Initialize an integer array with ASCII values and print the corresponding character values in a single row.

 

THEORY:

An array is a collection of homogeneous data stored in contiguous memory location. To print character in single row, we use print function instead of println.

 

CODE:

public class ASCIIArray {

    public static void main(String[] args) {

        int[] asciiArray = { 65, 66, 67, 68, 69 };

        for (int value : asciiArray) {

            System.out.print((char) value + " ");

        }

    }

}



Date: 20/02/2024

PROGRAM – 11

 

AIM: Write a program to reverse the elements of a given 2*2 array. Four integer numbers need to be passed as Command-Line arguments.

 

CODE:

public class ReverseArray {

    public static void main(String[] args) {

        if (args.length != 4) {

            System.out.println("Please provide four integer numbers as command-line arguments.");

            return;

        }

 

        int[][] originalArray = { { Integer.parseInt(args[0]), Integer.parseInt(args[1]) },

                { Integer.parseInt(args[2]), Integer.parseInt(args[3]) } };

 

        System.out.println("Original Array:");

        printArray(originalArray);

 

        System.out.println("Reversed Array:");

        reverseArray(originalArray);

        printArray(originalArray);

    }

 

    private static void reverseArray(int[][] array) {

        int temp = array[0][0];

        array[0][0] = array[1][1];

        array[1][1] = temp;

 

        temp = array[0][1];

        array[0][1] = array[1][0];

        array[1][0] = temp;

    }

 

    private static void printArray(int[][] array) {

        for (int[] row : array) {

            for (int element : row) {

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

            }

            System.out.println();

        }

    }

}


Date: 20/02/2024

PROGRAM – 12

 

AIM: Create a java program to implement stack and queue concept.

 

THEORY:

A stack is a data structure that follows the Last In, First Out (LIFO) principle, where the last element added is the first one to be removed. In Java, you can implement a stack using arrays or linked lists. Key operations on a stack include:

  • push(element): Adds an element to the top of the stack.
  • pop(): Removes and returns the element from the top of the stack.
  • peek(): Returns the element at the top of the stack without removing it.
  • isEmpty(): Checks if the stack is empty.
  • size(): Returns the number of elements in the stack.

 

A queue is a data structure that follows the First In, First Out (FIFO) principle, where the first element added is the first one to be removed. Similar to stacks, queues in Java can be implemented using arrays or linked lists. Key operations on a queue include:

  • enqueue(element): Adds an element to the back of the queue.
  • dequeue(): Removes and returns the element from the front of the queue.
  • peek(): Returns the element at the front of the queue without removing it.
  • isEmpty(): Checks if the queue is empty.
  • size(): Returns the number of elements in the queue.

 

 

CODE:

import java.util.LinkedList;

 

class Stack<T> {

    private LinkedList<T> list = new LinkedList<>();

 

    public void push(T element) {

        list.addFirst(element);

    }

 

    public T pop() {

        if (isEmpty()) {

            throw new IllegalStateException("Stack is empty");

        }

        return list.removeFirst();

    }

 

    public T peek() {

        if (isEmpty()) {

            throw new IllegalStateException("Stack is empty");

        }

        return list.getFirst();

    }

 

    public boolean isEmpty() {

        return list.isEmpty();

    }

 

    public int size() {

        return list.size();

    }

}

 

class Queue<T> {

    private LinkedList<T> list = new LinkedList<>();

 

    public void enqueue(T element) {

        list.addLast(element);

    }

 

    public T dequeue() {

        if (isEmpty()) {

            throw new IllegalStateException("Queue is empty");

        }

        return list.removeFirst();

    }

 

    public T peek() {

        if (isEmpty()) {

            throw new IllegalStateException("Queue is empty");

        }

        return list.getFirst();

    }

 

    public boolean isEmpty() {

        return list.isEmpty();

    }

 

    public int size() {

        return list.size();

    }

}

 

public class StackQueueExample {

    public static void main(String[] args) {

 

        Stack<Integer> stack = new Stack<>();

        stack.push(1);

        stack.push(2);

        stack.push(3);

 

        System.out.println("Stack size: " + stack.size());

        System.out.println("Top element of stack: " + stack.peek());

 

        while (!stack.isEmpty()) {

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

        }

 

        Queue<String> queue = new Queue<>();

        queue.enqueue("A");

        queue.enqueue("B");

        queue.enqueue("C");

 

        System.out.println("Queue size: " + queue.size());

        System.out.println("Front element of queue: " + queue.peek());

 

        while (!queue.isEmpty()) {

            System.out.println("Dequeued from queue: " + queue.dequeue());

        }

    }

}


Date: 20/02/2024

PROGRAM – 13

 

AIM: Write a java program to produce the tokens from given long string.

 

THEORY:

We have used StringTokenizer utility package to separate the long string into its tokens.

 

CODE:

import java.util.StringTokenizer;

 

public class TokenizerExample {

    public static void main(String[] args) {

        String longString = "This is a long string with multiple tokens.";

        StringTokenizer tokenizer = new StringTokenizer(longString);

 

        System.out.println("Tokens:");

        while (tokenizer.hasMoreTokens()) {

            System.out.println(tokenizer.nextToken());

        }

    }

}


Date: 20/02/2024

PROGRAM – 14

 

AIM: Using the concept of method overloading Write method for calculating the area of triangle, circle and rectangle. 

 

THEORY:

Method overloading in Java allows a class to have multiple methods with the same name but different parameters. It improves code readability and flexibility, and it is determined at compile-time based on the method signature, considering the number, type, and order of parameters.

 

CODE:

public class ShapeCalculator {

 

    // Calculate area of a triangle

    public double calculateArea(float base, double height, char t) {

        return 0.5 * base * height;

    }

 

    // Calculate area of a circle

    public double calculateArea(double radius) {

        return Math.PI * Math.pow(radius, 2);

    }

 

    // Calculate area of a rectangle

    public double calculateArea(double length, double width) {

        return length * width;

    }

 

    public static void main(String[] args) {

        char t = 0;

        ShapeCalculator calculator = new ShapeCalculator();

 

        // Triangle

        double triangleArea = calculator.calculateArea(5, 8, t);

        System.out.println("Area of Triangle: " + triangleArea);

 

        // Circle

        double circleArea = calculator.calculateArea(4);

        System.out.println("Area of Circle: " + circleArea);

 

        // Rectangle

        double rectangleArea = calculator.calculateArea(6, 9);

        System.out.println("Area of Rectangle: " + rectangleArea);

    }

}



Date: 27/02/2024

PROGRAM – 15

 

AIM: Create a class Box that uses a parameterized constructor to initialize the dimensions of a box. The dimensions of the Box are width, height, depth. The class should have a method that can return the volume of the box. Create an object of the Box class and test the functionalities.

 

THEORY:

In Java, a class serves as a blueprint, encapsulating data and methods, defining the structure and behavior of objects. Objects, instances of classes, represent tangible entities with specific attributes and behaviors. This object-oriented paradigm enhances code modularity, reusability, and the ability to model real-world scenarios effectively.

 

CODE:

public class Box {

    private double width;

    private double height;

    private double depth;

 

    public Box(double width, double height, double depth) {

        this.width = width;

        this.height = height;

        this.depth = depth;

    }

 

    public double calculateVolume() {

        return width * height * depth;

    }

 

    public static void main(String[] args) {

 

        Box myBox = new Box(3, 4, 5);

 

        double volume = myBox.calculateVolume();

        System.out.println("The volume of the box is: " + volume);

    }

}



Date: 27/02/2024

PROGRAM – 16

 

AIM: WAP to display the use of this keyword.

 

THEORY:

In Java, the this keyword refers to the current instance of a class. It is used to distinguish between instance variables and method parameters with the same name, helping in clarifying the scope and avoiding ambiguity. Additionally, this is employed to invoke current object's methods within the class, enhancing code readability and reducing redundancy.

 

CODE:

public class thisDemo {

 

    private int x;

    private int y;

 

    public thisDemo(int x, int y) {

        this.x = x;

        this.y = y;

    }

 

    public void displayCoordinates() {

        System.out.println("Coordinates: x = " + this.x + ", y = " + this.y);

    }

 

    public static void main(String[] args) {

 

        thisDemo myObject = new thisDemo(5, 10);

 

        myObject.displayCoordinates();

    }

}



Date: 27/02/2024

PROGRAM – 17

 

AIM: Write a program that can count the number of instances created for the class.

 

THEORY:

Static variable is used as a counter. The constructor increments the instance count whenever a new object is created. Static variable retains its value across different object instances.

 

CODE:

public class InstanceCounter {

 

    private static int instanceCount = 0;

 

    public InstanceCounter() {

        instanceCount++;

    }

 

    public static int getInstanceCount() {

        return instanceCount;

    }

 

    public static void main(String[] args) {

 

        InstanceCounter obj1 = new InstanceCounter();

        InstanceCounter obj2 = new InstanceCounter();

        InstanceCounter obj3 = new InstanceCounter();

 

        System.out.println("Number of instances created: " + InstanceCounter.getInstanceCount());

    }

}



Date: 27/02/2024

PROGRAM – 18


AIM: Java Program to get the cube of a given number using the static method.


THEORY:

A static method in Java is a method that is part of a class rather than an instance of that class. Every instance of a class has access to the method. Static methods have access to class variables (static variables) without using the class's object (instance). Only static data may be accessed by a static method.

 

CODE:

import java.util.Scanner;

 

public class CubeCalculator {

 

    public static double calculateCube(double number) {

        return Math.pow(number, 3);

    }

 

    public static void main(String[] args) {

 

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

 

        double inputNumber = scanner.nextDouble();

 

        double cubeResult = calculateCube(inputNumber);

 

        System.out.println("Cube of " + inputNumber + " is: " + cubeResult);

 

        scanner.close();

    }

}



05/03/2024

PROGRAM – 19

 

AIM: Implement a Java program demonstrating method overriding. 

 

THEORY:

Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its superclass. It is a way to achieve runtime polymorphism. The overridden method in the subclass should have the same signature (name, return type, and parameters) as the method in the superclass.

 

CODE:

class MethodOverriding {

    void makeSound() {

        System.out.println("Some generic sound");

    }

}

 

class Dog extends MethodOverriding {

   

    void makeSound() {

        System.out.println("Bark! Bark!");

    }

}

 

public class MethodOverridingExample {

    public static void main(String[] args) {

        MethodOverriding animal = new MethodOverriding();

        animal.makeSound();

 

        Dog dog = new Dog();

        dog.makeSound();

 

        MethodOverriding anotherDog = new Dog();

        anotherDog.makeSound();

    }

}



05/03/2024

PROGRAM – 20

 

AIM: Implement a Java program illustrating simple inheritance. 

 

THEORY:

Inheritance in Java allows a class (subclass or derived class) to inherit the properties and behaviors of another class (superclass or base class). The subclass can reuse the code of the superclass and extend its functionality. In simple inheritance, there is only one level of hierarchy between the classes.

 

CODE:

class Vehicle {

    void start() {

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

    }

 

    void stop() {

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

    }

}

 

class Car extends Vehicle {

    void drive() {

        System.out.println("Car is driving");

    }

}

 

public class SimpleInheritanceExample {

    public static void main(String[] args) {

        Car myCar = new Car();

        myCar.start();

        myCar.drive();

        myCar.stop();

    }

}



05/03/2024

PROGRAM – 21

 

AIM: Implement a Java program illustrating multilevel inheritance.    

 

THEORY:

Multilevel inheritance in Java involves a chain of inheritance with more than two classes. Each subclass inherits from its immediate superclass, creating a hierarchy. In multilevel inheritance, a class extends another class, and a third class extends the second class.

 

CODE:

 

class Animal {

    void eat() {

        System.out.println("Animal is eating");

    }

}

 

class Mammal extends Animal {

    void sleep() {

        System.out.println("Mammal is sleeping");

    }

}

 

class Dog extends Mammal {

    void bark() {

        System.out.println("Dog is barking");

    }

}

 

public class MultilevelInheritanceExample {

    public static void main(String[] args) {

        Dog myDog = new Dog();

        myDog.eat();

        myDog.sleep();

        myDog.bark();

    }

}



05/03/2024

PROGRAM – 22

 

AIM: Implement a Java program illustrating all uses of the `super` keyword. 

 

THEORY:

The `super` keyword in Java is used to refer to the immediate parent class object or invoke the parent class methods and fields. It is mainly used in the context of inheritance. There are three primary uses of the `super` keyword:

1. To call the parent class constructor.

2. To invoke the parent class method.

3. To access the parent class fields.

 

CODE:

class Parent {

    int parentField;

 

    Parent(int field) {

        this.parentField = field;

    }

 

    void display() {

        System.out.println("Parent class display method");

    }

}

 

class Child extends Parent {

    int childField;

 

    Child(int parentField, int childField) {

        super(parentField);

        this.childField = childField;

    }

 

    void display() {

        super.display();

        System.out.println("Child class display method");

    }

 

    void accessParentField() {

        System.out.println("Parent field value: " + super.parentField);

    }

}

 

public class superKeywordExample {

    public static void main(String[] args) {

        Child myChild = new Child(10, 20);

        myChild.display();

        myChild.accessParentField();

    }

}



05/03/2024

PROGRAM – 23

 

AIM: Implement a Java program to demonstrate dynamic polymorphism using interfaces.    

 

THEORY:

Dynamic polymorphism in Java is achieved through method overriding. Interfaces provide a way to achieve abstraction and support multiple inheritances. Dynamic polymorphism allows a reference variable of the superclass/interface to refer to an object of any subclass that implements the interface.

 

CODE:

interface Shape {

    void draw();

}

 

class Circle implements Shape {

 

    public void draw() {

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

    }

}

 

class Square implements Shape {

 

    public void draw() {

        System.out.println("Drawing a Square");

    }

}

 

public class DPIE {

    public static void main(String[] args) {

        Shape circle = new Circle();

        Shape square = new Square();

 

        drawShape(circle);

        drawShape(square);

    }

 

    static void drawShape(Shape shape) {

        shape.draw();

    }

}

 

 



Comments

Popular Posts