Question Bank › Technical › Java › Coding Questions
Write a Java program that demonstrates the String indexOf(String substring) method. Create a String variable holding the text "Please find the festival date" and use indexOf to find the starting index of the substring "festival", then print the result. FileName: FindSubstringIndex.java
public class FindSubstringIndex {
public static void main(String[] args) {
String text = "Please find the festival date";
int index = text.indexOf("festival");
System.out.println("index of substring " + index);
}
}Write a Java program named IndexOfExample3.java that demonstrates the String indexOf(String str, int fromIndex) method. Create a String variable holding the text "Delhi is the capital of India" and find the index of the substring "capital" starting the search from index 5, then again starting from index 20. Print each result on its own line as: index of substring <value>
public class IndexOfExample3 {
public static void main(String[] args) {
String s1 = "Delhi is the capital of India";
int index = s1.indexOf("capital", 5);
System.out.println("index of substring " + index);
index = s1.indexOf("capital", 20);
System.out.println("index of substring " + index);
}
}Write a Java program named IndexOfExample4.java that demonstrates the String indexOf(int ch, int fromIndex) method. Create a String variable holding the text "Mumbai is a coastal city" and find the index of the first occurrence of the character 'a' at or after index 10. Print the result as: index of char <value>
public class IndexOfExample4 {
public static void main(String[] args) {
String s1 = "Mumbai is a coastal city";
int index = s1.indexOf('a', 10);
System.out.println("index of char " + index);
}
}Write a Java program that creates a StringBuilder containing the text "Ram " and then uses the append() method to add the string "Kumar" to it. Finally, print the resulting StringBuilder to the console.
public class AppendDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Ram ");
sb.append("Kumar");
System.out.println(sb);
}
}Write a Java program that creates a StringBuilder containing the text "Namaste " and then uses the insert() method to insert the string "Bharat" at position 2. Finally, print the resulting StringBuilder to the console.
public class InsertDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Namaste ");
sb.insert(2, "Bharat");
System.out.println(sb);
}
}Write a Java program that creates a StringBuilder with the text "Bharat", uses the replace(beginIndex, endIndex, str) method to replace the characters from index 1 up to (but not including) index 4 with "har", and then prints the resulting string.
public class StringBuilderReplaceDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Bharat");
sb.replace(1, 4, "har");
System.out.println(sb);
}
}Write a Java program that creates a StringBuilder with the text "Namaste", uses the delete(beginIndex, endIndex) method to remove characters from index 2 up to (but not including) index 5, and then prints the resulting string.
public class StringBuilderDeleteDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Namaste");
sb.delete(2, 5);
System.out.println(sb);
}
}Write a Java program that uses the reverse() method of the StringBuilder class. Create a StringBuilder with the text "Bharat" and reverse it, then print the reversed string.
public class BuilderReverseDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Bharat");
sb.reverse();
System.out.println(sb); // prints tarahB
}
}Write a Java program that demonstrates the capacity() method of the StringBuilder class. Create an empty StringBuilder, print its default capacity (16). Append the string "Namaste" and print the capacity again. Then append the string "India is a wonderful country" and print the capacity once more, showing that when the content exceeds the current capacity, the new capacity becomes (oldCapacity*2)+2.
public class BuilderCapacityDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); // default 16
sb.append("Namaste");
System.out.println(sb.capacity()); // still 16
sb.append("India is a wonderful country");
System.out.println(sb.capacity()); // (16*2)+2 = 34
}
}Write a Java program that demonstrates the instanceof operator. Create a class named Student, make an object of it, and use instanceof to check whether the object is an instance of Student, printing the boolean result.
class Student {
public static void main(String args[]) {
Student s = new Student();
System.out.println(s instanceof Student);
}
}Write a Java program that demonstrates the instanceof operator with inheritance. Create a parent class named Fruit and a child class named Mango that extends Fruit. In main, create a Mango object referenced by a Mango variable and print the result of checking whether it is an instance of Fruit. The program should print true.
class Fruit {}
class Mango extends Fruit { // Mango inherits Fruit
public static void main(String args[]) {
Mango m = new Mango();
System.out.println(m instanceof Fruit); // true
}
}
Write a Java program that demonstrates the instanceof operator applied to a variable holding null. Declare a class named Vehicle, create a Vehicle reference set to null, and print the result of checking whether that null reference is an instance of Vehicle. The program should print false.
class Vehicle {
public static void main(String args[]) {
Vehicle v = null;
System.out.println(v instanceof Vehicle); // false
}
}Write a Java program that demonstrates the problem of variable shadowing when the 'this' keyword is NOT used. Create a class named 'Employee' with instance variables: int empId, String empName, double salary. The constructor should take parameters with the SAME names (empId, empName, salary) but WITHOUT using 'this' keyword, so the assignments fail to set the instance variables. Add a display() method that prints empId, empName and salary. In main, create two Employee objects: one with (201, "Ravi", 45000.0) and another with (202, "Meera", 52000.0), then call display() on both.
class Employee {
int empId;
String empName;
double salary;
Employee(int empId, String empName, double salary) {
empId = empId;
empName = empName;
salary = salary;
}
void display() {
System.out.println(empId + " " + empName + " " + salary);
}
}
class TestEmployee {
public static void main(String args[]) {
Employee e1 = new Employee(201, "Ravi", 45000.0);
Employee e2 = new Employee(202, "Meera", 52000.0);
e1.display();
e2.display();
}
}Write a Java program that shows how the this keyword can be used to invoke a method of the current class. Create a class named Greeter with two methods: greet() which prints "Good morning", and welcome() which calls greet() using this.greet() and then prints "Have a nice day". In the main method, create a Greeter object and call welcome().
class Greeter {
void greet() {
System.out.println("Good morning");
}
void welcome() {
System.out.println("Have a nice day");
this.greet();
}
}
class TestGreeter {
public static void main(String args[]) {
Greeter g = new Greeter();
g.welcome();
}
}Write a Java program that demonstrates constructor chaining using the this() keyword. Create a class named Shop. Its no-argument constructor should print "Welcome to the shop". Its parameterized constructor (taking an int itemCount) should first call the no-argument constructor using this(), then print the item count. In the main method, create an object of Shop using the parameterized constructor with the value 25.
class Shop {
Shop() {
System.out.println("Welcome to the shop");
}
Shop(int itemCount) {
this();
System.out.println(itemCount);
}
}
class TestShop {
public static void main(String args[]) {
Shop s = new Shop(25);
}
}Write a Java program that demonstrates passing the 'this' keyword as an argument in a method. Create a class named 'Payment' with a method 'process(Payment p)' that prints "payment processed". Add another method 'start()' that calls process(this). In main, create a Payment object and call start().
class Payment {
void process(Payment p) {
System.out.println("payment processed");
}
void start() {
process(this);
}
public static void main(String[] args) {
Payment pay = new Payment();
pay.start();
}
}Write a Java program that demonstrates the unary ++ and -- operators: start with int count = 6, then print count++ , ++count , count-- , --count each on its own line.
public class UnaryDemo {
public static void main(String[] args) {
int count = 6;
System.out.println(count++);
System.out.println(++count);
System.out.println(count--);
System.out.println(--count);
}
}Write a Java program that demonstrates the unary bitwise complement operator (~) and the unary logical NOT operator (!). Use an int variable x = 7, an int variable y = -7, a boolean flag1 = true and a boolean flag2 = false, and print the results of ~x, ~y, !flag1 and !flag2.
public class UnaryDemo {
public static void main(String[] args) {
int x = 7;
int y = -7;
boolean flag1 = true;
boolean flag2 = false;
System.out.println(~x);
System.out.println(~y);
System.out.println(!flag1);
System.out.println(!flag2);
}
}Write a Java program that uses the ternary operator to find the smaller of two integers: priceA = 7 and priceB = 3. Print the smaller value.
public class PriceCompare {
public static void main(String[] args) {
int priceA = 7;
int priceB = 3;
int min = (priceA < priceB) ? priceA : priceB;
System.out.println(min);
}
}Write a Java program that uses the ternary operator to check whether a given integer is even or odd. Use the number 24 and print "even number" if it is even, otherwise print "odd number".
public class TernaryEvenOdd {
public static void main(String[] args) {
int number = 24;
String output = (number % 2 == 0) ? "even number" : "odd number";
System.out.println(output);
}
}Write a Java program that demonstrates the use of compound assignment operators. Declare two integer variables: x = 12 and y = 25. Then apply the following operations: add 8 to x, and subtract 5 from y. Print the final values of x and y.
public class AssignmentExample {
public static void main(String[] args) {
int x = 12;
int y = 25;
x += 8;
y -= 5;
System.out.println(x);
System.out.println(y);
}
}Write a Java program that demonstrates compound assignment operators. Start with an integer variable 'num' initialized to 15. Then perform the following operations in order: add 5 to num, subtract 3 from num, multiply num by 2, and finally divide num by 4. After each operation, print the current value of num.
public class AssignmentDemo {
public static void main(String[] args) {
int num = 15;
num += 5;
System.out.println(num);
num -= 3;
System.out.println(num);
num *= 2;
System.out.println(num);
num /= 4;
System.out.println(num);
}
}Write a Java program that declares two int variables p = 18 and q = 4, then prints the results of p + q, p - q, p * q, p / q, and p % q, each on its own line.
public class ArithmeticDemo {
public static void main(String[] args) {
int p = 18;
int q = 4;
System.out.println(p + q);
System.out.println(p - q);
System.out.println(p * q);
System.out.println(p / q);
System.out.println(p % q);
}
}Write a Java program that demonstrates the left shift operator (<<). Declare an int variable x = 7 and print the results of x << 1, x << 2, x << 3, and x << 4, each on its own line.
public class ShiftDemo {
public static void main(String[] args) {
int x = 7;
System.out.println(x << 1);
System.out.println(x << 2);
System.out.println(x << 3);
System.out.println(x << 4);
}
}Write a Java program that demonstrates the difference between the logical && operator and the bitwise & operator. Use variables x = 12, y = 7, z = 25. Print the result of (x < y && x < z) and then the result of (x < y & x < z). The program should show that && short-circuits when the first condition is false, while & always evaluates both conditions.
public class AndOperatorDemo {
public static void main(String[] args) {
int x = 12;
int y = 7;
int z = 25;
System.out.println(x < y && x < z); // false && true = false
System.out.println(x < y & x < z); // false & true = false
}
}Write a Java program that demonstrates a simple shutdown hook by creating a class CleanupThread that extends Thread and overrides run() to print "shut down hook task completed for Delhi office..". In main, register an instance of CleanupThread as a shutdown hook using Runtime and then print "Application running... press ctrl+c to exit". FileName: CleanupThread.java
public class CleanupThread extends Thread {
public void run() {
System.out.println("shut down hook task completed for Delhi office..");
}
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
rt.addShutdownHook(new CleanupThread());
System.out.println("Application running... press ctrl+c to exit");
}
}Write a Java program that declares two strings: s1 = "" and s2 = "Bengaluru". For each string, check whether its length is zero OR it isEmpty(); if so print that the string is empty, otherwise print the string itself. Name the class EmptyCheckDemo.
public class EmptyCheckDemo {
public static void main(String[] args) {
String s1 = "";
String s2 = "Bengaluru";
if (s1.length() == 0 || s1.isEmpty())
System.out.println("String s1 is empty");
else
System.out.println(s1);
if (s2.length() == 0 || s2.isEmpty())
System.out.println("String s2 is empty");
else
System.out.println(s2);
}
}Write a Java program that demonstrates the difference between an empty string and a null string. Declare one String variable as an empty string ("") and another String variable as null. For the empty string, use the isEmpty() method to check and print whether it is empty. For the null string, show that calling isEmpty() directly on it throws a NullPointerException, so instead check for null first (using == null) and print an appropriate message. Name the class NullEmptyDemo.public class NullEmptyDemo {
public static void main(String[] args) {
String emptyStr = "";
String nullStr = null;
// Check the empty string using isEmpty()
if (emptyStr.isEmpty()) {
System.out.println("emptyStr is an empty string.");
} else {
System.out.println("emptyStr is not empty.");
}
// isEmpty() cannot be used on a null string; check for null first
if (nullStr == null) {
System.out.println("nullStr is a null string.");
} else if (nullStr.isEmpty()) {
System.out.println("nullStr is an empty string.");
} else {
System.out.println("nullStr is not empty.");
}
}
}Write a Java program that checks whether strings are empty, blank (containing only white spaces), or not blank. First check a string that consists of only spaces (for example " "), then check a string like " Welcome to Delhi. ". Use the length(), trim() and isEmpty() methods. Name the class BlankCheck.
public class BlankCheck {
public static void main(String[] args) {
String str = " ";
int size = str.length();
if (size == 0) {
System.out.println("The string is empty.");
} else if (str.trim().isEmpty()) {
System.out.println("The string is blank.");
} else {
System.out.println("The string is not blank.");
}
str = " Welcome to Delhi. ";
size = str.length();
if (size == 0) {
System.out.println("The string is empty.");
} else if (str.trim().isEmpty()) {
System.out.println("The string is blank.");
} else {
System.out.println("The string is not blank.");
}
}
}Write a Java program that demonstrates the use of the StringBuffer class. Create a StringBuffer initialized with the text "namaste", then append "bharat" to it, and finally print the resulting buffer contents to the console. Name the class BufferDemo.
public class BufferDemo {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("namaste");
buffer.append("bharat");
System.out.println(buffer);
}
}Write a Java program to demonstrate the use of the StringBuilder class. Create a StringBuilder initialized with "namaste", append "duniya" to it, and then print the resulting string.
public class BuilderDemo {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("namaste");
builder.append("duniya");
System.out.println(builder);
}
}Write a Java program named PrintTask.java that performs a single task using multiple threads. The task is to print "Task done by thread" on the console. Achieve this by extending the Thread class, and start three threads that all execute this same task.
public class PrintTask extends Thread {
public void run() {
System.out.println("Task done by thread");
}
public static void main(String[] args) {
PrintTask t1 = new PrintTask();
PrintTask t2 = new PrintTask();
PrintTask t3 = new PrintTask();
t1.start();
t2.start();
t3.start();
}
}Write a Java program named WorkerDemo.java that creates a thread by extending the Thread class. Override run() to print "background job is running..." and in main create an object and call start() to begin the thread.
class WorkerDemo extends Thread {
public void run() {
System.out.println("background job is running...");
}
public static void main(String args[]) {
WorkerDemo t1 = new WorkerDemo();
t1.start();
}
}Write a Java program named GreetTask.java that performs a single task using multiple threads. The task is to print "Namaste from thread" on the console. Create the task by implementing the Runnable interface, and start two threads that both run this same task.
public class GreetTask implements Runnable {
public void run() {
System.out.println("Namaste from thread");
}
public static void main(String[] args) {
Thread t1 = new Thread(new GreetTask());
Thread t2 = new Thread(new GreetTask());
t1.start();
t2.start();
}
}Write a Java program named TaskRunner.java that creates a thread by implementing the Runnable interface. The run() method should print "worker thread is active..." and the main method should start the thread using the Thread(Runnable) constructor.
class TaskRunner implements Runnable {
public void run() {
System.out.println("worker thread is active...");
}
public static void main(String args[]) {
TaskRunner task = new TaskRunner();
Thread t1 = new Thread(task); // Using the constructor Thread(Runnable r)
t1.start();
}
}Write a Java program that performs two different tasks using two threads, where each task is defined in its own class that extends Thread. The first thread's run() should print "Task: counting" and the second thread's run() should print "Task: printing". Name the file TwoTasks.java.
class CountTask extends Thread {
public void run() {
System.out.println("Task: counting");
}
}
class PrintTask extends Thread {
public void run() {
System.out.println("Task: printing");
}
}
public class TwoTasks {
public static void main(String[] args) {
CountTask t1 = new CountTask();
PrintTask t2 = new PrintTask();
t1.start();
t2.start();
}
}Write a Java program that performs two different tasks using two threads created via anonymous inner classes that extend the Thread class. The first thread should print "Namaste from Thread A" and the second thread should print "Namaste from Thread B". Name the file GreetThreads.java.
public class GreetThreads {
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
System.out.println("Namaste from Thread A");
}
};
Thread t2 = new Thread() {
public void run() {
System.out.println("Namaste from Thread B");
}
};
t1.start();
t2.start();
}
}Write a Java program that uses the String.join() method to combine the words "namaste", "from", "bharat" using the delimiter "-" and prints the resulting string. Name the file GreetingJoin.java.
public class GreetingJoin {
public static void main(String args[]) {
String joined = String.join("-", "namaste", "from", "bharat");
System.out.println(joined);
}
}Write a Java program that uses the String.join() method with a delimiter to format a date and a time. Join the day, month and year values "14", "08", "2023" using "/" to form the date, and join the hour, minute and second values "09", "45", "30" using ":" to form the time. Print the date, then a space, then the time on the same line. Name the file DateJoinExample.java.
public class DateJoinExample {
public static void main(String[] args) {
String date = String.join("/", "14", "08", "2023");
System.out.print(date);
String time = String.join(":", "09", "45", "30");
System.out.println(" " + time);
}
}Write a Java program that calls String.join() with a null delimiter and the elements "red", "green", "blue". The program should demonstrate that using null as the delimiter throws a NullPointerException. Name the class JoinNullDelimiter.
public class JoinNullDelimiter
{
public static void main(String[] args)
{
String result = null;
result = String.join(null, "red", "green", "blue");
System.out.println(result);
}
}Write a Java program that uses String.join() with a delimiter "|" and a list of elements where the first element is null, followed by " chai ", " samosa ", " study Java ", " samosa ", " sleep ". The null element should be treated as a normal string (no exception). Print the joined result. Name the class JoinDemo.
public class JoinDemo
{
public static void main(String[] args)
{
String result = null;
result = String.join("|", null, " chai ", " samosa ", " study Java ", " samosa ", " sleep ");
System.out.println(result);
}
}Write a Java program that creates an immutable class named 'Citizen' having one final data member 'aadhaarNumber', a parameterized constructor to set it, and a getter method. Then in a main method create a Citizen object with Aadhaar number "9876 5432 1098" and print it as "Aadhaar Number: ...".
final class Citizen {
final String aadhaarNumber;
public Citizen(String aadhaarNumber) {
this.aadhaarNumber = aadhaarNumber;
}
public String getAadhaarNumber() {
return aadhaarNumber;
}
}
public class ImmutableDemo {
public static void main(String ar[]) {
Citizen c = new Citizen("9876 5432 1098");
String s1 = c.getAadhaarNumber();
System.out.println("Aadhaar Number: " + s1);
}
}Write a Java program that demonstrates garbage collection: create a class named 'Courier' whose finalize() method prints "courier object is garbage collected". In main, create two Courier objects, set both references to null, and then request garbage collection using System.gc().
public class Courier {
public void finalize() {
System.out.println("courier object is garbage collected");
}
public static void main(String args[]) {
Courier c1 = new Courier();
Courier c2 = new Courier();
c1 = null;
c2 = null;
System.gc();
}
}Write a Java program that stores the string "delhi is capital of india" in a variable and prints the last index of the character 'i' in that string. File name: LastIndexExample.java
public class LastIndexExample {
public static void main(String[] args) {
String s1 = "delhi is capital of india";
int index1 = s1.lastIndexOf('i');
System.out.println(index1);
}
}Write a Java program named LastIndexOfExample3.java that demonstrates the String lastIndexOf(String substring) method. Use the string "Delhi is the last stop of journey" and print the index returned by lastIndexOf("of").public class LastIndexOfExample3 {
public static void main(String[] args) {
String str = "Delhi is the last stop of journey";
int index = str.lastIndexOf("of");
System.out.println(index);
}
}Write a Java program that stores the string "Mumbai is the city of dreams" in a variable and finds the last index of the character 'i' searching backwards starting from index 7 (i.e., using lastIndexOf('i', 7)). Print the resulting index. File name: LastIndexFromExample.javapublic class LastIndexFromExample {
public static void main(String[] args) {
String str = "Mumbai is the city of dreams";
int index = str.lastIndexOf('i', 7);
System.out.println(index);
}
}Write a Java program named LastIndexOfExample4.java that demonstrates the String lastIndexOf(String substring, int fromIndex) method. Use the string "Mumbai is the last stop of journey" and print the result of lastIndexOf("of", 30) and then lastIndexOf("of", 12).public class LastIndexOfExample4 {
public static void main(String[] args) {
String str = "Mumbai is the last stop of journey";
int index = str.lastIndexOf("of", 30);
System.out.println(index);
index = str.lastIndexOf("of", 12);
System.out.println(index); // -1, if not found
}
}Write a Java program that reverses a given string without using any built-in reverse method. Use the string "Java Programming". The program should print the original string and then its reverse.
public class StringReverser {
public static void main(String[] args) {
String str = "Java Programming";
int len = str.length();
System.out.println("Original string: '" + str + "'");
System.out.print("Reverse: ");
for (int i = 0; i < len; i++) {
System.out.print(str.charAt(len - i - 1));
}
System.out.println();
}
}Write a Java program that counts the number of whitespace characters in a given string. Use the string " Hello World " (with two leading and two trailing spaces). The program should print the original string, then compute and print the total number of whitespace characters. Use the length() method and remove spaces to find the count.
public class WhitespaceCounter {
public static void main(String[] args) {
String str = " Hello World ";
int sizeWithSpaces = str.length();
System.out.println("Original string: '" + str + "'");
String noSpaces = str.replace(" ", "");
int sizeWithoutSpaces = noSpaces.length();
int whitespaceCount = sizeWithSpaces - sizeWithoutSpaces;
System.out.println("Total whitespace characters: " + whitespaceCount);
}
}Write a Java program that shows what happens when the toString() method is NOT overridden. Create a class Customer with fields custId (int), custName (String) and custCity (String) and a constructor that initialises them. In main, create Customer(301, "Ravi", "Nagpur") and Customer(302, "Sneha", "Indore") and print each object directly using System.out.println(). Explain why the output is not the field values.
class Customer {
int custId;
String custName;
String custCity;
Customer(int custId, String custName, String custCity) {
this.custId = custId;
this.custName = custName;
this.custCity = custCity;
}
public static void main(String args[]) {
Customer c1 = new Customer(301, "Ravi", "Nagpur");
Customer c2 = new Customer(302, "Sneha", "Indore");
System.out.println(c1); // compiler calls c1.toString()
System.out.println(c2); // compiler calls c2.toString()
}
}Write a Java program that demonstrates overriding the toString() method. Create a class Employee with fields empId (int), empName (String) and empCity (String). The constructor should initialise these fields, and the toString() method should return the three values separated by spaces. In main, create two Employee objects — Employee(201, "Anil", "Pune") and Employee(202, "Meera", "Jaipur") — and print each object directly using System.out.println().
class Employee {
int empId;
String empName;
String empCity;
Employee(int empId, String empName, String empCity) {
this.empId = empId;
this.empName = empName;
this.empCity = empCity;
}
public String toString() { // overriding the toString() method
return empId + " " + empName + " " + empCity;
}
public static void main(String args[]) {
Employee e1 = new Employee(201, "Anil", "Pune");
Employee e2 = new Employee(202, "Meera", "Jaipur");
System.out.println(e1); // compiler calls e1.toString()
System.out.println(e2); // compiler calls e2.toString()
}
}Write a Java program named ReplaceExample1.java that creates the string "delhi is a very big city", replaces every occurrence of the character 'i' with 'e' using the String replace(char, char) method, and prints the resulting string.
public class ReplaceExample1{
public static void main(String args[]){
String s1="delhi is a very big city";
String replaceString=s1.replace('i','e');
System.out.println(replaceString);
}}Write a Java program named ReplaceExample2.java that creates the string "my city is Pune my city is clean", replaces every occurrence of the sequence "is" with "was" using the String replace(CharSequence, CharSequence) method, and prints the resulting string.
public class ReplaceExample2{
public static void main(String args[]){
String s1="my city is Pune my city is clean";
String replaceString=s1.replace("is","was");
System.out.println(replaceString);
}}Write a Java program that starts with the string "aaaaaa-bbbb-aaaaaa". First replace every 'b' with 'c' and print the result. Then, on that new string, replace every 'c' back with 'b' and print the result again.
public class ReplaceChainDemo {
public static void main(String[] args) {
String str = "aaaaaa-bbbb-aaaaaa";
String rs = str.replace("b", "c"); // Replace 'b' with 'c'
System.out.println(rs);
rs = rs.replace("c", "b"); // Replace 'c' with 'b'
System.out.println(rs);
}
}Write a Java program that demonstrates that the String replace() method throws a NullPointerException when the target (the string to be replaced) is null. Use the string "Ravi is learning Java at Pune Institute." and try to replace a null target with "Mumbai". Print the original string first, then perform the replace and print the result.
public class ReplaceNullDemo
{
public static void main(String[] args)
{
String text = "Ravi is learning Java at Pune Institute.";
System.out.println(text);
String target = null;
// Replacing a null target raises NullPointerException
text = text.replace(target, "Mumbai");
System.out.println(text);
}
}Write a Java program that uses the StringTokenizer class to tokenize the string "java is very easy" on the basis of whitespace and print each token on a new line. Name the class TokenDemo.
import java.util.StringTokenizer;
public class TokenDemo{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("java is very easy"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}Write a Java program that demonstrates the nextToken(String delim) method of the StringTokenizer class. Create a class named Demo and tokenize the string "red;green;blue;yellow" using the delimiter ";", then print the first token with the message "First token is : ".
import java.util.*;
public class Demo {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("red;green;blue;yellow");
// printing next token using the given delimiter
System.out.println("First token is : " + st.nextToken(";"));
}
}Write a Java program that demonstrates the hasMoreTokens() method of the StringTokenizer class. Tokenize the string "Learning Java is fun" using a space delimiter and print each token on a new line using a while loop with hasMoreTokens() and nextToken(). Name the class TokenCheckDemo.
import java.util.StringTokenizer;
public class TokenCheckDemo
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Learning Java is fun", " ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}Write a Java program that demonstrates the hasMoreElements() method of the StringTokenizer class. Use the string "Ravi is learning Java programming" with a space delimiter, and print each token on its own line by looping with hasMoreElements() and calling nextToken(). Name the class TokenEnumDemo.
import java.util.StringTokenizer;
public class TokenEnumDemo
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Ravi is learning Java programming", " ");
while (st.hasMoreElements())
{
System.out.println(st.nextToken());
}
}
}Write a Java program that uses the nextElement() method of the StringTokenizer class to print each token of the string "Mumbai Pune Nagpur Nashik" (tokens separated by spaces) one per line. Name the class TokenPrinter.
import java.util.StringTokenizer;
public class TokenPrinter {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Mumbai Pune Nagpur Nashik", " ");
while (st.hasMoreTokens()) {
System.out.println(st.nextElement());
}
}
}Write a Java program that uses the countTokens() method of the StringTokenizer class to count how many tokens are present in the string "Ravi is going to Delhi tomorrow" (tokens separated by spaces), and prints the total number of tokens. Name the class TokenCounter.
import java.util.StringTokenizer;
public class TokenCounter {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Ravi is going to Delhi tomorrow", " ");
System.out.println("Total number of Tokens: " + st.countTokens());
}
}Write a Java program that takes the sentence "java is a very good language" and uses the String replaceAll() method to replace every occurrence of the character 'a' with 'e', then prints the result. Name the file ReplaceCharDemo.java.
public class ReplaceCharDemo {
public static void main(String[] args) {
String s1 = "java is a very good language";
String replaced = s1.replaceAll("a", "e");
System.out.println(replaced);
}
}Write a Java program that takes the sentence "Ravi is a cricketer. Ravi is a singer. Ravi is a dancer." and uses the String replaceAll() method to replace every occurrence of the word "is" with "was", then prints the resulting sentence. Name the file ReplaceWordDemo.java.
public class ReplaceWordDemo {
public static void main(String[] args) {
String s1 = "Ravi is a cricketer. Ravi is a singer. Ravi is a dancer.";
String replaced = s1.replaceAll("is", "was");
System.out.println(replaced);
}
}Write a Java program that removes all white spaces from the string "Amit Sharma is from Pune. Amit Sharma is a teacher. Amit Sharma is happy." using the String replaceAll() method with the regular expression \s, and prints the resulting string.
public class ReplaceAllDemo
{
public static void main(String[] args)
{
String s1 = "Amit Sharma is from Pune. Amit Sharma is a teacher. Amit Sharma is happy.";
String replaceString = s1.replaceAll("\\s", "");
System.out.println(replaceString);
}
}Write a Java program that demonstrates that the replaceAll() method of the String class does not accept a null regular expression. Create a string "BharatBazaar", print it, then call replaceAll() with a null regex and a replacement of " ", and print the result. The program should show that a NullPointerException is raised. Name the file ReplaceAllNullDemo.java and the class ReplaceAllNullDemo.
public class ReplaceAllNullDemo
{
// main method
public static void main(String[] args)
{
// input string
String shop = "BharatBazaar";
System.out.println(shop);
String regex = null; // regular expression is null
// this line throws NullPointerException
shop = shop.replaceAll(regex, " ");
System.out.println(shop);
}
}Write a Java program that declares a Writer variable referring to a FileWriter for a file named diary.txt, writes the string "India is my homeland" to it, closes the writer, and prints "Finished" to the console. Use a try-catch block to handle IOException.
import java.io.*;
public class DiaryWriter {
public static void main(String[] args) {
try {
Writer w = new FileWriter("diary.txt");
String content = "India is my homeland";
w.write(content);
w.close();
System.out.println("Finished");
} catch (IOException e) {
e.printStackTrace();
}
}
}Write a Java program that uses the FileWriter class to write the text "Namaste from Mumbai" into a file named notes.txt, then closes the writer and prints "Saved" to the console. Handle any exception using try-catch.
import java.io.FileWriter;
public class NotesWriter {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("notes.txt");
fw.write("Namaste from Mumbai");
fw.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Saved");
}
}Write a Java program that shows the String.startsWith() method is case-sensitive. Create a String variable holding the value "mumbai local train timetable by indianrail". Print the result of startsWith("mu"), startsWith("mumbai local"), and startsWith("Mumbai local"). Name the class StartsWithCaseDemo.public class StartsWithCaseDemo {
public static void main(String[] args) {
String s1 = "mumbai local train timetable by indianrail";
System.out.println(s1.startsWith("mu")); // true
System.out.println(s1.startsWith("mumbai local")); // true
System.out.println(s1.startsWith("Mumbai local")); // false, 'm' and 'M' differ
}
}Write a Java program that demonstrates the overloaded String.startsWith(String prefix, int offset) method. Create a String variable holding the value "Bengaluru". Print the result of checking whether it starts with "B" (no offset), whether it starts with "e" (no offset), and whether it starts with "e" starting from offset 1. Name the class StartsWithOffsetDemo.
public class StartsWithOffsetDemo {
public static void main(String[] args) {
String city = "Bengaluru";
// no offset given, so offset is 0
System.out.println(city.startsWith("B")); // true
// no offset given, so offset is 0
System.out.println(city.startsWith("e")); // false
// offset is 1
System.out.println(city.startsWith("e", 1)); // true
}
}Write a Java program that demonstrates an abstract class for banks. Create an abstract class Bank with an abstract method getRateOfInterest() returning int. Create two subclasses, HDFC (returns 6) and ICICI (returns 9), each overriding the method. In the main method of class TestBank, create one object of each subclass and print their rates of interest.
abstract class Bank {
abstract int getRateOfInterest();
}
class HDFC extends Bank {
int getRateOfInterest() { return 6; }
}
class ICICI extends Bank {
int getRateOfInterest() { return 9; }
}
public class TestBank {
public static void main(String[] args) {
Bank b1 = new HDFC();
Bank b2 = new ICICI();
System.out.println("HDFC rate of interest: " + b1.getRateOfInterest());
System.out.println("ICICI rate of interest: " + b2.getRateOfInterest());
}
}Write a Java program to demonstrate inheritance. Create a superclass Teacher with a field salary = 35000 (float). Create a subclass Lecturer that extends Teacher and adds a field allowance = 8000 (int). In the main method of Lecturer, create a Lecturer object and print "Lecturer salary is:" followed by the salary, then print "Allowance of Lecturer is:" followed by the allowance.
class Teacher {
float salary = 35000;
}
class Lecturer extends Teacher {
int allowance = 8000;
public static void main(String args[]) {
Lecturer l = new Lecturer();
System.out.println("Lecturer salary is:" + l.salary);
System.out.println("Allowance of Lecturer is:" + l.allowance);
}
}Write a Java program that demonstrates single inheritance. Create a class Vehicle with a method move() that prints "moving...". Create a class Car that extends Vehicle and adds a method honk() that prints "honking...". In a main method (in a class TestInheritance), create a Car object, call honk() and then call move().
class Vehicle {
void move() {
System.out.println("moving...");
}
}
class Car extends Vehicle {
void honk() {
System.out.println("honking...");
}
}
class TestInheritance {
public static void main(String args[]) {
Car c = new Car();
c.honk();
c.move();
}
}Write a Java program that demonstrates multilevel inheritance. Create a class LivingThing with a method breathe() that prints "breathing...". Create a class Bird extending LivingThing with a method fly() that prints "flying...". Create a class Parrot extending Bird with a method speak() that prints "speaking...". In the main method, create a Parrot object and call speak(), fly() and breathe() in that order. Name the main class TestChain.
class LivingThing {
void breathe() { System.out.println("breathing..."); }
}
class Bird extends LivingThing {
void fly() { System.out.println("flying..."); }
}
class Parrot extends Bird {
void speak() { System.out.println("speaking..."); }
}
class TestChain {
public static void main(String args[]) {
Parrot p = new Parrot();
p.speak();
p.fly();
p.breathe();
}
}Write a Java program that demonstrates hierarchical inheritance. Create a parent class Vehicle with a method move() that prints "moving...". Create two child classes Car (with method honk() printing "honking...") and Bike (with method ring() printing "ringing..."), both extending Vehicle. In the main method, create a Bike object, call ring() and move() on it. (Calling honk() on the Bike object should not compile, so do not call it.) Name the main class TestHierarchy.
class Vehicle {
void move() { System.out.println("moving..."); }
}
class Car extends Vehicle {
void honk() { System.out.println("honking..."); }
}
class Bike extends Vehicle {
void ring() { System.out.println("ringing..."); }
}
class TestHierarchy {
public static void main(String args[]) {
Bike b = new Bike();
b.ring();
b.move();
// b.honk(); // Compile-time error: Bike has no honk()
}
}Write a Java program that prints 'Namaste India' to the console. The program should have a class named Greet with a main method.
public class Greet {
public static void main(String[] args) {
System.out.println("Namaste India");
}
}Write a Java program that declares two integer variables a = 14 and b = 9. Using a simple if statement, check whether the sum of a and b is greater than 20, and if so print the message "a + b is greater than 20".
public class SumCheck {
public static void main(String[] args) {
int a = 14;
int b = 9;
if (a + b > 20) {
System.out.println("a + b is greater than 20");
}
}
}Write a Java program that uses a for loop to print the numbers from 0 to 15, but stops (breaks out of the loop) as soon as the number 9 is printed. Use the break statement inside the loop.
public class BreakDemo {
public static void main(String[] args) {
for (int i = 0; i <= 15; i++) {
System.out.println(i);
if (i == 9) {
break;
}
}
}
}Write a Java program that uses a while loop to print the numbers 1, 2, 3, 4 and then exits the loop using the break statement when the counter reaches 5.
public class BreakWhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 5) {
i++;
break;
}
System.out.println(i);
i++;
}
}
}Write a Java program that demonstrates the if-else statement. Declare two int variables: marks = 35 and bonus = 8. If the sum of marks and bonus is less than 40, print "Total is below 40"; otherwise print "Total is 40 or above". Use an if-else block.
public class Result {
public static void main(String[] args) {
int marks = 35;
int bonus = 8;
if (marks + bonus < 40) {
System.out.println("Total is below 40");
} else {
System.out.println("Total is 40 or above");
}
}
}Write a Java program that demonstrates an if-else-if ladder. Declare a String variable named 'place' with the value "Jaipur". Compare it with "Indore", then with "Bhopal", then with "Surat" using else-if; if none match, print the value of 'place' itself.
public class Student {
public static void main(String[] args) {
String place = "Jaipur";
if(place == "Indore") {
System.out.println("place is indore");
}else if (place == "Bhopal") {
System.out.println("place is bhopal");
}else if(place == "Surat") {
System.out.println("place is surat");
}else {
System.out.println(place);
}
}
}Write a Java program that uses an if-else-if ladder to check the value of a String variable named 'state' set to "Kerala". If state equals "Punjab", print "state is Punjab"; else if state equals "Gujarat", print "state is Gujarat"; else if state equals "Kerala", print "state is Kerala"; otherwise print the value of state.
public class Citizen {
public static void main(String[] args) {
String state = "Kerala";
if (state.equals("Punjab")) {
System.out.println("state is Punjab");
} else if (state.equals("Gujarat")) {
System.out.println("state is Gujarat");
} else if (state.equals("Kerala")) {
System.out.println("state is Kerala");
} else {
System.out.println(state);
}
}
}Write a Java program that demonstrates a nested if-statement. Declare a String variable named 'location' with the value "Pune, India". First check whether the location ends with "India". If it does, then inside that block check: if the location contains "Nagpur" print "Your city is Nagpur"; else if it contains "Nashik" print "Your city is Nashik"; otherwise print only the part of the location before the comma (i.e., the city name). If the location does not end with "India", print "You are not living in India".
public class Student {
public static void main(String[] args) {
String location = "Pune, India";
if(location.endsWith("India")) {
if(location.contains("Nagpur")) {
System.out.println("Your city is Nagpur");
}else if(location.contains("Nashik")) {
System.out.println("Your city is Nashik");
}else {
System.out.println(location.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}Write a Java program that stores the integer 3 in a variable and uses a switch statement with cases 0, 1, and a default case. For case 0 print "number is 0", for case 1 print "number is 1", and for the default case print the value of the variable. Each case must end with break (except default).
public class NumberSwitch {
public static void main(String[] args) {
int num = 3;
switch (num) {
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}Write a Java program that uses a for loop to compute the sum of the first 15 natural numbers (1 to 15) and prints the result.
public class SumNatural {
public static void main(String[] args) {
int total = 0;
for (int k = 1; k <= 15; k++) {
total = total + k;
}
System.out.println("The sum of first 15 natural numbers is " + total);
}
}Write a Java program that uses an enhanced for loop (for-each loop) to iterate over an array of Indian city names: {"Delhi", "Mumbai", "Kolkata", "Chennai", "Bengaluru"} and prints each city on a new line. Use a class named CityList.public class CityList {
public static void main(String[] args) {
String[] cities = {"Delhi", "Mumbai", "Kolkata", "Chennai", "Bengaluru"};
System.out.println("List of cities:");
for (String city : cities) {
System.out.println(city);
}
}
}Write a Java program that uses a while loop to print the first 10 positive even numbers (starting from 2) and then prints "Done" after the loop. Use a class named EvenNumbers.
public class EvenNumbers {
public static void main(String[] args) {
int num = 2;
int count = 0;
System.out.println("First 10 even numbers:");
while (count < 10) {
System.out.println(num);
num = num + 2;
count++;
}
System.out.println("Done");
}
}Write a Java program using a while loop that prints the integers from 1 to 8, each on its own line. Initialize the loop variable before the loop and increment it inside the loop body so the loop does not run infinitely. Name the class WhileDemo.
public class WhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 8) {
System.out.println(i);
i++;
}
}
}Write a Java program using a do-while loop that prints the first 8 multiples of 3 starting from 3 (i.e., 3, 6, 9, ..., 24). Use a variable starting at 3 and increase it by 3 each iteration, continuing while the value is less than or equal to 24.
public class Multiples {
public static void main(String[] args) {
int i = 3;
System.out.println("First 8 multiples of 3:");
do {
System.out.println(i);
i = i + 3;
} while (i <= 24);
}
}Write a Java program that uses a do-while loop to print the integers from 1 to 7, one per line. Initialize the counter before the loop and increment it inside the loop body so the loop terminates correctly.
public class DoWhileDemo {
public static void main(String[] args) {
int n = 1;
do {
System.out.println(n);
n++;
} while (n <= 7);
}
}Write a Java program that demonstrates creating and using a user-defined package. Create a package named 'shop' and inside it define a public class 'Greeter' whose main method prints the message "Namaste from shop package". Save the file as Greeter.java inside the shop package.
package shop;
public class Greeter {
public static void main(String[] args) {
System.out.println("Namaste from shop package");
}
}Write a Java program that demonstrates importing all classes of a package using the form import packagename.*. Create a package named utilities containing two classes: Printer with a public method show() that prints "Printed from utilities" and Counter with a public method count() that prints "Counting in utilities". Then create a class WildcardImportDemo (in the default package) that uses import utilities.*; and calls both show() and count() from its main method. Save the package classes in Printer.java and Counter.java, and the demo in WildcardImportDemo.java.
// File: Printer.java
package utilities;
public class Printer {
public void show() {
System.out.println("Printed from utilities");
}
}
// File: Counter.java
package utilities;
public class Counter {
public void count() {
System.out.println("Counting in utilities");
}
}
// File: WildcardImportDemo.java
import utilities.*;
public class WildcardImportDemo {
public static void main(String[] args) {
Printer p = new Printer();
p.show();
Counter c = new Counter();
c.count();
}
}Write a Java program that demonstrates importing a single class from a package using the form import package.classname. Create a package named mypack containing a class Greeter with a public method greet() that prints "Namaste from mypack". Then, in a separate file (default package), create a class SingleImportDemo that imports only mypack.Greeter (using import mypack.Greeter;) and calls greet() from its main method. Save the package class in Greeter.java and the demo class in SingleImportDemo.java.
// File: Greeter.java
package mypack;
public class Greeter {
public void greet() {
System.out.println("Namaste from mypack");
}
}
// File: SingleImportDemo.java
import mypack.Greeter;
public class SingleImportDemo {
public static void main(String[] args) {
Greeter g = new Greeter();
g.greet();
}
}Write a Java program that demonstrates how to place a class file into a specific directory using packages. Create a class named 'Greeting' in package 'mypack' that prints 'Hello from package'. Save the source file as Greeting.java. After compilation, the class file should be placed in a directory structure corresponding to the package name.
package mypack;
public class Greeting {
public static void main(String[] args) {
System.out.println("Hello from package");
}
}Write a Java program that demonstrates the rule: there can be only one public class in a Java source file, and the file must be saved with the same name as the public class. Otherwise, it causes a compile-time error. Your program should include a public class named 'Main' and another non-public class named 'Helper'. Save the file as Main.java.
class Helper {
void display() {
System.out.println("Helper class");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main class");
Helper h = new Helper();
h.display();
}
}Write Java code to show how two public classes can be placed in the same package. Create two source files, each containing one public class, both declaring the same package name "myshop". The first file Shop.java should define public class Shop with an empty body, and the second file Item.java should define public class Item with an empty body.
//save as Shop.java
package myshop;
public class Shop{}
//save as Item.java
package myshop;
public class Item{}Write a Java program named StringDemo.java that creates three strings: one using a string literal "mango", one by converting a char array {'b','a','n','a','n','a'} into a String, and one using the new keyword with the text "apple". Print all three strings, each on its own line.public class StringDemo{
public static void main(String args[]){
String s1="mango";//string created using a string literal
char ch[]={'b','a','n','a','n','a'};
String s2=new String(ch);//converting char array to string
String s3=new String("apple");//string created using the new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}Write a Java program that demonstrates method overloading by changing the number of arguments. Create a class Sum with two static methods named add: the first add method takes two int arguments and returns their sum, and the second add method takes three int arguments and returns their sum. In the main method, print the result of add(6, 9) and the result of add(6, 9, 12).
class Sum {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
}
public class TestOverloading {
public static void main(String[] args) {
System.out.println(Sum.add(6, 9));
System.out.println(Sum.add(6, 9, 12));
}
}Write a Java program that demonstrates method overloading by changing the data type of arguments. Create a class Calculator with two static methods named add: the first add method takes two int arguments and returns their sum as an int, and the second add method takes two double arguments and returns their sum as a double. In the main method, print the result of add(7, 8) and the result of add(4.5, 5.25).
class Calculator {
static int add(int a, int b) {
return a + b;
}
static double add(double a, double b) {
return a + b;
}
}
public class TestOverloading {
public static void main(String[] args) {
System.out.println(Calculator.add(7, 8));
System.out.println(Calculator.add(4.5, 5.25));
}
}Write a Java program that counts how many times the character 'a' appears in the string "Welcome to Mumbai portal" using the charAt() method, and prints the frequency. Name the class FrequencyCounter.
public class FrequencyCounter {
public static void main(String[] args) {
String str = "Welcome to Mumbai portal";
int count = 0;
for (int i = 0; i <= str.length() - 1; i++) {
if (str.charAt(i) == 'a') {
count++;
}
}
System.out.println("Frequency of a is: " + count);
}
}Write a Java program that reads the contents of a text file named "sample.txt" using the FileReader class and prints the characters to the console. Assume the file exists in the current directory.
import java.io.FileReader;
public class FileReaderExample {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("sample.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();
}
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com