Java Programming Exercises and Core Concepts

String Length Calculation in Java

Q.1(c) Write a program to calculate the length of a string.

import java.util.*;

class StringLength {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String str;
        System.out.println("Enter a string:");
        str = sc.nextLine();
        System.out.println("String length=" + str.length());
    }
}

Command Line Arguments for Addition

Q. 2(b) Write a program using command line arguments to add two numbers.

public class Exercise3 {
    public static void main(String[] args) {
        int a, b;
        if (args.length != 2) {
            System.out.println("Wrong Number of Command Line Arguments!\nExiting...");
            System.exit(0);
        }
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        System.out.println("Sum of " + a + " and " + b + " is " + (a + b));
    }
}

Java Packages and Circle Area Calculation

Q. 4(a) Design a package containing a class which defines a method to find the area of a circle. Import it into a Java application to calculate the area of a circle.

Step 1: Create a folder named shapes

File 1: Circle.java – inside shapes folder

package shapes;

public class Circle {
    public double area(double r) {
        return 3.14 * r * r;
    }
}

Step 2: Create Main file – outside shapes folder

File 2: Main.java

import shapes.Circle;

class Main {
    public static void main(String args[]) {
        Circle c = new Circle();
        System.out.println("Area=" + c.area(10));
    }
}

Custom Exceptions and Thread Execution

class MyException extends Exception {}

class A extends Thread {
    public void run() {
        System.out.println("Thread");
    }

    public static void main(String a[]) {
        new A().start();
        try {
            throw new MyException();
        } catch (MyException e) {
            System.out.println("Custom");
        } catch (Exception e) {
            // Handle other exceptions
        } finally {
            System.out.println("End");
        }
    }
}

Abstract Classes and Inheritance

abstract class A {
    int x = 10;
    abstract void show();
}

class B extends A {
    final int y = 20;
    B() {
        super();
    }
    void show() {
        System.out.println(x + y);
    }
}

public class Demo {
    public static void main(String a[]) {
        A o = new B();
        o.show();
        int p[] = {1, 2};
        int q[][] = {{1, 2}, {3, 4}};
        Integer i = 10;
        System.out.println(i);
    }
}

Functional Interfaces and Lambda Expressions

(Interface + Static Method + Functional Interface + Lambda + Multiple Inheritance)

@FunctionalInterface
interface A {
    void show();
    static void s() {
        System.out.println("Static");
    }
}

interface B {
    void display();
}

class C implements A, B {
    public void show() {
        System.out.println("Show");
    }
    public void display() {
        System.out.println("Display");
    }
    public static void main(String a[]) {
        C c = new C();
        c.show();
        c.display();
        A.s();
        A x = () -> System.out.println("Lambda");
        x.show();
    }
}

Java Development Kit (JDK)

The JDK (Java Development Kit) was developed by Sun Microsystems. The Java Development Kit is a toolkit required on your system for programming in Java. It mainly contains the Java compiler (javac), which is used to compile Java programs. Besides the compiler, it also contains many packages that provide built-in classes and methods. The package java.lang contains the System class used to display data. The package java.util contains many utility classes used in Java programming.

Torque Calculation Assignment Statement

1(c) Write a Java assignment statement to evaluate the following expression:

Torque = (2 * m1 * m2) / (m1 + m2) * g

import java.util.*;

class Q1C {
    public static void main(String args[]) {
        double m1, m2, Torque;
        double g = 9.81;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter 1st mass ");
        m1 = sc.nextFloat();
        System.out.println("Enter 2nd mass ");
        m2 = sc.nextFloat();
        Torque = ((2 * m1 * m2) / (m1 + m2)) * g;
        System.out.println("Torque is " + Torque);
    }
}

Java Virtual Machine (JVM)

JVM (Java Virtual Machine) is an interpreter and the main component of Java. It makes Java platform-independent by converting bytecode into machine code suitable for the target system. Java source code is saved with the .java extension. The Java compiler (javac) compiles the source code into bytecode. The bytecode is stored in a .class file. The same .class file can run on any system that has a JVM. This makes Java portable and architecture-neutral. The source code is generally not distributed to customers; only the compiled .class file is shared, protecting the original program. The JVM interprets the bytecode and executes the program on the target machine.

Introduction to Exception Handling

5.1 Overview

  • Exception handling refers to the handling of abnormal or unexpected events.
  • Some abnormal conditions are known to the Java compiler, while some occur during runtime and are unknown to the compiler.
  • ‘Exception’ is a class, and it has subclasses.
  • An exception is an error condition occurrence. Example: Entering a character when an integer is expected causes a NumberFormatException.

5.2.1 Checked Exceptions

  • All checked exceptions are subclasses of the class Exception.
  • Checked exceptions require programmers to handle the exception that may be thrown.
  • Example: An IOException caused by the readLine() method is a checked exception.

5.2.2 Unchecked Exceptions

  • Unchecked exceptions are RuntimeException and its subclasses.
  • The compiler does not check for unchecked exceptions and does not require programmers to handle them.
  • Programmers may not even know that such an exception would be thrown.

Life Cycle of a Thread in Java

BONUS Q) Explain the Life Cycle of a Thread in Java [7M]

Definition

A thread in Java passes through various stages from its creation to termination. These stages together are called the Life Cycle of a Thread. Java provides the java.lang.Thread class to manage the thread life cycle.

States in the Thread Life Cycle

  1. New State: A thread is created using the new keyword. The thread object is created, but the start() method is not yet called. The thread is not yet scheduled for execution.
  2. Runnable State: A thread enters the Runnable state when the start() method is called. The thread is ready to run but waiting for the CPU to be allocated. The thread scheduler decides which runnable thread gets the CPU.
  3. Running State: A thread is in the Running state when it actually gets the CPU and executes. The run() method is being executed. Only one thread runs at a time on a single CPU.
  4. Blocked / Waiting State: A thread moves to the Blocked state temporarily when waiting for I/O, waiting for a lock, sleep() is called, or wait() is called. After the blocking condition is over, the thread moves back to the Runnable state.
  5. Dead State: A thread enters the Dead state when the run() method completes execution normally or an unhandled exception occurs. Once dead, a thread CANNOT be restarted.