Question Bank › Technical › Java › Coding Questions
Write a Java program that demonstrates the use of a break statement inside an inner loop. The program should have an outer loop iterating from 1 to 4 and an inner loop iterating from 1 to 4. When the outer loop variable is 3 and the inner loop variable is 2, break out of the inner loop only. Otherwise, print the values of the outer and inner loop variables separated by a space.
public class InnerBreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
if (i == 3 && j == 2) {
break;
}
System.out.println(i + " " + j);
}
}
}
}Write a Java program that reads the data of two files, source1.txt and source2.txt, and writes their combined content into a third file called merged.txt using SequenceInputStream. After copying all bytes, print "Done" to the console and close all the streams.
import java.io.*;
public class MergeFiles {
public static void main(String[] args) throws Exception {
FileInputStream fin1 = new FileInputStream("source1.txt");
FileInputStream fin2 = new FileInputStream("source2.txt");
FileOutputStream fout = new FileOutputStream("merged.txt");
SequenceInputStream sis = new SequenceInputStream(fin1, fin2);
int i;
while ((i = sis.read()) != -1) {
fout.write(i);
}
sis.close();
fout.close();
fin1.close();
fin2.close();
System.out.println("Done");
}
}Write a Java program that demonstrates throwing an unchecked exception. Create a class named VotingCheck with a static method verify(int age). If age is less than 18, throw a new ArithmeticException with the message "Citizen is not eligible to vote"; otherwise print "Citizen is eligible to vote!!". In main(), call verify(15) and then print "rest of the code...".
public class VotingCheck {
// method to check voting eligibility
public static void verify(int age) {
if (age < 18) {
// throw unchecked ArithmeticException if not eligible
throw new ArithmeticException("Citizen is not eligible to vote");
} else {
System.out.println("Citizen is eligible to vote!!");
}
}
// main method
public static void main(String args[]) {
// calling the method
verify(15);
System.out.println("rest of the code...");
}
}Write a Java program where the `main` method is placed in a class different from the class being used. Create a class `Employee` with an `int` field `empId` and a `String` field `empName` (do not assign any values). In another class `TestEmployee` that contains the `main` method, create one `Employee` object and print its `empId` and `empName` on separate lines.
class Employee {
int empId;
String empName;
}
class TestEmployee {
public static void main(String args[]) {
Employee e1 = new Employee();
System.out.println(e1.empId);
System.out.println(e1.empName);
}
}Write a Java program that demonstrates initializing an object through a reference variable. Create a class named `Book` with two fields: an `int` field `pages` and a `String` field `title`. In a separate class `TestBook` containing the `main` method, create one `Book` object, assign `pages = 250` and `title = "Wings of Fire"` using the reference variable, then print both members separated by a space.
class Book {
int pages;
String title;
}
class TestBook {
public static void main(String args[]) {
Book b1 = new Book();
b1.pages = 250;
b1.title = "Wings of Fire";
System.out.println(b1.pages + " " + b1.title);
}
}Write a Java program that demonstrates the use of an anonymous object. Create a class named FactorialCalc with a method computeFact(int n) that prints the factorial of n. In the main method, call computeFact(6) using an anonymous object (i.e., without storing the object in a reference variable).
class FactorialCalc {
void computeFact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("factorial is " + fact);
}
public static void main(String args[]) {
new FactorialCalc().computeFact(6); // calling method with anonymous object
}
}Write a Java program that joins two strings using the + operator. Create the string "Virat" and the string " Kohli" and combine them into one string, then print it.
class TestConcatOperator {
public static void main(String args[]) {
String s = "Virat" + " Kohli";
System.out.println(s);
}
}Write a Java program that concatenates two strings using the StringBuilder class and its append() method. Create a StringBuilder with "Vanakkam" and another with " India", append the second to the first, and print the resulting string. Name the class BuildGreet.
public class BuildGreet
{
public static void main(String args[])
{
StringBuilder s1 = new StringBuilder("Vanakkam"); // String 1
StringBuilder s2 = new StringBuilder(" India"); // String 2
StringBuilder s = s1.append(s2); // String 3 stores the result
System.out.println(s.toString()); // Displays result
}
}Write a Java program that concatenates two strings using the String.format() method with the %s format specifier. Create two String objects: one holding "Namaste" and another holding " Bharat", then use String.format("%s%s", ...) to join them and print the result. Name the class GreetFormat.public class GreetFormat
{
public static void main(String args[])
{
String s1 = new String("Namaste"); // String 1
String s2 = new String(" Bharat"); // String 2
String s = String.format("%s%s", s1, s2); // String 3 stores the result
System.out.println(s); // Displays result
}
}Write a Java program that uses the String.join() method (Java 8+) to concatenate the strings "Ram" and "Lakshman" with a hyphen ("-") as the separator, and then print the resulting string. The program should output: Ram-Lakshmanpublic class JodhString {
public static void main(String[] args) {
String s1 = new String("Ram");
String s2 = new String("Lakshman");
String result = String.join("-", s1, s2);
System.out.println(result);
}
}Write a Java program that uses the StringJoiner class (Java 8+) to concatenate the strings "Namaste" and "Duniya" with a comma and a space as the delimiter, and then print the resulting string. The program should output: Namaste, Duniya
import java.util.StringJoiner;
public class DeshJoiner {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(", ");
sj.add("Namaste");
sj.add("Duniya");
System.out.println(sj.toString());
}
}Write a Java program that creates a List of Strings containing "red", "green", "blue" and uses the Collectors.joining() method (Java 8+) to join them into a single string separated by " - ". Print the resulting string.
import java.util.*;
import java.util.stream.Collectors;
public class JoinDemo {
public static void main(String args[]) {
List<String> colours = Arrays.asList("red", "green", "blue");
String result = colours.stream().collect(Collectors.joining(" - "));
System.out.println(result);
}
}Write a Java program where a parent class Vehicle has a String field named brand set to "Maruti", and a child class Car extends Vehicle and also declares a String field named brand set to "Hyundai". The child class should have a method showBrands() that prints the child's brand first and then the parent's brand using the super keyword. In main, create a Car object and call showBrands().
class Vehicle {
String brand = "Maruti";
}
class Car extends Vehicle {
String brand = "Hyundai";
void showBrands() {
System.out.println(brand);
System.out.println(super.brand);
}
}
public class TestSuperDemo {
public static void main(String args[]) {
Car c = new Car();
c.showBrands();
}
}Write a Java program that demonstrates using the super keyword to invoke a parent class method. Create a parent class Person with a method display() that prints "Person displays". Create a child class Student that extends Person and overrides display() to print "Student displays". Also add a method show() in Student that calls the parent's display() using super.display() and then calls the child's display(). In the main method, create a Student object and call show().
class Person {
void display() {
System.out.println("Person displays");
}
}
class Student extends Person {
@Override
void display() {
System.out.println("Student displays");
}
void show() {
super.display();
display();
}
}
public class TestSuperMethod {
public static void main(String[] args) {
Student s = new Student();
s.show();
}
}Write a Java program that demonstrates using the super keyword to invoke a parent class constructor. Create a parent class Vehicle with a constructor that prints "Vehicle is created". Create a child class Car that extends Vehicle, and its constructor should call the parent constructor using super() and then print "Car is created". In the main method, create an object of Car.
class Vehicle {
Vehicle() {
System.out.println("Vehicle is created");
}
}
class Car extends Vehicle {
Car() {
super();
System.out.println("Car is created");
}
}
public class TestSuper {
public static void main(String[] args) {
Car c = new Car();
}
}Write a Java program to demonstrate that the compiler automatically inserts a call to super() in a constructor if there is no explicit call to super() or this(). Create a parent class 'LivingThing' with a no-argument constructor that prints "LivingThing created". Create a child class 'Human' that extends 'LivingThing' with a no-argument constructor that prints "Human created". In the main method, create an object of Human and observe the output.
class LivingThing {
LivingThing() {
System.out.println("LivingThing created");
}
}
class Human extends LivingThing {
Human() {
System.out.println("Human created");
}
}
public class TestSuperImplicit {
public static void main(String[] args) {
Human h = new Human();
}
}Write a Java program that shows how to write documentation comments for the javadoc tool. Create a class named `Calculator` in package `com.india` with a documentation comment describing the class. Add a method `square(int n)` that prints the square of `n`, and put a documentation comment above the method describing what it does.
package com.india;
/** This class is a user-defined class that contains one method square. */
public class Calculator {
/** The square method prints the square of the given number */
public static void square(int n) {
System.out.println(n * n);
}
}Write a Java program that uses Javadoc comments to document a class and its methods. The program should calculate the sum of two integers and print the result. Include appropriate Javadoc tags such as @author, @version, @since, @param, and @return. Use the class name 'Calculator' and the method name 'add'. The main method should create an object and call add(25, 35).
import java.io.*;
/**
* <h2>Addition of numbers</h2>
* This program demonstrates the use of Javadoc comments.
* It adds two integers and prints the result.
* <p>
* <b>Note:</b> Comments improve code readability.
*
* @author Ravi
* @version 1.0
* @since 2023-01-01
*/
public class Calculator {
/**
* This method calculates the sum of two integers.
* @param a This is the first parameter to add() method
* @param b This is the second parameter to add() method
* @return int This returns the sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
/**
* This is the main method which makes use of add() method.
* @param args Unused
* @see IOException
*/
public static void main(String[] args) {
Calculator calc = new Calculator();
int result = calc.add(25, 35);
System.out.println("Sum of numbers: " + result);
}
}Write a Java program that uses a for loop to print the numbers 1 to 15, but skips printing the number 9 by using the continue statement. Name the class SkipNineFor.
public class SkipNineFor {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
if (i == 9) {
continue;
}
System.out.println(i);
}
}
}Write a Java program that uses a while loop to print the numbers 1 to 12, but skips printing the number 7 by using the continue statement. Name the class SkipSevenWhile.
public class SkipSevenWhile {
public static void main(String[] args) {
int i = 1;
while (i <= 12) {
if (i == 7) {
i++;
continue;
}
System.out.println(i);
i++;
}
}
}Write a Java program where a class named MyTask extends Thread and overrides run() to print "task running...". In main, create a MyTask object and call its run() method directly (not start()). Explain that run() executes on the current call stack instead of a new thread.
class MyTask extends Thread {
public void run() {
System.out.println("task running...");
}
public static void main(String args[]) {
MyTask t1 = new MyTask();
t1.run(); // runs on the main thread's call stack, no new thread
}
}Write a Java program that demonstrates a final method. Create a class Scooter with a final method start() that prints "Scooter started". Create a subclass ElectricScooter that tries to define its own method with the same name start() — this should fail to compile because start() is final. To keep the program compiling, instead give ElectricScooter a different method charge() that prints "Charging battery", and in main create an ElectricScooter object and call start() and charge().
class Scooter {
final void start() {
System.out.println("Scooter started");
}
}
class ElectricScooter extends Scooter {
void charge() {
System.out.println("Charging battery");
}
}
public class Main {
public static void main(String[] args) {
ElectricScooter e = new ElectricScooter();
e.start();
e.charge();
}
}Write a Java program that demonstrates a final class. Create a final class named Vehicle with a method showType() that prints "This is a vehicle". Then create a class Car (which cannot extend Vehicle because Vehicle is final) that has its own method showBrand() printing "Maruti Suzuki". In the main method, create an object of Car and call both showBrand() and, using a Vehicle object, call showType().
final class Vehicle {
void showType() {
System.out.println("This is a vehicle");
}
}
class Car {
void showBrand() {
System.out.println("Maruti Suzuki");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.showBrand();
Vehicle v = new Vehicle();
v.showType();
}
}Write a Java program to demonstrate that a final method is inherited but cannot be overridden. Create a class Vehicle with a final method run() that prints "Vehicle is running". Then create a subclass Car that extends Vehicle. In the main method of Car, create an object of Car and call the run() method.
class Vehicle {
final void run() {
System.out.println("Vehicle is running");
}
}
class Car extends Vehicle {
public static void main(String[] args) {
Car c = new Car();
c.run();
}
}Write a Java program to demonstrate a blank final variable. Create a class Employee with fields id (int), name (String), and a final field aadhaarNumber (String) that is not initialized at declaration. Initialize aadhaarNumber in the constructor. In the main method, create an Employee object with id 101, name "Ramesh", and aadhaarNumber "1234-5678-9012", then print the details.
class Employee {
int id;
String name;
final String aadhaarNumber;
Employee(int id, String name, String aadhaarNumber) {
this.id = id;
this.name = name;
this.aadhaarNumber = aadhaarNumber;
}
void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Aadhaar Number: " + aadhaarNumber);
}
public static void main(String[] args) {
Employee emp = new Employee(101, "Ramesh", "1234-5678-9012");
emp.display();
}
}Write a Java program that shows a blank final variable being initialized in a constructor. Create a class 'Car' with a final int variable 'topSpeed' that is not initialized at declaration; initialize it to 120 inside the constructor and print it. In main, create one Car object.
class Car {
final int topSpeed; // blank final variable
Car() {
topSpeed = 120;
System.out.println(topSpeed);
}
public static void main(String args[]) {
new Car();
}
}Write a Java program that demonstrates the use of a final parameter. Create a class FinalParameterDemo with a method cube that takes a final int parameter n and returns n*n*n. In the main method, create an object and call cube(4), then print the result. Also, show what happens if you try to modify n inside the method (comment out the modification).
public class FinalParameterDemo {
int cube(final int n) {
// n = n + 2; // This would cause a compile-time error: cannot assign a value to final variable n
return n * n * n;
}
public static void main(String[] args) {
FinalParameterDemo demo = new FinalParameterDemo();
int result = demo.cube(4);
System.out.println("Cube of 4 is: " + result);
}
}Write a Java program that creates a ByteArrayInputStream from the byte array {65, 66, 67, 68} and reads it byte by byte, printing each byte's numeric value and its corresponding character, until the end of the stream is reached.import java.io.*;
public class ByteArrayReadExample {
public static void main(String[] args) throws IOException {
byte[] data = { 65, 66, 67, 68 };
ByteArrayInputStream stream = new ByteArrayInputStream(data);
int value = 0;
while ((value = stream.read()) != -1) {
char ch = (char) value;
System.out.println("Byte value is: " + value + "; Character is: " + ch);
}
}
}Write a Java program that receives exactly one command-line argument (a student's name) and prints it in the format: "The student name is: <name>". The program should read the first argument passed from the command prompt.
public class StudentArgExample {
public static void main(String[] args) {
System.out.println("The student name is: " + args[0]);
}
}Write a Java program that accepts any number of command-line arguments and prints each one on a separate line using a for loop that traverses the args array. For example, if run as `java Demo Delhi Mumbai Chennai`, it should print Delhi, Mumbai and Chennai each on its own line.
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}Write a Java program that shows the usage of the join() method. Create a class named TaskRunner that extends Thread and overrides run() to loop j from 0 to 1 (i.e., j < 2). Inside the loop, sleep the thread for 400 milliseconds inside a try-catch, then print the current thread name using Thread.currentThread().getName(), and finally print the value of j. In main, create two threads t1 and t2 of type TaskRunner, start both, call join() on each inside try-catch blocks, and then print "Both threads have finished". Name the file JoinDemo.java.
public class JoinDemo {
static class TaskRunner extends Thread {
public void run() {
for (int j = 0; j < 2; j++) {
try {
Thread.sleep(400);
System.out.println("The current thread name is: " + Thread.currentThread().getName());
} catch (Exception e) {
System.out.println("The exception has been caught: " + e);
}
System.out.println(j);
}
}
}
public static void main(String[] args) {
TaskRunner t1 = new TaskRunner();
TaskRunner t2 = new TaskRunner();
t1.start();
t2.start();
try {
t1.join();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
try {
t2.join();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
System.out.println("Both threads have finished");
}
}Write a Java program named JoinWaitDemo.java that creates three threads of the same class. Each thread's run() method prints the numbers 1 to 3, pausing 300 milliseconds before each number. In main, start the first thread and call join() on it with no timeout (handling InterruptedException), then start the second and third threads.
class JoinWaitDemo extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
JoinWaitDemo t1 = new JoinWaitDemo();
JoinWaitDemo t2 = new JoinWaitDemo();
JoinWaitDemo t3 = new JoinWaitDemo();
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
System.out.println(e);
}
t2.start();
t3.start();
}
}Write a Java program that demonstrates the use of a predefined (built-in) method. Use the Math.max() method from the Java class library to find the larger of the two numbers 15 and 22, and print the result to the console in the format: The larger number is: <result>
public class MaxDemo
{
public static void main(String[] args)
{
// using the predefined max() method of the Math class
System.out.print("The larger number is: " + Math.max(15, 22));
}
}Write a Java program named PosNeg.java that reads an integer from the user and calls a user-defined method checkSign(int n) to print whether the number is positive or negative. For example, if the user enters 27 the output should be '27 is positive', and if the user enters -14 the output should be '-14 is negative'.
import java.util.Scanner;
public class PosNeg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
checkSign(num);
}
public static void checkSign(int n) {
if (n >= 0)
System.out.println(n + " is positive");
else
System.out.println(n + " is negative");
}
}Write a Java program that demonstrates an instance method. Create a class Calculator with an instance (non-static) method multiply(int a, int b) that stores the product in a field and returns it. In main, create an object of Calculator and print the result of multiplying 14 and 6 by invoking the instance method.
public class Calculator {
int result;
// instance method (no static keyword)
public int multiply(int a, int b) {
result = a * b;
return result;
}
public static void main(String[] args) {
// creating an object of the class
Calculator obj = new Calculator();
// invoking the instance method
System.out.println("The product is: " + obj.multiply(14, 6));
}
}Write a Java program that demonstrates accessor (getter) and mutator (setter) methods. Create a class named Employee with private fields empId (int) and empName (String). Provide getEmpId(), setEmpId(int), getEmpName(), setEmpName(String) methods, and a display() method that prints the employee id and name. In main, create an Employee object, set empId to 104 and empName to "Rohan", then call display().
public class Employee {
private int empId;
private String empName;
public int getEmpId() { // accessor method
return empId;
}
public void setEmpId(int empId) { // mutator method
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public void display() {
System.out.println("Employee id: " + empId);
System.out.println("Employee name: " + empName);
}
public static void main(String[] args) {
Employee e = new Employee();
e.setEmpId(104);
e.setEmpName("Rohan");
e.display();
}
}Write a Java program in a file ShapeDemo.java that declares an abstract class Shape containing an abstract method void draw(); then create a subclass Circle that implements draw() to print "Drawing a circle". In main(), create a Shape reference pointing to a Circle object and call draw().
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
public class ShapeDemo {
public static void main(String args[]) {
Shape obj = new Circle();
obj.draw();
}
}Write a Java program named ThreadNamingDemo.java that creates two threads by extending the Thread class. Print the default names of both threads, start both threads (each thread's run() should print "working..."), then rename the first thread to "Ravi Kumar" using setName() and print its new name.
class ThreadNamingDemo extends Thread {
public void run() {
System.out.println("working...");
}
public static void main(String args[]) {
ThreadNamingDemo t1 = new ThreadNamingDemo();
ThreadNamingDemo t2 = new ThreadNamingDemo();
System.out.println("Name of t1: " + t1.getName());
System.out.println("Name of t2: " + t2.getName());
t1.start();
t2.start();
t1.setName("Ravi Kumar");
System.out.println("After changing name of t1: " + t1.getName());
}
}Write a Java program named WorkerNameDemo.java that sets a thread's name at the time of creation without using setName(). Create a class WorkerName that extends Thread, with a constructor WorkerName(String threadName) that passes the name to the superclass constructor using super(threadName). Override run() to print "The worker thread is running....". In main(), create a WorkerName object with the name "ReportThread" and start it.
class WorkerName extends Thread {
WorkerName(String threadName) {
super(threadName);
}
public void run() {
System.out.println("The worker thread is running....");
}
}
public class WorkerNameDemo {
public static void main(String args[]) {
WorkerName t = new WorkerName("ReportThread");
t.start();
}
}Write a Java program named ThreadInfoDemo.java that demonstrates the Thread.currentThread() method. Create a class ThreadInfoDemo that extends Thread and overrides run() to print the name of the currently executing thread using Thread.currentThread().getName(). In main(), create two ThreadInfoDemo objects and start both threads.
class ThreadInfoDemo extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]) {
ThreadInfoDemo t1 = new ThreadInfoDemo();
ThreadInfoDemo t2 = new ThreadInfoDemo();
t1.start();
t2.start();
}
}Write a Java program that demonstrates thread priorities. Create a class named PriorityCheck that extends Thread and overrides run() to print "Running in run method". In main, create three threads t1, t2, t3 of this class. First print the default priority of t1, t2 and t3. Then set the priorities: t1 to 7, t2 to 2 and t3 to 9. Finally print the priority of each thread again.
public class PriorityCheck extends Thread {
public void run() {
System.out.println("Running in run method");
}
public static void main(String[] args) {
PriorityCheck t1 = new PriorityCheck();
PriorityCheck t2 = new PriorityCheck();
PriorityCheck t3 = new PriorityCheck();
System.out.println("Default priority of t1: " + t1.getPriority());
System.out.println("Default priority of t2: " + t2.getPriority());
System.out.println("Default priority of t3: " + t3.getPriority());
t1.setPriority(7);
t2.setPriority(2);
t3.setPriority(9);
System.out.println("Priority of t1: " + t1.getPriority());
System.out.println("Priority of t2: " + t2.getPriority());
System.out.println("Priority of t3: " + t3.getPriority());
}
}Write a Java program that demonstrates the String substring() method. Take the string "ViratKohli", print the original string, print the substring starting from index 5, and print the substring from index 0 to 5. Name the class SubstringDemo.
public class SubstringDemo{
public static void main(String args[]){
String s="ViratKohli";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 5: " + s.substring(5)); //Kohli
System.out.println("Substring starting from index 0 to 5: " + s.substring(0,5)); //Virat
}
}Write a Java program that uses the String.split() method to break a sentence into parts. Take the sentence "Ravi, My friend is Arjun" and split it using a dot (".") as the delimiter (regular expression), then print the resulting array using Arrays.toString(). Name the class SplitDemo.import java.util.*;
public class SplitDemo
{
public static void main(String args[])
{
String text = new String("Ravi, My friend is Arjun");
/* Splits the sentence by the delimiter passed as an argument */
String[] parts = text.split("\\.");
System.out.println(Arrays.toString(parts));
}
}Write a Java program that creates a class named `Train` with a no-argument constructor. The constructor should print the message "Train is ready". In the main method, create one object of the Train class so the constructor is invoked.
class Train {
Train() {
System.out.println("Train is ready");
}
public static void main(String args[]) {
Train t = new Train();
}
}Write a Java program that demonstrates a default constructor displaying default values. Create a class named `CricketPlayer` with fields `runs` (int) and `playerName` (String). Do not assign any values to these fields. Create two objects of the class and display their field values to show the default values provided by Java.
class CricketPlayer {
int runs;
String playerName;
void display() {
System.out.println(runs + " " + playerName);
}
public static void main(String args[]) {
CricketPlayer p1 = new CricketPlayer();
CricketPlayer p2 = new CricketPlayer();
p1.display();
p2.display();
}
}Write a Java program that demonstrates a parameterized constructor. Create a class named Book with fields bookId (int) and title (String). Define a constructor that takes two parameters and assigns them to the fields. Add a display() method that prints bookId and title separated by a space. In main, create two Book objects: one with (101, "Wings of Fire") and another with (102, "Discovery of India"), then call display() on both.
class Book {
int bookId;
String title;
// parameterized constructor
Book(int id, String t) {
bookId = id;
title = t;
}
void display() {
System.out.println(bookId + " " + title);
}
public static void main(String args[]) {
Book b1 = new Book(101, "Wings of Fire");
Book b2 = new Book(102, "Discovery of India");
b1.display();
b2.display();
}
}Write a Java program that demonstrates constructor overloading. Create a class named Employee with fields empId (int), empName (String) and salary (int). Provide a two-argument constructor that sets empId and empName, and a three-argument constructor that sets empId, empName and salary. Add a display() method that prints the three fields separated by spaces. In main, create one Employee using the two-argument constructor with values (501, "Rohit") and another using the three-argument constructor with values (502, "Sneha", 45000), then call display() on both.
class Employee {
int empId;
String empName;
int salary;
// two-argument constructor
Employee(int id, String name) {
empId = id;
empName = name;
}
// three-argument constructor
Employee(int id, String name, int sal) {
empId = id;
empName = name;
salary = sal;
}
void display() {
System.out.println(empId + " " + empName + " " + salary);
}
public static void main(String args[]) {
Employee e1 = new Employee(501, "Rohit");
Employee e2 = new Employee(502, "Sneha", 45000);
e1.display();
e2.display();
}
}Write a Java program to copy the values of one object into another using a constructor (similar to a copy constructor). Create a class Book with fields bookId (int) and title (String). Provide a parameterized constructor to initialize these fields and another constructor that takes a Book object and copies its field values. In the main method, create a Book object b1 with id 301 and title "Java Basics", then create b2 using the copy constructor with b1. Display the details of both objects.
class Book {
int bookId;
String title;
Book(int id, String t) {
bookId = id;
title = t;
}
Book(Book b) {
bookId = b.bookId;
title = b.title;
}
void display() {
System.out.println(bookId + " " + title);
}
public static void main(String[] args) {
Book b1 = new Book(301, "Java Basics");
Book b2 = new Book(b1);
b1.display();
b2.display();
}
}Write a Java program to copy the values of one object into another by assigning the fields directly, without using a constructor. Create a class Employee with fields empId (int) and empName (String). Provide a parameterized constructor to initialize these fields and a no-argument constructor. In the main method, create an Employee object e1 with id 201 and name "Rahul", and another Employee object e2 using the no-argument constructor. Then copy the values from e1 to e2 by assigning each field individually. Finally, display the details of both objects.
class Employee {
int empId;
String empName;
Employee(int id, String name) {
empId = id;
empName = name;
}
Employee() {}
void display() {
System.out.println(empId + " " + empName);
}
public static void main(String[] args) {
Employee e1 = new Employee(201, "Rahul");
Employee e2 = new Employee();
e2.empId = e1.empId;
e2.empName = e1.empName;
e1.display();
e2.display();
}
}Write a Java program (file: WorkerThread.java) that demonstrates a simple daemon thread. Create a class WorkerThread extending Thread whose run() checks Thread.currentThread().isDaemon() and prints "daemon thread work" if true, otherwise "user thread work". In main, create three WorkerThread objects, mark only the first one as a daemon using setDaemon(true), then start all three.
public class WorkerThread extends Thread {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("daemon thread work");
} else {
System.out.println("user thread work");
}
}
public static void main(String[] args) {
WorkerThread t1 = new WorkerThread();
WorkerThread t2 = new WorkerThread();
WorkerThread t3 = new WorkerThread();
t1.setDaemon(true); // t1 becomes a daemon thread
t1.start();
t2.start();
t3.start();
}
}Write a Java program that demonstrates the use of single-line comments. Declare an integer variable named total with value 250 and print it. Add a single-line comment (starting with //) on the declaration line explaining the variable, and another single-line comment on the print line describing what is being printed.
public class SingleCommentDemo {
public static void main(String[] args) {
int total = 250; // total is a variable with value 250
System.out.println(total); // printing the variable total
}
}Write a Java program that demonstrates the use of multi-line comments. Declare an integer variable named marks with value 85 and print it. Also, inside a multi-line comment (between /* and */), write code that would declare two double variables (for example price = 45.5 and tax = 3.2) and print their sum, so that this commented code is NOT executed. The program should print only the value of marks.
public class CommentDemo {
public static void main(String[] args) {
/* Let's declare and
print a variable in Java. */
int marks = 85;
System.out.println(marks);
/* double price = 45.5;
double tax = 3.2;
System.out.println(price + tax); */
}
}Write a Java program that demonstrates the String trim() method. Create a String holding the value " Anjali " (with leading and trailing spaces). Print the original string, then print the string after calling trim(). Name the class StringTrimDemo.
public class StringTrimDemo
{
public static void main(String ar[])
{
String s=" Anjali ";
System.out.println(s);// Anjali
System.out.println(s.trim());//Anjali
}
}Write a Java program that demonstrates the String startsWith() and endsWith() methods. Create a String holding the value "Rohit". Print whether it starts with "Ro" and whether it ends with "t". Name the class StringCheck.
public class StringCheck
{
public static void main(String ar[])
{
String s="Rohit";
System.out.println(s.startsWith("Ro"));//true
System.out.println(s.endsWith("t"));//true
}
}Write a Java program that stores the name of an Indian river in a String variable and prints the characters at index 0 and index 2 using the String charAt() method. Use the river name "Ganga". The class should be named RiverCharAt.
public class RiverCharAt
{
public static void main(String[] args)
{
String river = "Ganga";
System.out.println(river.charAt(0));
System.out.println(river.charAt(2));
}
}Write a Java program that demonstrates the String.intern() method. Create a String object using the new keyword with the value "Rahul", then call intern() on it and store the result in another String variable. Print the interned string. The output should be Rahul.
public class StringInternDemo {
public static void main(String[] args) {
String name = new String("Rahul");
String internedName = name.intern();
System.out.println(internedName);
}
}Write a Java program that demonstrates the String.valueOf() method. Convert an integer variable 'marks' with value 85 to a String using String.valueOf(), then concatenate the string "100" to it and print the result. The output should be 85100.
public class StringValueOfDemo {
public static void main(String[] args) {
int marks = 85;
String strMarks = String.valueOf(marks);
System.out.println(strMarks + "100");
}
}Write a Java program that demonstrates the String class replace() method. Create a String containing the sentence: "Delhi is the capital of India. Delhi is a busy city. Delhi has many monuments." Then use replace() to replace every occurrence of "Delhi" with "Mumbai" and print the resulting string. Name the class StringReplaceDemo.
public class StringReplaceDemo {
public static void main(String[] args) {
String s1 = "Delhi is the capital of India. Delhi is a busy city. Delhi has many monuments.";
String replaced = s1.replace("Delhi", "Mumbai");
System.out.println(replaced);
}
}Write a Java program that demonstrates the parameterless getBytes() method of the String class. Create a String variable holding the value "INDIA2024", convert it to a byte array using getBytes() (which uses the platform's default charset, UTF-8), and then print each byte value on its own line. Name the file StringBytesDemo.java and the class StringBytesDemo.
public class StringBytesDemo {
public static void main(String[] args) {
String s1 = "INDIA2024";
byte[] barr = s1.getBytes();
for (int i = 0; i < barr.length; i++) {
System.out.println(barr[i]);
}
}
}Write a Java program that takes the String "KOLKATA" and converts it into a byte array using the getBytes() method. Print each byte value on its own line, then reconstruct a String from that byte array using the String constructor and print the reconstructed String. Name the file ByteArrayRoundTrip.java.
public class ByteArrayRoundTrip {
public static void main(String[] args) {
String s1 = "KOLKATA";
byte[] barr = s1.getBytes();
for (int i = 0; i < barr.length; i++) {
System.out.println(barr[i]);
}
// Getting string back
String s2 = new String(barr);
System.out.println(s2);
}
}Write a Java program that demonstrates the append() method of the StringBuffer class. Create a StringBuffer initialized with "Namaste " and then append "Bharat" to it. Finally, print the modified StringBuffer. The program should be in a class named StringBufferAppendExample.
public class StringBufferAppendExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Namaste ");
sb.append("Bharat");
System.out.println(sb);
}
}Write a Java program that stores the prices of two items in integer variables — a notebook costing Rs 25 and a pen costing Rs 15 — adds them, and prints the total cost.
public class TotalCost {
public static void main(String[] args) {
int notebook = 25;
int pen = 15;
int total = notebook + pen;
System.out.println(total);
}
}Write a Java program that stores the number of mangoes 45 in an int variable, then assigns it to a double variable named weightInKg (implicit widening), and prints both values on separate lines.
public class MangoCount {
public static void main(String[] args) {
int mangoes = 45;
double weightInKg = mangoes;
System.out.println(mangoes);
System.out.println(weightInKg);
}
}Write a Java program that stores the value 27.86 in a float variable named price, then explicitly narrows it to an int variable named rupees using typecasting, and prints both values on separate lines.
public class ShopBill {
public static void main(String[] args) {
float price = 27.86f;
// int rupees = price; // compile-time error without cast
int rupees = (int) price;
System.out.println(price);
System.out.println(rupees);
}
}Write a Java program that adds two byte variables and stores the result in a byte variable using an explicit cast. Use the values 20 and 30, then print the result.
public class ByteAddDemo {
public static void main(String[] args) {
byte x = 20;
byte y = 30;
// byte z = x + y; // Compile-time error: x + y is promoted to int
byte z = (byte)(x + y);
System.out.println(z);
}
}Write a Java program demonstrating runtime polymorphism. Create a parent class Bird with a method sound() that prints "chirping...". Create three subclasses: Parrot (prints "squawking..."), Crow (prints "cawing...") and Owl (prints "hooting..."), each overriding sound(). In main, use a Bird reference to point to each subclass object in turn and call sound().
class Bird {
void sound() { System.out.println("chirping..."); }
}
class Parrot extends Bird {
void sound() { System.out.println("squawking..."); }
}
class Crow extends Bird {
void sound() { System.out.println("cawing..."); }
}
class Owl extends Bird {
void sound() { System.out.println("hooting..."); }
}
class TestPolymorphism {
public static void main(String[] args) {
Bird b;
b = new Parrot();
b.sound();
b = new Crow();
b.sound();
b = new Owl();
b.sound();
}
}Write a Java program that demonstrates an infinite do-while loop. Use a do-while loop with the condition true, and inside the loop print the message "infinite do-while loop". The program should run indefinitely.
public class InfiniteDoWhile {
public static void main(String[] args) {
do {
System.out.println("infinite do-while loop");
} while (true);
}
}Write a Java program named CleanupDemo.java that creates an object, prints its hash code, sets the reference to null, requests garbage collection with System.gc(), and then prints a closing message. The class must override finalize() so that it prints "finalize() method invoked" when the object is collected.
public class CleanupDemo {
public static void main(String[] args) {
CleanupDemo item = new CleanupDemo();
System.out.println("Hashcode is: " + item.hashCode());
item = null;
System.gc();
System.out.println("Garbage collection request finished");
}
protected void finalize() {
System.out.println("finalize() method invoked");
}
}Write a Java program that demonstrates the rule: if a superclass method declares no exception, the subclass overridden method cannot declare a checked exception, but may declare an unchecked exception. Create a class `Shape` with a method `draw()` that declares no exception, and a subclass `Circle` whose overridden `draw()` declares `IOException` (a checked exception). Show that this causes a compile-time error. Name the file `ShapeTest.java`.
import java.io.*;
class Shape {
void draw() {
System.out.println("shape method");
}
}
class Circle extends Shape {
void draw() throws IOException { // compile-time error: checked exception not allowed
System.out.println("circle method");
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape s = new Circle();
s.draw();
}
}Write a Java program that demonstrates the rule: if a superclass method declares an exception, the subclass overridden method may declare the same exception or a subclass of it, but cannot declare a parent (broader) exception. Create a class `Vehicle` with a method `show()` that declares `ArithmeticException`, and a subclass `Car` whose overridden `show()` declares `RuntimeException` (a parent of ArithmeticException). Show that this causes a compile-time error. Name the file `VehicleTest.java`.
class Vehicle {
void show() throws ArithmeticException {
System.out.println("vehicle method");
}
}
class Car extends Vehicle {
void show() throws RuntimeException { // compile-time error: parent exception
System.out.println("car method");
}
}
public class VehicleTest {
public static void main(String[] args) {
Vehicle v = new Car();
v.show();
}
}Write a Java program that demonstrates method overriding where the subclass overridden method declares no exception. Create a parent class Vehicle with a method show() that declares 'throws Exception' and prints "Vehicle method". Create a child class Car that overrides show() without declaring any exception and prints "Car method". In main, create a Car object and call show() inside a try-catch block that catches Exception.
class Vehicle {
void show() throws Exception {
System.out.println("Vehicle method");
}
}
class Car extends Vehicle {
void show() {
System.out.println("Car method");
}
}
public class OverrideDemo {
public static void main(String[] args) {
try {
Car c = new Car();
c.show();
} catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
}Write a Java program that demonstrates the DataInputStream class. The program should read the contents of a file named notes.txt (located in the current working directory) and print each character followed by a hyphen '-'. Use FileInputStream wrapped in a DataInputStream, read all available bytes into a byte array, then loop through the array converting each byte to a char and printing it with a trailing '-'.
import java.io.*;
public class DataStreamDemo {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("notes.txt");
DataInputStream din = new DataInputStream(input);
int count = input.available();
byte[] data = new byte[count];
din.read(data);
for (byte b : data) {
char c = (char) b;
System.out.print(c + "-");
}
din.close();
}
}Write a Java program that uses the String getChars() method to copy a substring into a character array and then prints the array. Use the string "hello india how r u" and copy characters from index 6 to 16 (exclusive) into a char array of size 10, starting at index 0 of the array.
public class StringGetCharsExample {
public static void main(String[] args) {
String str = "hello india how r u";
char[] ch = new char[10];
try {
str.getChars(6, 16, ch, 0);
System.out.println(ch);
} catch (Exception ex) {
System.out.println(ex);
}
}
}Write a Java program that demonstrates the String getChars() method throwing an exception when the source range exceeds the string length. Use the string "Welcome to India" and attempt to copy characters from index 1 to 26 into a char array of size 20. Catch and print the exception.
public class StringGetCharsExample2 {
public static void main(String[] args) {
String str = "Welcome to India";
char[] ch = new char[20];
try {
str.getChars(1, 26, ch, 0);
System.out.println(ch);
} catch (Exception e) {
System.out.println(e);
}
}
}Write a Java program that demonstrates a thread pool using ExecutorService and Executors. Create a task class named PrintTask that implements Runnable, takes a String label in its constructor, prints the current thread's name with "(Start) label = <label>", sleeps for 1500 milliseconds, then prints the current thread's name with "(End)". In main, create a fixed thread pool of 3 threads, submit 5 PrintTask instances with labels "Alpha", "Beta", "Gamma", "Delta", "Epsilon", and shut down the executor.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class PrintTask implements Runnable {
private String label;
public PrintTask(String label) {
this.label = label;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) label = " + label);
pause();
System.out.println(Thread.currentThread().getName() + " (End)");
}
private void pause() {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
String[] labels = {"Alpha", "Beta", "Gamma", "Delta", "Epsilon"};
for (String label : labels) {
pool.execute(new PrintTask(label));
}
pool.shutdown();
}
}Write a Java program using a fixed thread pool of 2 threads. Create a Runnable task class named Job that takes a job name in its constructor. In run(), loop 3 times (j = 0 to 2): on the first iteration print "Start time for job: <name> = <time>", otherwise print "Running job: <name> = <time>", using SimpleDateFormat with pattern "hh : mm : ss"; then sleep 1000 ms. After the loop print "<name> is finished.". In main, create an ExecutorService with Executors.newFixedThreadPool(2) and submit three Job tasks named "Report", "Invoice" and "Audit", then shut down the executor.
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.text.SimpleDateFormat;
class Job implements Runnable {
private String jobName;
public Job(String str) {
jobName = str;
}
public void run() {
try {
for (int j = 0; j <= 2; j++) {
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("hh : mm : ss");
if (j == 0) {
System.out.println("Start time for job: " + jobName + " = " + sdf.format(dt));
} else {
System.out.println("Running job: " + jobName + " = " + sdf.format(dt));
}
Thread.sleep(1000);
}
System.out.println(jobName + " is finished.");
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Job("Report"));
executor.execute(new Job("Invoice"));
executor.execute(new Job("Audit"));
executor.shutdown();
}
}Write a Java program that demonstrates the restriction that a static method cannot directly use a non-static (instance) data member. Create a class named Shop with a non-static integer field price = 250. In its main method (which is static), try to print price directly and show that this causes a compile-time error. Add a comment in the code explaining why the error occurs.
class Shop {
int price = 250; // non-static (instance) variable
public static void main(String[] args) {
// ERROR: cannot access non-static variable 'price' from a static context
// System.out.println(price); // uncommenting this line causes a compile-time error
System.out.println("Cannot access non-static field price directly from static main");
}
}Write a Java program that demonstrates whether a class can run without a main() method using a static block. The program should print "startup block executed" from a static block and then exit the JVM before any main method is needed. (Note: this behaviour worked only up to JDK 1.6; from JDK 1.7 onward a main method is required.)
public class StartupDemo {
static {
System.out.println("startup block executed");
System.exit(0);
}
public static void main(String[] args) {
}
}Write a Java program that demonstrates the FilterOutputStream class. The program should create a file named "notes.txt" in the current directory, wrap a FileOutputStream in a FilterOutputStream, write the string "Hello Mumbai!" to the file using the write(byte[]) method, then flush and close the streams, and finally print "Done" to the console.
import java.io.*;
public class FilterDemo {
public static void main(String[] args) throws IOException {
File data = new File("notes.txt");
FileOutputStream file = new FileOutputStream(data);
FilterOutputStream filter = new FilterOutputStream(file);
String s = "Hello Mumbai!";
byte b[] = s.getBytes();
filter.write(b);
filter.flush();
filter.close();
file.close();
System.out.println("Done");
}
}Write a Java program that demonstrates the String indexOf() method overloads. Use the String "java is a simple language" and: (a) find the index of the substring "is" and of the substring "simple"; (b) find the index of "is" searching from index 4; (c) find the index of the character 'a'. Print each result on its own line. FileName: IndexOfDemo.java
public class IndexOfDemo {
public static void main(String[] args) {
String s = "java is a simple language";
int i1 = s.indexOf("is");
int i2 = s.indexOf("simple");
System.out.println(i1 + " " + i2);
int i3 = s.indexOf("is", 4);
System.out.println(i3);
int i4 = s.indexOf('a');
System.out.println(i4);
}
}Write a Java program that creates an empty StringBuilder, prints its default capacity, appends "Namaste", prints the capacity, appends "India is a great country", prints the capacity, calls ensureCapacity(20) and prints the capacity, then calls ensureCapacity(80) and prints the capacity.
class CapacityDemo {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());
sb.append("Namaste");
System.out.println(sb.capacity());
sb.append("India is a great country");
System.out.println(sb.capacity());
sb.ensureCapacity(20);
System.out.println(sb.capacity());
sb.ensureCapacity(80);
System.out.println(sb.capacity());
}
}Write a Java program that shows downcasting is possible when the instanceof operator is used. Create a parent class Animal and a child class Dog extending Animal. In Dog, write a static method test(Animal a) that checks 'if (a instanceof Dog)', then casts a to Dog and prints "downcasting successful". In main, create an Animal reference pointing to a Dog object and call Dog.test with it.
class Animal { }
class Dog extends Animal {
static void test(Animal a) {
if (a instanceof Dog) {
Dog d = (Dog) a; // downcasting after instanceof check
System.out.println("downcasting successful");
}
}
public static void main(String[] args) {
Animal a = new Dog();
Dog.test(a);
}
}Write a Java program that demonstrates downcasting a parent reference to a child type WITHOUT using the instanceof operator. Create a parent class Vehicle and a child class Car extending Vehicle. In Car, write a static method check(Vehicle v) that casts v to Car (downcasting) and then prints "downcasting done". In main, create a Vehicle reference pointing to a Car object and call Car.check with it.
class Vehicle { }
class Car extends Vehicle {
static void check(Vehicle v) {
Car c = (Car) v; // downcasting without instanceof
System.out.println("downcasting done");
}
public static void main(String[] args) {
Vehicle v = new Car();
Car.check(v);
}
}Write a Java program that shows a real use of the instanceof keyword. Declare an interface Shape. Class Circle implements Shape and has a method drawCircle() that prints "Drawing circle". Class Square implements Shape and has a method drawSquare() that prints "Drawing square". In main, create one Circle and one Square, store them in a Shape array, and loop over the array: use instanceof to check the actual type and call the matching method.
interface Shape {}
class Circle implements Shape {
public void drawCircle() { System.out.println("Drawing circle"); }
}
class Square implements Shape {
public void drawSquare() { System.out.println("Drawing square"); }
}
public class InstanceofDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle(), new Square() };
for (Shape s : shapes) {
if (s instanceof Circle) {
((Circle) s).drawCircle();
} else if (s instanceof Square) {
((Square) s).drawSquare();
}
}
}
}Write a Java program that creates a ThreadGroup named "TeamGroup", starts three threads named "alpha", "beta" and "gamma" inside that group (each thread prints its own name), then prints the thread group's name and lists the group's active threads. Save the program as TeamGroupDemo.java.
public class TeamGroupDemo implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
TeamGroupDemo job = new TeamGroupDemo();
ThreadGroup tg = new ThreadGroup("TeamGroup");
Thread t1 = new Thread(tg, job, "alpha");
t1.start();
Thread t2 = new Thread(tg, job, "beta");
t2.start();
Thread t3 = new Thread(tg, job, "gamma");
t3.start();
System.out.println("Thread Group Name: " + tg.getName());
tg.list();
}
}Write a Java program that demonstrates the ThreadGroup method isDestroyed(). Create a ThreadGroup named "KabaddiGroup", start two threads in it that each print a message after a short sleep, then destroy the group and print whether it is destroyed using isDestroyed(). FileName: IsDestroyedDemo.java
public class IsDestroyedDemo {
public static void main(String[] args) throws InterruptedException {
ThreadGroup kabaddiGroup = new ThreadGroup("KabaddiGroup");
WorkerThread t1 = new WorkerThread(kabaddiGroup, "Raider");
WorkerThread t2 = new WorkerThread(kabaddiGroup, "Defender");
t1.join();
t2.join();
kabaddiGroup.destroy();
System.out.println("Is group destroyed? " + kabaddiGroup.isDestroyed());
}
}
class WorkerThread extends Thread {
WorkerThread(ThreadGroup group, String name) {
super(group, name);
start();
}
public void run() {
for (int j = 0; j < 50; j++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
System.out.println(getName() + " thread has finished executing");
}
}Write a Java program that demonstrates the ThreadGroup method activeCount(). Create a ThreadGroup named "CricketGroup". Create three threads in this group, each printing its name and sleeping briefly in a loop. After starting them, print the number of active threads in the group using activeCount(). FileName: ActiveCountDemo.java
public class ActiveCountDemo {
public static void main(String[] args) {
ThreadGroup cricketGroup = new ThreadGroup("CricketGroup");
for (int i = 1; i <= 3; i++) {
new PlayerThread(cricketGroup, "Player-" + i);
}
System.out.println("Active threads in group: " + cricketGroup.activeCount());
}
}
class PlayerThread extends Thread {
PlayerThread(ThreadGroup group, String name) {
super(group, name);
start();
}
public void run() {
for (int j = 0; j < 500; j++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
System.out.println(getName() + " finished");
}
}Write a Java program that demonstrates the ThreadGroup activeGroupCount() method. Create a parent thread group "Warehouse" and two child thread groups "Packing" and "Dispatch" inside it, start one thread in each child group, and print the number of active subgroups of the parent group using activeGroupCount(). Use the file name ActiveGroupDemo.java.
class WorkThread extends Thread {
WorkThread(String name, ThreadGroup grp) {
super(grp, name);
start();
}
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " finished");
}
}
public class ActiveGroupDemo {
public static void main(String[] args) {
ThreadGroup parent = new ThreadGroup("Warehouse");
ThreadGroup packing = new ThreadGroup(parent, "Packing");
ThreadGroup dispatch = new ThreadGroup(parent, "Dispatch");
WorkThread t1 = new WorkThread("Packer1", packing);
WorkThread t2 = new WorkThread("Dispatcher1", dispatch);
System.out.println("Active subgroups of Warehouse: " + parent.activeGroupCount());
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main interrupted: " + e);
}
}
}Write a Java program that demonstrates the ThreadGroup destroy() method. Create a thread group named "SalesTeam", start two threads in it that each sleep briefly in a loop, and after the threads finish, call destroy() on the thread group and print whether it is destroyed. Use the file name DestroyDemo.java.
class SalesThread extends Thread {
SalesThread(String name, ThreadGroup grp) {
super(grp, name);
start();
}
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " finished");
}
}
public class DestroyDemo {
public static void main(String[] args) {
ThreadGroup grp = new ThreadGroup("SalesTeam");
SalesThread t1 = new SalesThread("AgentA", grp);
SalesThread t2 = new SalesThread("AgentB", grp);
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main interrupted: " + e);
}
grp.destroy();
System.out.println("Thread group destroyed successfully");
}
}Write a Java program that demonstrates the ThreadGroup method enumerate(). Create a ThreadGroup named "BatchGroup", start three threads in it (named "Task-1", "Task-2", "Task-3") that each sleep briefly and print a completion message, then use enumerate(Thread[]) to count and print how many threads of the group are currently active.
public class EnumerateDemo {
public static void main(String[] args) {
ThreadGroup batchGroup = new ThreadGroup("BatchGroup");
Thread t1 = new Thread(batchGroup, new Job(), "Task-1");
Thread t2 = new Thread(batchGroup, new Job(), "Task-2");
Thread t3 = new Thread(batchGroup, new Job(), "Task-3");
t1.start();
t2.start();
t3.start();
Thread[] list = new Thread[batchGroup.activeCount() + 2];
int count = batchGroup.enumerate(list);
System.out.println("Threads enumerated in " + batchGroup.getName() + " = " + count);
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
}
}
class Job implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Exception encountered: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " thread has finished executing");
}
}Write a Java program that demonstrates the ThreadGroup method getMaxPriority(). Create a ThreadGroup named "TeamGroup" with a maximum priority of 7, create two threads in that group (named "Worker-A" and "Worker-B") that each sleep briefly and then print a completion message, and finally print the maximum priority of the group.
public class MaxPriorityDemo {
public static void main(String[] args) {
ThreadGroup teamGroup = new ThreadGroup("TeamGroup");
teamGroup.setMaxPriority(7);
Thread t1 = new Thread(teamGroup, new Worker(), "Worker-A");
Thread t2 = new Thread(teamGroup, new Worker(), "Worker-B");
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e);
}
System.out.println("Maximum priority of " + teamGroup.getName() + " = " + teamGroup.getMaxPriority());
}
}
class Worker implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Exception encountered: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " thread has finished executing");
}
}Write a Java program that demonstrates the getParent() method of ThreadGroup. Create a parent ThreadGroup named 'ParentGroup' and a child ThreadGroup named 'ChildGroup' as its child. Create a thread named 'MyThread' in the child group that sleeps for 5 milliseconds in a loop 100 times, catching InterruptedException and printing a message. After the loop, print the thread name and that it has finished executing. In the main method, after starting the thread, print the parent group of the child group using getParent(). FileName: GetParentDemo.java
public class GetParentDemo {
public static void main(String[] args) {
ThreadGroup parent = new ThreadGroup("ParentGroup");
ThreadGroup child = new ThreadGroup(parent, "ChildGroup");
MyThread t = new MyThread("MyThread", child);
System.out.println("Parent of ChildGroup: " + child.getParent().getName());
}
}
class MyThread extends Thread {
MyThread(String name, ThreadGroup group) {
super(group, name);
start();
}
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " thread has finished executing");
}
}Write a Java program that illustrates the use of the isDaemon() method. Create a class 'WorkerThread' extending Thread whose constructor takes a thread name and a ThreadGroup, calls super(tgrp, tName) and then start(). Override run() to loop 100 times calling Thread.sleep(5) inside a try-catch for InterruptedException (printing "Exception encountered: " + e on catch), and after the loop print the current thread's name followed by " thread has finished executing". In main, create a ThreadGroup named "DemoGroup", create a WorkerThread named "worker-1" in that group, and print whether it is a daemon thread using isDaemon().
class WorkerThread extends Thread {
WorkerThread(String tName, ThreadGroup tgrp) {
super(tgrp, tName);
start();
}
public void run() {
for (int j = 0; j < 100; j++) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.println("Exception encountered: " + e);
}
}
System.out.println(Thread.currentThread().getName() + " thread has finished executing");
}
}
class IsDaemonExample {
public static void main(String args[]) {
ThreadGroup grp = new ThreadGroup("DemoGroup");
WorkerThread t = new WorkerThread("worker-1", grp);
System.out.println("Is worker-1 a daemon thread? " + t.isDaemon());
}
}Write a Java program that shows the real use of the this() constructor call for constructor chaining. Create a class Employee with fields empId (int), empName (String), department (String) and salary (double). The 3-argument constructor should set empId, empName and department. The 4-argument constructor should reuse the 3-argument constructor by calling this(empId, empName, department) and then set salary. Include a display() method that prints all four fields, and a main method that creates one Employee with 3 arguments and one with 4 arguments and calls display() on both.
class Employee{
int empId;
String empName,department;
double salary;
Employee(int empId,String empName,String department){
this.empId=empId;
this.empName=empName;
this.department=department;
}
Employee(int empId,String empName,String department,double salary){
this(empId,empName,department);//reusing constructor
this.salary=salary;
}
void display(){System.out.println(empId+" "+empName+" "+department+" "+salary);}
}
class TestThis7{
public static void main(String args[]){
Employee e1=new Employee(201,"Ravi","Accounts");
Employee e2=new Employee(202,"Meera","Accounts",45000.0);
e1.display();
e2.display();
}}Write a Java program that demonstrates the rule that a call to this() must be the first statement in a constructor. Create a class Employee with fields empId (int), empName (String), department (String) and salary (double). Provide a 3-argument constructor that sets empId, empName and department. Provide a 4-argument constructor that sets salary first and then tries to call this(empId, empName, department). Compile-time behaviour should be shown by placing the this() call after the salary assignment (which causes a compile-time error). Also include a display() method that prints all four fields, and a main method that creates Employee objects and calls display().
class Employee{
int empId;
String empName,department;
double salary;
Employee(int empId,String empName,String department){
this.empId=empId;
this.empName=empName;
this.department=department;
}
Employee(int empId,String empName,String department,double salary){
this.salary=salary;
this(empId,empName,department);//Compile-time error: this() must be first statement
}
void display(){System.out.println(empId+" "+empName+" "+department+" "+salary);}
}
class TestThis8{
public static void main(String args[]){
Employee e1=new Employee(201,"Ravi","Accounts");
Employee e2=new Employee(202,"Meera","Accounts",45000.0);
e1.display();
e2.display();
}}Write a Java program that demonstrates passing the 'this' keyword as an argument in a constructor call. Create a class named 'Customer' with an integer field 'custId' and a constructor that sets it. Create another class named 'Order' that holds a reference to a Customer object; its constructor takes a Customer object and assigns it to its field. In the Customer constructor, create an Order object by passing 'this' to the Order constructor. Add a method in Order named 'showCustomerId()' that prints the customer's id. In main, create a Customer with id 501 and call showCustomerId() on the order created inside it.
class Order {
Customer cust;
Order(Customer cust) {
this.cust = cust;
}
void showCustomerId() {
System.out.println(cust.custId);
}
}
class Customer {
int custId;
Order order;
Customer(int custId) {
this.custId = custId;
this.order = new Order(this);
}
}
public class Main {
public static void main(String[] args) {
Customer c = new Customer(501);
c.order.showCustomerId();
}
}Write a Java program that declares two short variables p = 5 and q = 5. First show that p = p + q causes a compile-time error (because the result of short + short is int), then fix it by using the compound assignment p += q and print the final value of p.
public class ShortAddDemo {
public static void main(String[] args) {
short p = 5;
short q = 5;
// p = p + q; // Compile-time error: 5 + 5 is int, cannot assign int to short
p += q; // internally p = (short)(p + q), so this is fine
System.out.println(p);
}
}Write a Java program that demonstrates the difference between the signed right shift operator >> and the unsigned right shift operator >>> in Java. Print the results of 24>>2, 24>>>2, -24>>2 and -24>>>2.
public class ShiftOperatorDemo {
public static void main(String[] args) {
// For a positive number, >> and >>> behave the same
System.out.println(24>>2);
System.out.println(24>>>2);
// For a negative number, >>> fills the sign bit (MSB) with 0
System.out.println(-24>>2);
System.out.println(-24>>>2);
}
}Write a Java program named LogicCheck.java that demonstrates the difference between the logical AND operator (&&) and the bitwise AND operator (&). Declare int x = 8, y = 3, z = 15. Print the result of (x < y && x++ < z), then print x. Next print the result of (x < y & x++ < z), then print x again.
public class LogicCheck {
public static void main(String args[]) {
int x = 8;
int y = 3;
int z = 15;
System.out.println(x < y && x++ < z);
System.out.println(x);
System.out.println(x < y & x++ < z);
System.out.println(x);
}
}Write a Java program named SpeedTest.java that compares the performance of string concatenation using the String class versus the StringBuffer class. Create two methods: one that starts with the string "Cricket" and appends "India" to it 8000 times using the + operator, and another that starts with a StringBuffer initialized to "Cricket" and appends "India" 8000 times using append(). In main(), measure and print the time taken (in milliseconds) by each method using System.currentTimeMillis().
public class SpeedTest {
public static String concatWithString() {
String s = "Cricket";
for (int i = 0; i < 8000; i++) {
s = s + "India";
}
return s;
}
public static String concatWithStringBuffer() {
StringBuffer sb = new StringBuffer("Cricket");
for (int i = 0; i < 8000; i++) {
sb.append("India");
}
return sb.toString();
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by Concating with String: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by Concating with StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
}
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com