Question Bank › Technical › Java › Coding Questions
Write a Java program to demonstrate that the hashCode of a String changes after concatenation, while the hashCode of a StringBuffer remains the same after appending. Use the string "hello" and append "world".
public class HashCodeDemo {
public static void main(String[] args) {
System.out.println("Hashcode test of String:");
String str = "hello";
System.out.println(str.hashCode());
str = str + "world";
System.out.println(str.hashCode());
System.out.println("Hashcode test of StringBuffer:");
StringBuffer sb = new StringBuffer("hello");
System.out.println(sb.hashCode());
sb.append("world");
System.out.println(sb.hashCode());
}
}Write a Java program that demonstrates the use of FilterInputStream. The program should read the contents of a file named "C:\\data\\input.txt" using a BufferedInputStream (which is a FilterInputStream) and print each character to the console.
import java.io.*;
public class FilterStreamDemo {
public static void main(String[] args) {
File file = new File("C:\\data\\input.txt");
try (FileInputStream fileInputStream = new FileInputStream(file);
FilterInputStream filterInputStream = new BufferedInputStream(fileInputStream)) {
int ch;
while ((ch = filterInputStream.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}Write a Java program that registers a shutdown hook using an anonymous inner class. The program should print "cleanup done for Mumbai server.." from the hook, and from the main thread print "Main is going to sleep... press ctrl+c to exit", then sleep for 2000 milliseconds. FileName: ServerShutdown.java
public class ServerShutdown{
public static void main(String[] args)throws Exception {
Runtime rt=Runtime.getRuntime();
rt.addShutdownHook(new Thread(){
public void run(){
System.out.println("cleanup done for Mumbai server..");
}
}
);
System.out.println("Main is going to sleep... press ctrl+c to exit");
try{Thread.sleep(2000);}catch (Exception e) {}
}
}Write a Java program named RemoveHookDemo.java that registers a shutdown hook thread which prints "Goodbye ...", prints a starting message, waits for 2 seconds, then removes the registered shutdown hook using removeShutdownHook(), and finally prints a terminating message.
public class RemoveHookDemo {
static class Farewell extends Thread {
public void run() {
System.out.println("Goodbye ...");
}
}
public static void main(String[] args) {
try {
Farewell fw = new Farewell();
Runtime.getRuntime().addShutdownHook(fw);
System.out.println("The program is starting ...");
System.out.println("Waiting for 2 seconds ...");
Thread.sleep(2000);
Runtime.getRuntime().removeShutdownHook(fw);
System.out.println("The program is ending ...");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}Write a Java program to compare the performance of StringBuffer and StringBuilder. The program should measure the time taken to append the string "India" 20000 times to a StringBuffer initialized with "Bharat" and to a StringBuilder initialized with "Bharat". Print the time taken by each in milliseconds.
public class PerformanceTest {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Bharat");
for (int i = 0; i < 20000; i++) {
sb.append("India");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Bharat");
for (int i = 0; i < 20000; i++) {
sb2.append("India");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
}
}Write a Java program that creates two threads using anonymous inner classes that implement Runnable. One thread should print "Hello from Thread A" and the other should print "Hello from Thread B". Start both threads.
public class MultiTaskDemo {
public static void main(String[] args) {
Runnable taskA = new Runnable() {
public void run() {
System.out.println("Hello from Thread A");
}
};
Runnable taskB = new Runnable() {
public void run() {
System.out.println("Hello from Thread B");
}
};
Thread t1 = new Thread(taskA);
Thread t2 = new Thread(taskB);
t1.start();
t2.start();
}
}Write a Java program that demonstrates that the String replaceAll() method throws a PatternSyntaxException when an improper (invalid) regular expression is supplied. Use the input string "Ravi likes cricket, Mumbai Indians is a strong team." and an invalid regex consisting of a single backslash. Print the original string, then call replaceAll() with that invalid regex and the replacement "Delhi ", and print the result. (The program is expected to throw PatternSyntaxException at runtime.)
public class ReplaceAllDemo
{
public static void main(String[] args)
{
String str = "Ravi likes cricket, Mumbai Indians is a strong team.";
System.out.println(str);
String regex = "\\"; // invalid regular expression
// invoking replaceAll() raises PatternSyntaxException
str = str.replaceAll(regex, "Delhi ");
System.out.println(str);
}
}Write a Java program that uses the replaceAll() method to insert a space before and after every character of a string. Take the input string "IncredibleIndia", print it, then replace every empty match (regex "") with a single space " " and print the modified string. Name the file ReplaceAllSpaceDemo.java and the class ReplaceAllSpaceDemo.
public class ReplaceAllSpaceDemo
{
// main method
public static void main(String[] args)
{
// input string
String text = "IncredibleIndia";
System.out.println(text);
String regex = "";
// adding a white space before and after every character of the input string
text = text.replaceAll(regex, " ");
System.out.println(text);
}
}Write a Java program that demonstrates an abstract class with an abstract method. Create an abstract class 'Vehicle' that has one abstract method 'move'. Provide an implementation of this method in a subclass 'Car'. In the main method, create an object of 'Car' using a 'Vehicle' reference and call the 'move' method.
abstract class Vehicle {
abstract void move();
}
class Car extends Vehicle {
void move() {
System.out.println("Car is moving safely");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.move();
}
}Write a Java program that shows the real scenario of an abstract class. Make Shape an abstract class with an abstract method draw(). Rectangle and Circle extend Shape and implement draw() printing "drawing rectangle" and "drawing circle" respectively. Add a factory method getShape(String type) that returns a new Rectangle when type is "rectangle" and a new Circle otherwise. In main, obtain a Shape from the factory using "circle" and call draw().
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape {
void draw() { System.out.println("drawing rectangle"); }
}
class Circle extends Shape {
void draw() { System.out.println("drawing circle"); }
}
public class TestAbstraction1 {
static Shape getShape(String type) {
if (type.equals("rectangle")) {
return new Rectangle();
}
return new Circle();
}
public static void main(String[] args) {
Shape s = getShape("circle");
s.draw();
}
}Write a Java program showing that an abstract class can have a constructor, a data member, an abstract method and a non-abstract method. Create an abstract class Vehicle with a data member String model, a constructor that sets the model and prints "Vehicle created: <model>", an abstract method start(), and a non-abstract method changeGear() that prints "Gear changed". Then create a child class Car extending Vehicle whose constructor calls the parent constructor with model "Swift", and which implements start() to print "Car started safely". In main(), create a Car object and call start() and changeGear().
abstract class Vehicle {
String model;
Vehicle(String model) {
this.model = model;
System.out.println("Vehicle created: " + model);
}
abstract void start();
void changeGear() {
System.out.println("Gear changed");
}
}
class Car extends Vehicle {
Car() {
super("Swift");
}
void start() {
System.out.println("Car started safely");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
v.changeGear();
}
}Write a Java program that demonstrates how an abstract class can provide partial implementation of an interface. Create an interface PaymentGateway with four methods: pay(), refund(), checkStatus() and cancel(). Then create an abstract class PartialGateway that implements PaymentGateway and provides the implementation of only pay() (print "Payment processed") and checkStatus() (print "Status checked"). Finally, create a concrete class UpiGateway extending PartialGateway that implements the remaining methods refund() (print "Refund done") and cancel() (print "Payment cancelled"). In main(), create a UpiGateway object and call all four methods.
interface PaymentGateway {
void pay();
void refund();
void checkStatus();
void cancel();
}
abstract class PartialGateway implements PaymentGateway {
public void pay() {
System.out.println("Payment processed");
}
public void checkStatus() {
System.out.println("Status checked");
}
}
class UpiGateway extends PartialGateway {
public void refund() {
System.out.println("Refund done");
}
public void cancel() {
System.out.println("Payment cancelled");
}
}
public class Main {
public static void main(String[] args) {
UpiGateway g = new UpiGateway();
g.pay();
g.refund();
g.checkStatus();
g.cancel();
}
}Write a Java program to demonstrate that Java does not support multiple inheritance with classes. Create two classes, X and Y, each with a method display() that prints different messages. Then create a class Z that attempts to extend both X and Y. Show the compile-time error by commenting the erroneous line and explaining why it occurs.
class X {
void display() {
System.out.println("Message from X");
}
}
class Y {
void display() {
System.out.println("Message from Y");
}
}
// Uncommenting the following line will cause a compile-time error
// class Z extends X, Y { }
public class MultipleInheritanceDemo {
public static void main(String[] args) {
System.out.println("Java does not support multiple inheritance with classes.");
System.out.println("If class Z extended both X and Y, and both have display(), the compiler would not know which display() to call.");
}
}Write a Java program using nested loops and the continue statement. The outer loop runs for i = 0 to 2 (inclusive). The inner loop runs for j = i to 5 (inclusive). If j equals 3, skip the rest of the inner loop body using continue; otherwise print the value of j.
public class SkipExample {
public static void main(String[] args) {
for (int i = 0; i <= 2; i++) {
for (int j = i; j <= 5; j++) {
if (j == 3) {
continue;
}
System.out.println(j);
}
}
}
}Write a Java program that demonstrates accessing a class from another package using its fully qualified name without importing it. Create a class named MessagePrinter in package 'mypack' with a method show() that prints 'Hello from mypack'. Then, create a class FullyQualifiedDemo in the default package that creates an object of mypack.MessagePrinter using the fully qualified name and calls its show() method.
// File: mypack/MessagePrinter.java
package mypack;
public class MessagePrinter {
public void show() {
System.out.println("Hello from mypack");
}
}
// File: FullyQualifiedDemo.java
public class FullyQualifiedDemo {
public static void main(String[] args) {
mypack.MessagePrinter mp = new mypack.MessagePrinter();
mp.show();
}
}Write a Java program that demonstrates the use of a subpackage. Create a class named Greeting inside a subpackage 'in.example.core' (which is a subpackage of 'in.example'). The class should have a main method that prints 'Namaste from subpackage'. Also, create a main class named SubpackageDemo in the default package that creates an object of Greeting and calls a method greet() which prints the same message. Ensure proper package declaration and import.
// File: in/example/core/Greeting.java
package in.example.core;
public class Greeting {
public void greet() {
System.out.println("Namaste from subpackage");
}
public static void main(String[] args) {
System.out.println("Namaste from subpackage");
}
}
// File: SubpackageDemo.java
import in.example.core.Greeting;
public class SubpackageDemo {
public static void main(String[] args) {
Greeting g = new Greeting();
g.greet();
}
}Write a Java program with a class Calculator that has two static methods both named add(int a, int b) but with different return types: one returns int and the other returns double. In the main method, call Calculator.add(7, 5) and print the result. Explain what happens when you compile this program.
class Calculator {
static int add(int a, int b) { return a + b; }
static double add(int a, int b) { return a + b; }
}
class TestOverloading {
public static void main(String[] args) {
System.out.println(Calculator.add(7, 5));
}
}Write a Java program that demonstrates method overloading ambiguity due to type promotion. Create a class with two overloaded methods: one named 'calculate' that takes an int and a long, and another named 'calculate' that takes a long and an int. Both methods should print a distinct message. In the main method, call calculate(15, 15) and observe the compilation error. Explain why the ambiguity occurs.
class OverloadingAmbiguity {
void calculate(int a, long b) {
System.out.println("int-long method invoked");
}
void calculate(long a, int b) {
System.out.println("long-int method invoked");
}
public static void main(String[] args) {
OverloadingAmbiguity obj = new OverloadingAmbiguity();
obj.calculate(15, 15); // Compilation error: ambiguous method call
}
}Write a Java program that counts the number of vowels in a string using the charAt() method. The program should store the vowels in an ArrayList<Character>, use a helper method isVowel(char c) that checks membership in that list, and a method countVowels(String s) that loops with charAt(). In main, test it on two strings: "Rahul is learning Java at Pune." and "An apple a day keeps the doctor away." and print each string followed by its vowel count. Name the class VowelCounter.
import java.util.*;
public class VowelCounter {
ArrayList<Character> al;
VowelCounter() {
al = new ArrayList<Character>();
al.add('A'); al.add('E');
al.add('a'); al.add('e');
al.add('I'); al.add('O');
al.add('i'); al.add('o');
al.add('U'); al.add('u');
}
private boolean isVowel(char c) {
for (int i = 0; i < al.size(); i++) {
if (c == al.get(i)) {
return true;
}
}
return false;
}
public int countVowels(String s) {
int countVowel = 0;
int size = s.length();
for (int j = 0; j < size; j++) {
char c = s.charAt(j);
if (isVowel(c)) {
countVowel = countVowel + 1;
}
}
return countVowel;
}
public static void main(String[] args) {
VowelCounter obj = new VowelCounter();
String str = "Rahul is learning Java at Pune.";
int noOfVowel = obj.countVowels(str);
System.out.println("String: " + str);
System.out.println("Total number of vowels in the string are: " + noOfVowel + "\n");
str = "An apple a day keeps the doctor away.";
System.out.println("String: " + str);
noOfVowel = obj.countVowels(str);
System.out.println("Total number of vowels in the string are: " + noOfVowel);
}
}Write a Java program that demonstrates converting a string to lowercase using different locales. The program should define a string with mixed case, convert it to lowercase using the English locale and the Turkish locale, and print both results. Use the string "HELLO WORLD from JAVA".
import java.util.Locale;
public class LocaleLowerExample {
public static void main(String[] args) {
String s = "HELLO WORLD from JAVA";
String englishLower = s.toLowerCase(Locale.ENGLISH);
System.out.println(englishLower);
String turkishLower = s.toLowerCase(Locale.forLanguageTag("tr"));
System.out.println(turkishLower);
}
}Write a Java program that uses CharArrayWriter to hold the text "Bharat is great" in memory, then writes that same text into four files named p.txt, q.txt, r.txt and s.txt in the current directory, closes all file writers, and finally prints "Done".
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayDemo {
public static void main(String[] args) throws Exception {
CharArrayWriter out = new CharArrayWriter();
out.write("Bharat is great");
FileWriter f1 = new FileWriter("p.txt");
FileWriter f2 = new FileWriter("q.txt");
FileWriter f3 = new FileWriter("r.txt");
FileWriter f4 = new FileWriter("s.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Done");
}
}Write a Java program that takes the string "good morning" and converts it to upper case using two locales: Turkish (language tag "tr") and English (language tag "en"). Print the Turkish result first and then the English result, each on its own line.
import java.util.Locale;
public class UpperLocaleDemo {
public static void main(String[] args) {
String s = "good morning";
String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
String english = s.toUpperCase(Locale.forLanguageTag("en"));
System.out.println(turkish);
System.out.println(english);
}
}Write a Java program that demonstrates the PushbackInputStream class. The program should take the string "3@@4@56@@@78", read it byte by byte, and whenever two consecutive '@' characters are found, print "--" instead of them; otherwise print the character as it is. Use PushbackInputStream to push back a character when needed.
import java.io.*;
public class PushbackDemo {
public static void main(String[] args) throws Exception {
String text = "3@@4@56@@@78";
byte[] data = text.getBytes();
ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
PushbackInputStream push = new PushbackInputStream(byteStream);
int ch;
while ((ch = push.read()) != -1) {
if (ch == '@') {
int next = push.read();
if (next == '@') {
System.out.print("--");
} else {
push.unread(next);
System.out.print((char) ch);
}
} else {
System.out.print((char) ch);
}
}
}
}Write a Java program that demonstrates the PushbackReader class. The program should read characters from a char array containing the sequence: '7', '-', '-', '8', '-', '9', '1', '-', '-', '-', '2', '3'. For each character read, if it is a hyphen ('-'), read the next character. If the next character is also a hyphen, print "#*" (without a newline). Otherwise, push back the next character and print the hyphen. For all other characters, print them as they are. Use a CharArrayReader and a PushbackReader.import java.io.*;
public class PushbackReaderDemo {
public static void main(String[] args) throws Exception {
char[] data = {'7', '-', '-', '8', '-', '9', '1', '-', '-', '-', '2', '3'};
CharArrayReader charArrayReader = new CharArrayReader(data);
PushbackReader pushbackReader = new PushbackReader(charArrayReader);
int ch;
while ((ch = pushbackReader.read()) != -1) {
if (ch == '-') {
int next = pushbackReader.read();
if (next == '-') {
System.out.print("#*");
} else {
if (next != -1) {
pushbackReader.unread(next);
}
System.out.print((char) ch);
}
} else {
System.out.print((char) ch);
}
}
}
}Write a Java program that demonstrates the use of StringWriter. The program should read the contents of a file named "C://data//input.txt" using a BufferedReader (with UTF-8 encoding) and write the data to a StringWriter. Finally, print the contents of the StringWriter to the console. Handle any IOExceptions by declaring them in the main method.
import java.io.*;
public class StringWriterDemo {
public static void main(String[] args) throws IOException {
char[] buffer = new char[1024];
StringWriter writer = new StringWriter();
FileInputStream input = null;
BufferedReader reader = null;
try {
input = new FileInputStream("C://data//input.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, charsRead);
}
System.out.println(writer.toString());
} finally {
if (writer != null) writer.close();
if (reader != null) reader.close();
}
}
}Write a Java program to demonstrate that a private constructor prevents instantiation from outside the class. Create a class named 'Demo' with a private constructor and a method 'show' that prints "Private Constructor Demo". Then, in a main method, try to create an object of 'Demo' and observe the compile-time error. Your program should include the necessary classes and comments explaining the error.
class Demo {
private Demo() {
// private constructor
}
void show() {
System.out.println("Private Constructor Demo");
}
}
public class PrivateConstructorExample {
public static void main(String[] args) {
// Demo obj = new Demo(); // Compile-time error: Demo() has private access in Demo
System.out.println("Cannot create instance of Demo from outside the class due to private constructor.");
}
}Write a Java program that demonstrates the protected access modifier across packages. Create a public class Vehicle in package garage with a protected method showInfo() that prints "Vehicle info". Then create a class Car in package showroom that extends Vehicle and calls showInfo() from its own method display(). Finally, create a public class Main in package showroom whose main method creates a Car object and calls display().
// File: garage/Vehicle.java
package garage;
public class Vehicle {
protected void showInfo() {
System.out.println("Vehicle info");
}
}
// File: showroom/Car.java
package showroom;
import garage.Vehicle;
public class Car extends Vehicle {
public void display() {
showInfo();
}
}
// File: showroom/Main.java
package showroom;
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.display();
}
}
Write a Java program to demonstrate that when overriding a method, the overriding method in the subclass cannot have a more restrictive access modifier than the overridden method. Create a superclass `Vehicle` with a protected method `display()` that prints "Vehicle display", and a subclass `Car` that overrides `display()` with the same protected access. Then, in a main method, create a `Car` object and call `display()`.
class Vehicle {
protected void display() {
System.out.println("Vehicle display");
}
}
class Car extends Vehicle {
@Override
protected void display() {
System.out.println("Car display");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.display();
}
}Write a Java program that demonstrates why multiple inheritance of classes causes ambiguity but can be achieved cleanly using interfaces. Create two interfaces, Greetable (with method greet()) and Wishing (with method wish()), both declaring a method with the same name greet(). Then create a class FestivalGreeter that implements both interfaces and provides a single implementation of greet() that prints "Namaste" and a wish() method that prints "Happy Diwali". In main, create a FestivalGreeter object and call both methods.
interface Greetable {
void greet();
}
interface Wishing {
void greet();
void wish();
}
class FestivalGreeter implements Greetable, Wishing {
public void greet() {
System.out.println("Namaste");
}
public void wish() {
System.out.println("Happy Diwali");
}
public static void main(String[] args) {
FestivalGreeter obj = new FestivalGreeter();
obj.greet();
obj.wish();
}
}Write a Java program to demonstrate a default method in an interface. Create an interface 'Vehicle' with an abstract method 'start()' and a default method 'honk()' that prints "Beep beep!". Then create a class 'Car' that implements 'Vehicle' and provides an implementation of 'start()' that prints "Car starting...". In the main method, create a 'Car' object, call 'start()' and 'honk()'.
interface Vehicle {
void start();
default void honk() {
System.out.println("Beep beep!");
}
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starting...");
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.start();
v.honk();
}
}Write a Java program using nested if statements. Declare a String variable address with the value "Pune, India". First check whether the address ends with "India". If it does, then check inside: if the address contains "Mumbai" print "Your city is Mumbai"; else if it contains "Nagpur" print "Your city is Nagpur"; otherwise print the part of the address before the comma (the city name). If the address does not end with "India", print "You are not living in India".
public class Resident {
public static void main(String[] args) {
String address = "Pune, India";
if (address.endsWith("India")) {
if (address.contains("Mumbai")) {
System.out.println("Your city is Mumbai");
} else if (address.contains("Nagpur")) {
System.out.println("Your city is Nagpur");
} else {
System.out.println(address.split(",")[0]);
}
} else {
System.out.println("You are not living in India");
}
}
}Write a Java program that demonstrates a member inner class accessing a private field of the outer class. Create an outer class named 'BankAccount' with a private integer field 'balance' initialized to 5000. Inside it, define a non-static inner class 'Transaction' with a method 'showBalance()' that prints the balance. In the main method, create an instance of BankAccount, then create an instance of the inner class using the outer instance, and call showBalance().
class BankAccount {
private int balance = 5000;
class Transaction {
void showBalance() {
System.out.println("Balance is " + balance);
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
BankAccount.Transaction txn = account.new Transaction();
txn.showBalance();
}
}Write a Java program that demonstrates a member inner class. Create an outer class Bank with a private integer field balance = 5000 and a member inner class Auditor that has a method showBalance() printing "Balance is " followed by the outer class's private balance. In main, create a Bank object, then create an Auditor object using it, and call showBalance().
class Bank {
private int balance = 5000;
class Auditor {
void showBalance() {
System.out.println("Balance is " + balance);
}
}
}
public class InnerClassDemo {
public static void main(String args[]) {
Bank bank = new Bank();
Bank.Auditor auditor = bank.new Auditor();
auditor.showBalance();
}
}Write a Java program that demonstrates handling a checked exception. The program should try to create a PrintWriter for a file named "notes.txt", write the line "stored" into it, and catch the FileNotFoundException using a try-catch block. After the try-catch, print "File stored successfully". Name the class CheckedDemo.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CheckedDemo {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("notes.txt"); // may throw checked exception
pw.println("stored");
pw.close(); // flush so the line is actually written
}
// handler for the checked exception
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File stored successfully");
}
}Write a Java program where a try block performs a division that throws an ArithmeticException, and the catch block itself also performs a division by zero (which throws an exception inside the catch block). Use the values 60 and 0 for the division in the try block, and 60 and 0 again in the catch block. After the try-catch, print "remaining code". Name the class CatchInsideCatch.
public class CatchInsideCatch {
public static void main(String[] args) {
try {
int result1 = 60 / 0; // may throw ArithmeticException
} catch (Exception e) {
// generating an exception inside the catch block
int result2 = 60 / 0; // may throw ArithmeticException
}
System.out.println("remaining code");
}
}Write a Java program that, inside a try block, computes int result = 40 / 0 (which throws an ArithmeticException), but the catch block is written for ArrayIndexOutOfBoundsException. Show what happens when the program runs.
public class MismatchCatchDemo {
public static void main(String[] args) {
try {
int result = 40 / 0; // throws ArithmeticException
}
// trying to handle ArithmeticException using ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("rest of the code");
}
}Write a Java program that demonstrates thread states. Create a class named Task that implements Runnable. In its run() method, first call Thread.sleep(100) inside a try-catch block (this moves the thread into the TIMED_WAITING state). Then print the state of a thread reference t1 using Thread.currentThread() context, i.e. print the state of the main thread while the sleeping thread is in timed waiting. After that, call Thread.sleep(200) inside another try-catch block. The main method should create a Thread t1 from a Task object, start it, and then print the state of t1.
class Task implements Runnable {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("State of the main thread while the task thread is in timed waiting: " + Thread.currentThread().getState());
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public class ThreadStateDemo {
public static void main(String[] args) {
Task task = new Task();
Thread t1 = new Thread(task);
t1.start();
System.out.println("State of t1 after start(): " + t1.getState());
}
}Write a Java program that demonstrates a synchronized block. Create a class Table with a method printTable(int n) that prints the multiplication table of n from 1 to 5, with a 300 ms pause between each line. The method should use a synchronized block on 'this' to ensure that only one thread prints the table at a time. In the main method, create two threads that share the same Table object and call printTable with different numbers. Start both threads and wait for them to finish.
class Table {
void printTable(int n) {
synchronized (this) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
public class SyncBlockDemo {
public static void main(String[] args) {
Table table = new Table();
Thread t1 = new Thread(new Runnable() {
public void run() {
table.printTable(5);
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
table.printTable(100);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
}Write a Java program that demonstrates a synchronized block using an anonymous class. Create a class Messenger with a method sendMessage(String msg) that prints the message, sleeps for 500 milliseconds, and then prints that the message was sent. In the main method, create a Messenger object, then create two threads using anonymous inner classes that each call sendMessage with different messages, synchronizing on the Messenger object. Start both threads and wait for them to finish.
class Messenger {
public void sendMessage(String msg) {
System.out.println("\nSending: " + msg);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println(msg + " sent");
}
}
public class SyncAnonymousDemo {
public static void main(String[] args) {
Messenger messenger = new Messenger();
Thread t1 = new Thread(new Runnable() {
public void run() {
synchronized (messenger) {
messenger.sendMessage("Hello");
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
synchronized (messenger) {
messenger.sendMessage("Welcome to the Java tutorial");
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}Write a Java program that demonstrates inter-thread communication using PipedReader and PipedWriter. One thread should write the text "Jai Hind from Bharat\n" into a PipedWriter, and another thread should read it character by character from a connected PipedReader and print each character to the console.
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipeDemo {
public static void main(String[] args) {
try {
final PipedReader reader = new PipedReader();
final PipedWriter writer = new PipedWriter(reader);
Thread readerThread = new Thread(new Runnable() {
public void run() {
try {
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception ex) {
}
}
});
Thread writerThread = new Thread(new Runnable() {
public void run() {
try {
writer.write("Jai Hind from Bharat\n".toCharArray());
} catch (Exception ex) {
}
}
});
readerThread.start();
writerThread.start();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}Write a Java program that reads a text file named "input.txt" containing the line "I love my India". The program should replace every space character with an underscore '_' and print the modified content to the console. Use a custom FilterReader to perform the replacement.
import java.io.*;
class SpaceToUnderscoreFilter extends FilterReader {
SpaceToUnderscoreFilter(Reader in) {
super(in);
}
public int read() throws IOException {
int c = super.read();
if ((char) c == ' ') {
return '_';
} else {
return c;
}
}
}
public class FilterReaderDemo {
public static void main(String[] args) {
try {
Reader reader = new FileReader("input.txt");
SpaceToUnderscoreFilter filter = new SpaceToUnderscoreFilter(reader);
int ch;
while ((ch = filter.read()) != -1) {
System.out.print((char) ch);
}
filter.close();
reader.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}Write a Java program that demonstrates FileDescriptor operations. The program should: create a file named "Notes.txt", write the byte values {65, 66, 67, 68, 69} to it using a FileOutputStream, flush the stream, obtain the FileDescriptor via getFD(), call sync() on it to force buffers to the underlying device, then read the file back with a FileInputStream and print each byte as a character. Finally print whether the descriptor is valid using valid() and print a success message.import java.io.*;
public class DescriptorDemo {
public static void main(String[] args) {
FileDescriptor fd = null;
byte[] data = {65, 66, 67, 68, 69};
try {
FileOutputStream fos = new FileOutputStream("Notes.txt");
FileInputStream fis = new FileInputStream("Notes.txt");
fd = fos.getFD();
fos.write(data);
fos.flush();
fd.sync(); // force buffers to synchronize with the device
int value = 0;
while ((value = fis.read()) != -1) {
char c = (char) value;
System.out.print(c);
}
System.out.println("\nDescriptor valid: " + fd.valid());
System.out.println("sync() executed successfully!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}Write a Java program that demonstrates covariant return types. Create a base class Vehicle with a method getVehicle() that returns a Vehicle object (returning this). Create a subclass Car that overrides getVehicle() so it returns a Car object instead of Vehicle. In the main method, create a Car object, call getVehicle() on it, and print a message showing which class the returned object belongs to. FileName: VehicleDemo.java
class Vehicle {
Vehicle getVehicle() {
return this;
}
}
class Car extends Vehicle {
@Override
Car getVehicle() {
return this;
}
}
public class VehicleDemo {
public static void main(String[] args) {
Car c = new Car();
Car returned = c.getVehicle();
System.out.println("Returned object is of type: " + returned.getClass().getSimpleName());
}
}Write a Java program that demonstrates the covariant return type. Create a class Vehicle with a method getDetails() that returns a Vehicle object and prints "Vehicle details". Create a subclass Car that overrides getDetails() so that its return type is Car (a subtype of Vehicle) and prints "Car details". In main(), create a Car object, call getDetails() through a Vehicle reference and through a Car reference, and show that no explicit cast is needed.
class Vehicle {
Vehicle getDetails() {
System.out.println("Vehicle details");
return this;
}
}
class Car extends Vehicle {
@Override
Car getDetails() {
System.out.println("Car details");
return this;
}
}
public class Main {
public static void main(String[] args) {
Vehicle v = new Car();
v.getDetails();
Car c = new Car();
Car result = c.getDetails();
System.out.println(result instanceof Car);
}
}Write a Java program that demonstrates using both an abstract class and an interface together. Create an interface Payment with four methods: pay(), refund(), checkStatus() and cancel(). Create an abstract class OnlinePayment that implements Payment and provides a concrete implementation of checkStatus() that prints "Status checked". Then create a class UpiPayment that extends OnlinePayment and implements the remaining three methods, each printing a short message ("Paid via UPI", "Refunded via UPI", "Cancelled via UPI"). In main(), create a UpiPayment object and call all four methods.interface Payment {
void pay();
void refund();
void checkStatus();
void cancel();
}
abstract class OnlinePayment implements Payment {
public void checkStatus() {
System.out.println("Status checked");
}
}
class UpiPayment extends OnlinePayment {
public void pay() {
System.out.println("Paid via UPI");
}
public void refund() {
System.out.println("Refunded via UPI");
}
public void cancel() {
System.out.println("Cancelled via UPI");
}
}
public class Main {
public static void main(String[] args) {
UpiPayment p = new UpiPayment();
p.pay();
p.refund();
p.checkStatus();
p.cancel();
}
}Write a Java program to multiply two 2×2 matrices and print the resulting matrix. Use matrix A = {{2, 3}, {4, 5}} and matrix B = {{1, 2}, {3, 4}}. The element at row i, column j of the product is the sum over k of A[i][k] * B[k][j].public class MatrixMultiply {
public static void main(String[] args) {
int a[][] = {{2, 3}, {4, 5}};
int b[][] = {{1, 2}, {3, 4}};
int c[][] = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = 0;
for (int k = 0; k < 2; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}Write a Java program that demonstrates how the compiler generates an internal class for a local inner class. The program should have an outer class named OuterDemo with a private instance variable, and a method that defines a local inner class named InnerLocal which prints the outer class's private variable. The compiler will generate a class like OuterDemo$1InnerLocal that holds a reference to the outer class instance.
public class OuterDemo {
private int value = 45;
void show() {
class InnerLocal {
void display() {
System.out.println(value);
}
}
InnerLocal inner = new InnerLocal();
inner.display();
}
public static void main(String[] args) {
OuterDemo obj = new OuterDemo();
obj.show();
}
}Write a Java program with an outer class named OuterDemo that has a private instance variable data = 30 and a method display(). Inside display(), declare a local variable value = 50 and define a local inner class Inner with a method msg() that prints value. In display(), create an Inner object and call msg(). In main(), create an OuterDemo object and call display().
class OuterDemo {
private int data = 30;
void display() {
int value = 50;
class Inner {
void msg() {
System.out.println(value);
}
}
Inner i = new Inner();
i.msg();
}
public static void main(String[] args) {
OuterDemo obj = new OuterDemo();
obj.display();
}
}Write a Java program to demonstrate static synchronization. Create a class 'MathTable' with a static synchronized method 'printTable(int n)' that prints the first 5 multiples of n (n*1 to n*5), sleeping 200 ms after each print. Create two thread classes: one calls MathTable.printTable(2) and the other calls MathTable.printTable(5). In main, start both threads. Explain why static synchronization prevents interference between them.
class MathTable {
synchronized static void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(200);
} catch (Exception e) {
}
}
}
}
class ThreadA extends Thread {
public void run() {
MathTable.printTable(2);
}
}
class ThreadB extends Thread {
public void run() {
MathTable.printTable(5);
}
}
public class StaticSyncDemo {
public static void main(String[] args) {
ThreadA t1 = new ThreadA();
ThreadB t2 = new ThreadB();
t1.start();
t2.start();
}
}Write a Java program that demonstrates static synchronization using anonymous classes to create the threads. Create a class named 'Counter' with a static synchronized method 'showMultiples(int n)' that prints the first 5 multiples of n (n*1 to n*5), pausing 300 ms between prints. In the main method, create two threads using anonymous inner classes: one calls Counter.showMultiples(3) and the other calls Counter.showMultiples(7). Start both threads.
class Counter {
synchronized static void showMultiples(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(300);
} catch (Exception e) {
}
}
}
}
public class StaticSyncAnonymous {
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
Counter.showMultiples(3);
}
};
Thread t2 = new Thread() {
public void run() {
Counter.showMultiples(7);
}
};
t1.start();
t2.start();
}
}Write a Java program that demonstrates a deadlock scenario. Create two String objects: resource1 = "resourceA" and resource2 = "resourceB". Create two threads: Thread-1 locks resource1, then sleeps for 100 ms, then tries to lock resource2 and prints "Thread-1: locked both resources". Thread-2 locks resource2, then sleeps for 100 ms, then tries to lock resource1 and prints "Thread-2: locked both resources". Start both threads. The program will likely deadlock because each thread holds one lock and waits for the other.
public class DeadlockDemo {
public static void main(String[] args) {
final String resource1 = "resourceA";
final String resource2 = "resourceB";
Thread t1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread-1: locked resource1");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resource2) {
System.out.println("Thread-1: locked both resources");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (resource2) {
System.out.println("Thread-2: locked resource2");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resource1) {
System.out.println("Thread-2: locked both resources");
}
}
});
t1.start();
t2.start();
}
}Write a Java program that demonstrates how to avoid deadlock by ensuring a consistent lock ordering. Create two resource classes, ResourceA and ResourceB, each with a private integer field (e.g., valueA=100, valueB=200) and getter/setter methods. In the main method, create one instance of each resource. Create two threads: Thread-1 acquires the lock on ResourceA first, then after a short delay acquires the lock on ResourceB, and prints "Thread-1 acquired both resources". Thread-2 acquires the lock on ResourceA first, then after a short delay acquires the lock on ResourceB, and prints "Thread-2 acquired both resources". Both threads must acquire locks in the same order (ResourceA then ResourceB) to prevent deadlock. Start both threads.
public class DeadlockAvoidance {
static class ResourceA {
private int value = 100;
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
}
static class ResourceB {
private int value = 200;
public int getValue() { return value; }
public void setValue(int value) { this.value = value; }
}
public static void main(String[] args) {
final ResourceA a = new ResourceA();
final ResourceB b = new ResourceB();
Thread t1 = new Thread(() -> {
synchronized (a) {
System.out.println("Thread-1: locked ResourceA");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (b) {
System.out.println("Thread-1 acquired both resources");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (a) {
System.out.println("Thread-2: locked ResourceA");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (b) {
System.out.println("Thread-2 acquired both resources");
}
}
});
t1.start();
t2.start();
}
}Write a Java program that demonstrates nested try blocks handling two different exceptions. In the outer try block, place two inner try blocks: the first inner try divides 84 by 0 (catching ArithmeticException), and the second inner try stores a value at index 6 of an int array of size 6 (catching ArrayIndexOutOfBoundsException). After both inner try blocks, print "remaining statement". The outer try has a catch for Exception that prints "outer catch handled". Finally, after the outer try-catch, print "program ended".
public class NestedTryDemo {
public static void main(String[] args) {
try {
try {
System.out.println("attempting division by zero");
int q = 84 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
try {
int arr[] = new int[6];
arr[6] = 9;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("remaining statement");
} catch (Exception e) {
System.out.println("outer catch handled");
}
System.out.println("program ended");
}
}Write a Java program that shows that calling the String contains() method with null as the argument throws a NullPointerException. Create a String variable named text with the value "Hello India!". Then, inside a try block, check if(text.contains(null)) and print "Inside the if block" if true, otherwise print "Inside the else block". Add a catch block for NullPointerException that prints "Null is not allowed".
public class ContainsNullDemo {
public static void main(String[] args) {
String text = "Hello India!";
try {
if (text.contains(null)) {
System.out.println("Inside the if block");
} else {
System.out.println("Inside the else block");
}
} catch (NullPointerException e) {
System.out.println("Null is not allowed");
}
}
}Write a Java program that demonstrates a static nested class containing a static method. The outer class should have a static variable `count = 45`. The static nested class `Helper` should have a static method `show()` that prints "count is " followed by the value of `count`. In `main`, call the static method directly through the nested class name without creating any instance of the nested class.
public class OuterDemo {
static int count = 45;
static class Helper {
static void show() {
System.out.println("count is " + count);
}
}
public static void main(String args[]) {
OuterDemo.Helper.show(); // no instance of static nested class needed
}
}Write a Java program that shows what the compiler-generated class file for a static nested class looks like. The outer class `TestOuter1` should have a static variable `data = 25` and a static nested class `Inner` with a method `msg()` that prints "data is " followed by `data`. In `main`, create an instance of `Inner` and call `msg()`. Also show, as a comment or a separate demonstration class, the equivalent compiler-generated form of the nested class named `TestOuter1$Inner` that uses a StringBuilder to build the output string.
public class TestOuter1 {
static int data = 25;
static class Inner {
void msg() {
System.out.println("data is " + data);
}
}
public static void main(String args[]) {
TestOuter1.Inner obj = new TestOuter1.Inner();
obj.msg();
}
}
// Compiler-generated equivalent of the nested class:
// static class TestOuter1$Inner {
// TestOuter1$Inner() {}
// void msg() {
// System.out.println((new StringBuilder()).append("data is ")
// .append(TestOuter1.data).toString());
// }
// }Write a Java program that uses labeled loops to print pairs of numbers (i, j) for i from 1 to 4 and j from 1 to 4, but stops completely when i equals 3 and j equals 2. Use a label on the outer loop and a break statement to exit both loops when that condition is met.
public class LabeledLoopDemo {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 4; i++) {
inner:
for (int j = 1; j <= 4; j++) {
if (i == 3 && j == 2) {
break outer;
}
System.out.println(i + " " + j);
}
}
}
}Write a Java program that reads a text file named "notes.txt" (located in the current working directory) byte by byte using a BufferedInputStream wrapped around a FileInputStream, and prints each character to the console. Close both streams at the end and handle any exceptions by printing the exception.
import java.io.*;
public class BufferedReadDemo{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("notes.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int c;
while((c=bin.read())!=-1){
System.out.print((char)c);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}Write a Java program with a thread class whose run() method loops twice; in each iteration it checks Thread.interrupted() and prints "interrupted thread code" if true, otherwise prints "normal thread code". In main, create two such threads t1 and t2, start t1 and immediately interrupt it, then start t2 without interrupting it.
public class InterruptDemo extends Thread {
public void run() {
for (int i = 1; i <= 2; i++) {
if (Thread.interrupted()) {
System.out.println("interrupted thread code");
} else {
System.out.println("normal thread code");
}
}
}
public static void main(String[] args) {
InterruptDemo t1 = new InterruptDemo();
InterruptDemo t2 = new InterruptDemo();
t1.start();
t1.interrupt();
t2.start();
}
}Write a Java program that uses a labeled break statement to exit an outer loop from within 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 outer loop using a label. Otherwise, print the values of the outer and inner loop variables separated by a space. Use the label 'outer:' for the outer loop.
public class LabeledBreakDemo {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 4; j++) {
if (i == 3 && j == 2) {
break outer;
}
System.out.println(i + " " + j);
}
}
}
}Write a Java program that uses SequenceInputStream to read and print the contents of two files, first.txt and second.txt, one after the other. Use FileInputStream objects for both files and close all streams at the end.
import java.io.*;
public class SequenceDemo {
public static void main(String[] args) throws Exception {
FileInputStream f1 = new FileInputStream("first.txt");
FileInputStream f2 = new FileInputStream("second.txt");
SequenceInputStream seq = new SequenceInputStream(f1, f2);
int ch;
while ((ch = seq.read()) != -1) {
System.out.print((char) ch);
}
seq.close();
f1.close();
f2.close();
}
}Write a Java program that uses SequenceInputStream with an Enumeration to read the contents of four files — part1.txt, part2.txt, part3.txt and part4.txt — one after another and print the combined data to the console. Create a Vector, add the four FileInputStream objects to it, obtain an Enumeration by calling elements(), pass that Enumeration to the SequenceInputStream constructor, and then read and print every byte until end of stream. Close the streams at the end.
import java.io.*;
import java.util.*;
public class MultiFileReader {
public static void main(String[] args) throws IOException {
FileInputStream f1 = new FileInputStream("part1.txt");
FileInputStream f2 = new FileInputStream("part2.txt");
FileInputStream f3 = new FileInputStream("part3.txt");
FileInputStream f4 = new FileInputStream("part4.txt");
Vector<FileInputStream> v = new Vector<>();
v.add(f1);
v.add(f2);
v.add(f3);
v.add(f4);
Enumeration<FileInputStream> e = v.elements();
SequenceInputStream bin = new SequenceInputStream(e);
int i;
while ((i = bin.read()) != -1) {
System.out.print((char) i);
}
bin.close();
f1.close();
f2.close();
f3.close();
f4.close();
}
}Write a Java program that demonstrates throwing a checked exception. Create a class named FileCheckDemo with a static method readConfig() that declares throws FileNotFoundException. Inside readConfig(), create a FileReader for the path "D:\\Office\\Ramesh\\config.txt" wrapped in a BufferedReader, then explicitly throw a new FileNotFoundException(). In main(), call readConfig() inside a try block, catch FileNotFoundException and print its stack trace, then print "remaining code...".
import java.io.*;
public class FileCheckDemo {
// method that declares a checked exception
public static void readConfig() throws FileNotFoundException {
FileReader file = new FileReader("D:\\Office\\Ramesh\\config.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
// main method
public static void main(String args[]) {
try {
readConfig();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("remaining code...");
}
}Write a Java program to demonstrate throwing a user-defined exception. Define a custom exception class 'InvalidAgeException' that extends Exception. In the main method, throw an object of InvalidAgeException with the message "Age must be above 18", catch it, and print "Caught the exception" followed by the exception message.
class InvalidAgeException extends Exception {
public InvalidAgeException(String str) {
super(str);
}
}
public class TestCustomException {
public static void main(String[] args) {
try {
throw new InvalidAgeException("Age must be above 18");
} catch (InvalidAgeException e) {
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
}Write a Java program to demonstrate the use of the super keyword to call a parent class constructor from a child class. Create a parent class 'Vehicle' with fields 'regNo' (int) and 'model' (String), and a constructor to initialize them. Create a child class 'Car' that extends 'Vehicle' and adds a field 'price' (double). The child class constructor should accept regNo, model, and price, and use super(regNo, model) to initialize the inherited fields. Include a method 'display()' in the child class to print the details. In the main method, create a Car object with regNo 101, model "Hyundai", and price 750000.0, and call display().
class Vehicle {
int regNo;
String model;
Vehicle(int regNo, String model) {
this.regNo = regNo;
this.model = model;
}
}
class Car extends Vehicle {
double price;
Car(int regNo, String model, double price) {
super(regNo, model);
this.price = price;
}
void display() {
System.out.println(regNo + " " + model + " " + price);
}
}
public class TestSuper {
public static void main(String[] args) {
Car c1 = new Car(101, "Hyundai", 750000.0);
c1.display();
}
}Write a Java program that demonstrates the ByteArrayOutputStream class. The program should write the byte value 66 into a ByteArrayOutputStream and then copy that same data into two files, notes1.txt and notes2.txt, using writeTo(). Finally print "Done" to the console.
import java.io.*;
public class ByteArrayDemo {
public static void main(String args[]) throws Exception {
FileOutputStream out1 = new FileOutputStream("notes1.txt");
FileOutputStream out2 = new FileOutputStream("notes2.txt");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(66);
bout.writeTo(out1);
bout.writeTo(out2);
bout.flush();
bout.close(); // has no effect on a ByteArrayOutputStream
out1.close();
out2.close();
System.out.println("Done");
}
}Write a Java program to demonstrate exception propagation. Create a class ExceptionPropagationDemo with three methods: method1(), method2(), and method3(). In method1(), perform an integer division by zero (e.g., int result = 100 / 0;). method2() calls method1(). method3() calls method2() inside a try-catch block that catches Exception and prints "Exception caught". In the main method, create an object and call method3(), then print "Program continues". Show that the unchecked exception propagates from method1 to method3 where it is handled.
public class ExceptionPropagationDemo {
void method1() {
int result = 100 / 0;
}
void method2() {
method1();
}
void method3() {
try {
method2();
} catch (Exception e) {
System.out.println("Exception caught");
}
}
public static void main(String[] args) {
ExceptionPropagationDemo demo = new ExceptionPropagationDemo();
demo.method3();
System.out.println("Program continues");
}
}Write a Java program that demonstrates exception propagation using the throws keyword. Create a class 'Demo' with three methods: methodA() that throws an IOException with message "Input error", methodB() that calls methodA() and declares throws IOException, and methodC() that calls methodB() inside a try-catch block catching Exception and printing "Exception handled". In the main method, create a Demo object, call methodC(), and then print "Execution completed". The program should compile and run without errors.
import java.io.IOException;
class Demo {
void methodA() throws IOException {
throw new IOException("Input error");
}
void methodB() throws IOException {
methodA();
}
void methodC() {
try {
methodB();
} catch (Exception e) {
System.out.println("Exception handled");
}
}
}
public class ExceptionPropagation {
public static void main(String[] args) {
Demo obj = new Demo();
obj.methodC();
System.out.println("Execution completed");
}
}Write a Java program to demonstrate that Java monitors are reentrant. Create a class ReentrantDemo with two synchronized methods: outer() and inner(). The outer() method should call inner() and then print "Inside outer method". The inner() method should print "Inside inner method". In the main method, create an object of ReentrantDemo and call outer(). Show that a thread can reacquire the same monitor when calling a synchronized method from another synchronized method of the same object.
public class ReentrantDemo {
public synchronized void outer() {
inner();
System.out.println("Inside outer method");
}
public synchronized void inner() {
System.out.println("Inside inner method");
}
public static void main(String[] args) {
ReentrantDemo demo = new ReentrantDemo();
demo.outer();
}
}Write a Java program that demonstrates a static blank final variable. Declare a static final int variable named 'marks' without initializing it at declaration, initialize it inside a static block to 85, and then print its value from the main method.
class Student {
static final int marks; // static blank final variable
static {
marks = 85;
}
public static void main(String args[]) {
System.out.println(Student.marks);
}
}Write a Java program that prints the class loader of the current class and the class loader of the String class. Explain why the output for String is null.
public class ClassLoaderDemo {
public static void main(String[] args) {
Class<?> cls = ClassLoaderDemo.class;
System.out.println(cls.getClassLoader());
System.out.println(String.class.getClassLoader());
}
}Write a Java program that demonstrates the String.format() method. Use a student name "Aarav" and print: (1) a string "student is Aarav" using %s, (2) a string "marks are 78.456000" using %f on the value 78.456, and (3) a string where the same value 78.456 is formatted with width 30 and 10 digits after the decimal point using %30.10f. Print all three results on separate lines.
public class FormatDemo {
public static void main(String[] args) {
String name = "Aarav";
String s1 = String.format("student is %s", name);
String s2 = String.format("marks are %f", 78.456);
String s3 = String.format("marks are %30.10f", 78.456);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}Write a Java program that uses String.format() to format different data types into strings. Format the following values: an integer 305, a string "Priya Sharma", a float 305.00, the hexadecimal representation of 305, and the character 'k'. Print each formatted string on a new line.
public class FormatDataTypes {
public static void main(String[] args) {
String str1 = String.format("%d", 305);
String str2 = String.format("%s", "Priya Sharma");
String str3 = String.format("%f", 305.00);
String str4 = String.format("%x", 305);
String str5 = String.format("%c", 'k');
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}Write a Java program that demonstrates formatting an integer with width and padding using String.format(). Specifically, format the integer 250 in the following ways: (1) as a plain integer, (2) right-aligned in a width of 8 characters, (3) left-aligned in a width of 8 characters, (4) with a leading space for positive numbers (using '% d'), and (5) zero-padded to a total width of 8 characters. Print each formatted string on a new line.
public class FormatWidthPadding {
public static void main(String[] args) {
String str1 = String.format("%d", 250);
String str2 = String.format("|%8d|", 250);
String str3 = String.format("|%-8d|", 250);
String str4 = String.format("|% d|", 250);
String str5 = String.format("|%08d|", 250);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}Write a Java program that demonstrates that calling join() on a thread which gets interrupted throws InterruptedException. Create a class named Worker that extends Thread and stores a reference to another thread (the one to be interrupted). In its run() method, it should call interrupt() on that stored thread. In main, create a thread 'helper' that simply sleeps for a long time, start it, create a Worker thread passing 'helper' as the thread to interrupt, start the worker, and then call helper.join() inside a try-catch so that the InterruptedException is caught and its message printed. Name the file InterruptJoinDemo.java.
public class InterruptJoinDemo {
static class Worker extends Thread {
Thread threadToInterrupt;
Worker(Thread t) {
this.threadToInterrupt = t;
}
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
threadToInterrupt.interrupt();
}
}
public static void main(String[] args) {
Thread helper = new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
});
helper.start();
// the worker interrupts the main thread, which is blocked in helper.join()
Worker w = new Worker(Thread.currentThread());
w.start();
try {
helper.join();
} catch (InterruptedException e) {
System.out.println("join() threw InterruptedException: " + e.getMessage());
}
helper.interrupt();
System.out.println("Main finished");
}
}Write a Java program named JoinTimeoutDemo.java that creates three threads of the same class. Each thread's run() method prints the numbers 1 to 4, pausing 400 milliseconds before each number. In main, start the first thread and call join(1200) on it (handling InterruptedException), then start the second and third threads.
class JoinTimeoutDemo extends Thread {
public void run() {
for (int i = 1; i <= 4; i++) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
JoinTimeoutDemo t1 = new JoinTimeoutDemo();
JoinTimeoutDemo t2 = new JoinTimeoutDemo();
JoinTimeoutDemo t3 = new JoinTimeoutDemo();
t1.start();
try {
t1.join(1200);
} catch (InterruptedException e) {
System.out.println(e);
}
t2.start();
t3.start();
}
}Write a Java program where a method declares that it may throw an IOException using the throws keyword, but no exception actually occurs. The method should print "payment processed" and the main method (which also declares throws IOException) should call it and then print "normal flow...". Show that the program runs fine when the exception does not occur.
import java.io.*;
class PaymentService {
void processPayment() throws IOException {
System.out.println("payment processed");
}
}
public class TestThrowsDemo {
public static void main(String args[]) throws IOException { // declare exception
PaymentService ps = new PaymentService();
ps.processPayment();
System.out.println("normal flow...");
}
}Write a Java program (file: WorkerThread.java) that shows that a thread cannot be made a daemon after it has been started. Create a class WorkerThread extending Thread whose run() prints the current thread's name and whether it is a daemon. In main, create two WorkerThread objects, start the first one, then call setDaemon(true) on it (which must throw IllegalThreadStateException), and finally start the second thread.
public class WorkerThread extends Thread {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Name: " + Thread.currentThread().getName());
System.out.println("Daemon: " + Thread.currentThread().isDaemon());
}
public static void main(String[] args) {
WorkerThread w1 = new WorkerThread();
WorkerThread w2 = new WorkerThread();
w1.start();
try {
w1.setDaemon(true); // throws IllegalThreadStateException
} catch (IllegalThreadStateException e) {
System.out.println("Cannot set daemon after start: " + e);
}
w2.start();
}
}Write a Java program in a file named TestThrow.java with a method checkNum(int num) that throws an ArithmeticException with the message "Number is negative, cannot calculate square" if num is less than 1; otherwise it prints "Square of <num> is <num*num>". In main(), create an object of the class, call checkNum(-3), and then print "Rest of the code..".
public class TestThrow {
// method that validates the number before squaring
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("Number is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num * num));
}
}
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}Write a Java program in a file named TestThrowAndThrows.java that demonstrates the use of 'throws' and 'throw'. Create a static method called method() that declares 'throws ArithmeticException', prints "Inside the method()", and then throws a new ArithmeticException with the message "throwing ArithmeticException". In main(), call method() inside a try block and catch ArithmeticException, printing "caught in main() method" in the catch block.
public class TestThrowAndThrows
{
// user-defined method that declares it may throw ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}Write a Java program that demonstrates whether Java comments are executed. The program should include a comment containing a Unicode escape sequence that, when processed, causes a statement to be executed. The program should print a message indicating that the comment was executed. Use the class name 'Demo'.
public class Demo {
public static void main(String[] args) {
// This comment will be executed
// \u000d System.out.println("Comment executed!");
}
}Write a Java program that uses the DataOutputStream class to write an integer value 75 to a text file named dataout.txt on the D: drive, flush and close the stream, and then print "Done..." to the console.
import java.io.*;
public class DataOutputDemo {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream("D:\\dataout.txt");
DataOutputStream data = new DataOutputStream(file);
data.writeInt(75);
data.flush();
data.close();
System.out.println("Done...");
}
}Write a Java program that demonstrates converting a String into byte arrays using different character encodings. Use the input string "Namaste India." and print the byte values (as integers) obtained from getBytes() for the charsets "UTF-16", "UTF-16BE", "ISO-8859-1" and "UTF-16LE". Handle the UnsupportedEncodingException with a try-catch block. Name the file CharsetBytesDemo.java.
import java.io.*;
public class CharsetBytesDemo
{
public static void main(String[] args)
{
String str = "Namaste India.";
System.out.println("The input String is : ");
System.out.println(str + "\n");
try
{
byte[] byteArr = str.getBytes("UTF-16");
System.out.println("After converted into UTF-16 the String is : ");
for (int j = 0; j < byteArr.length; j++)
{
System.out.print(byteArr[j]);
}
System.out.println("\n");
byte[] byteArr1 = str.getBytes("UTF-16BE");
System.out.println("After converted into UTF-16BE the String is : ");
for (int j = 0; j < byteArr1.length; j++)
{
System.out.print(byteArr1[j]);
}
System.out.println("\n");
byte[] byteArr2 = str.getBytes("ISO-8859-1");
System.out.println("After converted into ISO-8859-1 the String is : ");
for (int j = 0; j < byteArr2.length; j++)
{
System.out.print(byteArr2[j]);
}
System.out.println("\n");
byte[] byteArr3 = str.getBytes("UTF-16LE");
System.out.println("After converted into UTF-16LE the String is : ");
for (int j = 0; j < byteArr3.length; j++)
{
System.out.print(byteArr3[j]);
}
}
catch (UnsupportedEncodingException g)
{
System.out.println("Unsupported character set" + g);
}
}
}Write a Java program that demonstrates the getBytes() method of the String class when an unsupported character encoding is specified. The program should attempt to convert the string "Welcome to India." into bytes using the encoding "UTF-17". Since this encoding is not supported, the getBytes() method will throw an UnsupportedEncodingException. Handle this exception by printing the message "Unsupported encoding: UTF-17" to the standard error stream. The program should be in a class named StringGetBytesExample4.
public class StringGetBytesExample4 {
public static void main(String[] args) {
String str = "Welcome to India.";
System.out.println("The input String is: ");
System.out.println(str + "\n");
try {
byte[] byteArr = str.getBytes("UTF-17");
System.out.println("After converted into UTF-17 the String is: ");
for (int j = 0; j < byteArr.length; j++) {
System.out.print(byteArr[j]);
}
} catch (java.io.UnsupportedEncodingException e) {
System.err.println("Unsupported encoding: UTF-17");
}
}
}Write a Java program that demonstrates the three types of variables in Java: a static variable shared by all objects, an instance variable, and a local variable inside a method. Use a static variable marks = 80, an instance variable rollNo = 12, and a local variable count = 5 inside a method.
public class Student {
static int marks = 80; // static variable
int rollNo = 12; // instance variable
void show() {
int count = 5; // local variable
System.out.println(count);
}
public static void main(String[] args) {
Student s = new Student();
s.show();
System.out.println(marks);
System.out.println(s.rollNo);
}
}Write a Java program that assigns the int value 200 to an int variable, then narrows it to a byte variable using a cast. Print both the int value and the byte value.
public class ByteOverflowDemo {
public static void main(String[] args) {
int a = 200;
byte b = (byte)a;
System.out.println(a);
System.out.println(b);
}
}Write a Java program to demonstrate upcasting. Create a class Animal with a method sound() that prints "Animal makes a sound". Create a subclass Dog that extends Animal and overrides sound() to print "Dog barks". In the main method, create a Dog object and assign it to an Animal reference. Call sound() using that reference. What is the output?
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
a.sound();
}
}Write a Java program that demonstrates that runtime polymorphism cannot be achieved through data members. Create a parent class Vehicle with an integer data member maxSpeed = 80, and a child class Car (extends Vehicle) with its own data member maxSpeed = 120. In the main method, declare a Vehicle reference that points to a Car object, and print the value of maxSpeed accessed through that reference.
class Vehicle {
int maxSpeed = 80;
}
class Car extends Vehicle {
int maxSpeed = 120;
}
class TestPolymorphism {
public static void main(String[] args) {
Vehicle v = new Car();
System.out.println(v.maxSpeed);
}
}Write a Java program that demonstrates the legal usage of the strictfp keyword. Show that strictfp can be applied to a class, to an interface, and to a method. Create a strictfp class named Shape, a strictfp interface named Measurable, and inside the Shape class a strictfp method named computeArea that prints a message.
strictfp class Shape {
strictfp void computeArea() {
System.out.println("Computing area with strict floating-point precision");
}
}
strictfp interface Measurable {
double area();
}
class Main {
public static void main(String[] args) {
Shape s = new Shape();
s.computeArea();
}
}Write a Java program that demonstrates the illegal uses of the strictfp keyword: applying it to an abstract method, to an instance variable, and to a constructor. Show each illegal case in its own class so the compiler reports an error for each.
class A {
strictfp abstract void show(); // illegal: strictfp not allowed on abstract methods
}
class B {
strictfp int value = 25; // illegal: strictfp not allowed on variables
}
class C {
strictfp C() {} // illegal: strictfp not allowed on constructors
}Write a Java program that prints numbers from 1 to 30 using two threads: one thread prints odd numbers and the other prints even numbers, in order. Use a synchronized block and wait()/notify() for coordination. The output should be: 1 2 3 4 ... 30.
public class OddEvenPrinter {
private int count = 1;
private static final int MAX = 30;
public void printOdd() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public void printEven() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public static void main(String[] args) {
OddEvenPrinter printer = new OddEvenPrinter();
Thread t1 = new Thread(() -> printer.printOdd());
Thread t2 = new Thread(() -> printer.printEven());
t1.start();
t2.start();
}
}Write a Java program demonstrating inter-thread communication. Create a class Account with an int balance = 8000. It has a synchronized method withdraw(int amt) that prints "going to withdraw...", and if balance < amt prints "Less balance; waiting for deposit..." and calls wait(); otherwise it subtracts amt and prints "withdraw completed...". It also has a synchronized method deposit(int amt) that prints "going to deposit...", adds amt to balance, prints "deposit completed..." and calls notify(). In main, start one thread that withdraws 10000 and another thread that deposits 3000 after a short delay.
class Account{
int balance=8000;
synchronized void withdraw(int amt){
System.out.println("going to withdraw...");
if(this.balance<amt){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.balance-=amt;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amt){
System.out.println("going to deposit...");
this.balance+=amt;
System.out.println("deposit completed...");
notify();
}
}
public class InterThreadDemo{
public static void main(String args[]){
final Account a=new Account();
new Thread(){
public void run(){a.withdraw(10000);}
}.start();
new Thread(){
public void run(){
try{Thread.sleep(500);}catch(Exception e){}
a.deposit(3000);
}
}.start();
}
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com