Question Bank › Technical › Java › Coding Questions
Write a Java program that demonstrates the toCharArray() method of the String class. Create a string with the value "world", convert it to a character array, and then print each character on the same line.
public class StringToCharArrayExample {
public static void main(String[] args) {
String s = "world";
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);
}
}
}Write a Java program that takes the string "Learning Java is fun", converts it into a character array using the toCharArray() method, prints the length of the character array, and then prints each character of the array on its own line.
public class StringToCharArrayExample {
public static void main(String[] args) {
String s1 = "Learning Java is fun";
char[] ch = s1.toCharArray();
int len = ch.length;
System.out.println("Char Array length: " + len);
System.out.println("Char Array elements: ");
for (int i = 0; i < len; i++) {
System.out.println(ch[i]);
}
}
}Write a Java program that reads the contents of a text file named "notes.txt" located at D:\notes.txt using the BufferedReader class, and prints each character of the file to the console. Close both the BufferedReader and the FileReader at the end.
import java.io.*;
public class ReadFileExample {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("D:\\notes.txt");
BufferedReader br = new BufferedReader(fr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
br.close();
fr.close();
}
}Write a Java program that reads a person's name from the console using InputStreamReader and BufferedReader, then prints a welcome message in the form "Welcome <name>".
import java.io.*;
public class WelcomeReader {
public static void main(String args[]) throws Exception {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(reader);
System.out.println("Enter your name");
String name = br.readLine();
System.out.println("Welcome " + name);
}
}Write a Java program that repeatedly reads lines of text from the console using InputStreamReader and BufferedReader, printing each line back, and stops when the user enters the word "bye".
import java.io.*;
public class ConsoleLoopExample {
public static void main(String args[]) throws Exception {
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(reader);
String input = "";
while (!input.equals("bye")) {
System.out.println("Enter data: ");
input = br.readLine();
System.out.println("data is: " + input);
}
br.close();
reader.close();
}
}Write a Java program that uses BufferedWriter to write the text "Welcome to India" to a file named "output.txt" in the current directory. After writing, close the writer and print "Done" to the console. Handle any exceptions by declaring throws Exception in the main method.
import java.io.*;
public class BufferedWriterDemo {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("output.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to India");
buffer.close();
System.out.println("Done");
}
}Write a Java program that demonstrates the use of the CharArrayReader class. Create a character array containing the characters of the string "India", then use a CharArrayReader to read and print each character followed by its integer Unicode value, separated by " : ". The program should handle any exceptions.
import java.io.CharArrayReader;
public class CharArrayReaderDemo {
public static void main(String[] args) throws Exception {
char[] letters = { 'I', 'n', 'd', 'i', 'a' };
CharArrayReader reader = new CharArrayReader(letters);
int ch;
while ((ch = reader.read()) != -1) {
System.out.println((char) ch + " : " + ch);
}
reader.close();
}
}Write a Java program that converts a given string to lowercase and prints the result. Use the string "WELCOME TO INDIA".
public class LowerCaseExample {
public static void main(String[] args) {
String s = "WELCOME TO INDIA";
String lower = s.toLowerCase();
System.out.println(lower);
}
}Write a Java program that demonstrates the PrintStream class. Create a FileOutputStream for the file "C:\\output\\report.txt", wrap it in a PrintStream, write the integer 2024 and the strings "Namaste India" and "Welcome to Mumbai" using println, then close both streams and print "Done" to the console.
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamDemo {
public static void main(String[] args) throws Exception {
FileOutputStream fout = new FileOutputStream("C:\\output\\report.txt");
PrintStream pout = new PrintStream(fout);
pout.println(2024);
pout.println("Namaste India");
pout.println("Welcome to Mumbai");
pout.close();
fout.close();
System.out.println("Done");
}
}Write a Java program that uses the printf() method of the PrintStream class (System.out) to print an integer value using the %d format specifier. Create a class named PrintDemo.java, declare int marks = 87 in main(), and print it with System.out.printf("%d", marks).public class PrintDemo {
public static void main(String[] args) {
int marks = 87;
System.out.printf("%d", marks);
}
}Write a Java program that creates the string s1 = " welcome to mumbai ", prints its length and the string itself (without trim), then stores s1.trim() in a variable and prints the trimmed string's length and the trimmed string. Name the class TrimLengthDemo.
public class TrimLengthDemo {
public static void main(String[] args) {
String s1 = " welcome to mumbai ";
System.out.println(s1.length());
System.out.println(s1); // Without trim()
String tr = s1.trim();
System.out.println(tr.length());
System.out.println(tr); // With trim()
}
}Write a Java program that checks whether a string contains only white spaces or also other characters. Use the trim() method: if the trimmed string's length is greater than 0, print "The string contains characters other than white spaces"; otherwise print "The string contains only white spaces". Test it first with the string " delhi " and then with a string made of only spaces " ". Name the class WhitespaceCheck.
public class WhitespaceCheck
{
public static void main(String[] args)
{
String str = " delhi ";
if ((str.trim()).length() > 0)
{
System.out.println("The string contains characters other than white spaces");
}
else
{
System.out.println("The string contains only white spaces");
}
str = " ";
if ((str.trim()).length() > 0)
{
System.out.println("The string contains characters other than white spaces");
}
else
{
System.out.println("The string contains only white spaces");
}
}
}Write a Java program to demonstrate that the trim() method returns a new string when the original string has leading or trailing whitespace, but returns the same string reference when there is no whitespace to trim. Use the strings " hello " and "world". Print the hash codes of the original and trimmed strings for both cases.
public class TrimDemo {
public static void main(String[] args) {
String strWithSpaces = " hello ";
String trimmedStr = strWithSpaces.trim();
System.out.println(strWithSpaces.hashCode());
System.out.println(trimmedStr.hashCode());
String strWithoutSpaces = "world";
String sameStr = strWithoutSpaces.trim();
System.out.println(strWithoutSpaces.hashCode());
System.out.println(sameStr.hashCode());
}
}Write a Java program to demonstrate that strings are immutable. Create a string variable 'name' with the value "Amit". Then call the concat method on it to append " Sharma" and store the result in a new variable 'fullName'. Print both 'name' and 'fullName'. Explain why 'name' remains unchanged.
class StringImmutableDemo {
public static void main(String[] args) {
String name = "Amit";
String fullName = name.concat(" Sharma");
System.out.println("name: " + name);
System.out.println("fullName: " + fullName);
}
}Write a Java program that uses the PrintWriter class to write a message to the console and another message to a file named "output.txt". The console message should be "Hello, this is a test." and the file message should be "Writing to a file using PrintWriter.". The program should flush and close the writer after each use.
import java.io.File;
import java.io.PrintWriter;
public class PrintWriterDemo {
public static void main(String[] args) throws Exception {
// Write to console
PrintWriter consoleWriter = new PrintWriter(System.out);
consoleWriter.write("Hello, this is a test.");
consoleWriter.flush();
consoleWriter.close();
// Write to file
PrintWriter fileWriter = new PrintWriter(new File("output.txt"));
fileWriter.write("Writing to a file using PrintWriter.");
fileWriter.flush();
fileWriter.close();
}
}Write a Java program that stores the integer 45 in a variable, converts it to a String using String.valueOf(int), then concatenates the string "10" to it and prints the result.
public class IntToStringDemo {
public static void main(String[] args) {
int marks = 45;
String s1 = String.valueOf(marks);
System.out.println(s1 + 10);
}
}Write a Java program that converts two boolean values (one true, one false) into their String representations using String.valueOf(boolean), and prints both resulting strings on separate lines.
public class BooleanToStringDemo {
public static void main(String[] args) {
boolean isPassed = true;
boolean isFailed = false;
String s1 = String.valueOf(isPassed);
String s2 = String.valueOf(isFailed);
System.out.println(s1);
System.out.println(s2);
}
}Write a Java program that converts two char values 'R' and 'K' into Strings using String.valueOf(char) and prints both resulting strings.
public class ValueOfCharDemo {
public static void main(String[] args) {
char c1 = 'R';
char c2 = 'K';
String s1 = String.valueOf(c1);
String s2 = String.valueOf(c2);
System.out.println(s1);
System.out.println(s2);
}
}Write a Java program that converts a float value 7.25f and a double value 3.75 into their String forms using String.valueOf(float) and String.valueOf(double), then prints both strings.
public class ValueOfFloatDemo {
public static void main(String[] args) {
float price = 7.25f;
double rate = 3.75;
String s1 = String.valueOf(price);
String s2 = String.valueOf(rate);
System.out.println(s1);
System.out.println(s2);
}
}Write a Java program that demonstrates the use of String.valueOf() to convert various primitive types and an object into strings. Use the following values: boolean true, byte 21, short 22, int 23, long 24L, float 25.5f, double 26.5d, a char array {'I','n','d','i','a'}, and an instance of the class itself. Print each converted string on a new line.public class StringValueOfDemo {
public static void main(String[] args) {
boolean b = true;
byte by = 21;
short sh = 22;
int i = 23;
long l = 24L;
float f = 25.5f;
double d = 26.5d;
char[] chr = {'I','n','d','i','a'};
StringValueOfDemo obj = new StringValueOfDemo();
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(by));
System.out.println(String.valueOf(sh));
System.out.println(String.valueOf(i));
System.out.println(String.valueOf(l));
System.out.println(String.valueOf(f));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(chr));
System.out.println(String.valueOf(obj));
}
}Write a Java program that creates a file named "greeting.txt" and writes the text "Namaste India" to it using an OutputStreamWriter. Ensure the writer is closed properly.
import java.io.*;
public class FileWriterExample {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("greeting.txt");
Writer writer = new OutputStreamWriter(outputStream);
writer.write("Namaste India");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}Write a Java program that uses InputStreamReader to read characters from a file named "notes.txt" and print them to the console one character at a time. Handle any exceptions using a try-catch block.
import java.io.*;
public class ReaderDemo {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("notes.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}Write a Java program to demonstrate that private members (variables and methods) are accessible only within the same class. Create a class 'Employee' with a private int variable 'salary' initialized to 50000 and a private method 'displaySalary' that prints the salary. Then, in another class 'PrivateAccessDemo', try to access these private members from the main method and observe the compile-time errors. Your program should include comments explaining the errors.
class Employee {
private int salary = 50000;
private void displaySalary() {
System.out.println("Salary: " + salary);
}
}
public class PrivateAccessDemo {
public static void main(String[] args) {
Employee emp = new Employee();
// System.out.println(emp.salary); // Compile-time error: salary has private access in Employee
// emp.displaySalary(); // Compile-time error: displaySalary() has private access in Employee
System.out.println("Private members are not accessible from outside the class.");
}
}Write a Java program that demonstrates the default (package-private) access modifier. Create a class Laptop in package electronics with a default method start() that prints "Laptop started". Then create a public class Shop in the same package electronics whose main method creates a Laptop object and calls start(). Explain in the program comments why this works only within the same package.
// File: electronics/Laptop.java
package electronics;
class Laptop {
void start() {
System.out.println("Laptop started");
}
}
// File: electronics/Shop.java
package electronics;
public class Shop {
public static void main(String[] args) {
Laptop l = new Laptop();
l.start();
}
}
Write a Java program to demonstrate the public access modifier. Create a class `Greeting` in package `mypack` with a public method `sayHello()` that prints "Hello from mypack". Then, in the default package, create a class `Main` that imports `mypack.Greeting`, creates an instance, and calls `sayHello()`.
// File: mypack/Greeting.java
package mypack;
public class Greeting {
public void sayHello() {
System.out.println("Hello from mypack");
}
}
// File: Main.java
import mypack.Greeting;
public class Main {
public static void main(String[] args) {
Greeting g = new Greeting();
g.sayHello();
}
}Write a Java program that demonstrates encapsulation: create a class 'Employee' with a single private field 'empName', a public getter getEmpName() and a public setter setEmpName(String empName). In a main method, set the name to "Ramesh" using the setter and print it using the getter.
public class Employee {
// private data member
private String empName;
// getter method for empName
public String getEmpName() {
return empName;
}
// setter method for empName
public void setEmpName(String empName) {
this.empName = empName;
}
public static void main(String[] args) {
Employee e = new Employee();
e.setEmpName("Ramesh");
System.out.println(e.getEmpName());
}
}Write a Java program that defines a read-only class named 'Library' which has only a private data member 'libraryName' initialised to "City Central Library" and only a getter method getLibraryName() to read it. Include a main method that creates a Library object and prints the library name.
public class Library {
// private data member
private String libraryName = "City Central Library";
// only getter method (no setter) -> read-only class
public String getLibraryName() {
return libraryName;
}
public static void main(String[] args) {
Library lib = new Library();
System.out.println(lib.getLibraryName());
}
}Write a Java program that defines a write-only class named 'Employee' with a private field 'department' (String). The class should have only a setter method for department and no getter method. Include a main method to create an Employee object and set its department.
public class Employee {
private String department;
public void setDepartment(String department) {
this.department = department;
}
public static void main(String[] args) {
Employee emp = new Employee();
emp.setDepartment("Finance");
System.out.println("Department set successfully.");
}
}Write a Java program that demonstrates encapsulation using a class named 'Customer' with four private fields: customerId (long), fullName (String), email (String), and balance (float). Provide public getter and setter methods for each field. Also include a main method to test the class by creating an object, setting values, and printing them.
class Customer {
private long customerId;
private String fullName;
private String email;
private float balance;
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
}
public class Main {
public static void main(String[] args) {
Customer cust = new Customer();
cust.setCustomerId(1001L);
cust.setFullName("Ramesh Kumar");
cust.setEmail("ramesh@example.com");
cust.setBalance(5000.0f);
System.out.println("Customer ID: " + cust.getCustomerId());
System.out.println("Name: " + cust.getFullName());
System.out.println("Email: " + cust.getEmail());
System.out.println("Balance: " + cust.getBalance());
}
}Write a Java program that demonstrates multiple inheritance using interfaces. Define an interface Singer with method sing() and an interface Dancer with method dance(). Create a class Performer that implements both Singer and Dancer, where sing() prints "La La La" and dance() prints "Thumka". In main, create a Performer object and call both methods.
interface Singer {
void sing();
}
interface Dancer {
void dance();
}
class Performer implements Singer, Dancer {
public void sing() {
System.out.println("La La La");
}
public void dance() {
System.out.println("Thumka");
}
public static void main(String[] args) {
Performer obj = new Performer();
obj.sing();
obj.dance();
}
}Write a Java program to demonstrate interface inheritance. Create an interface 'Readable' with a method 'read()'. Create another interface 'Writable' that extends 'Readable' and adds a method 'write()'. Then create a class 'Document' that implements 'Writable', providing implementations for both methods: 'read()' prints "Reading document" and 'write()' prints "Writing document". In the main method, create a 'Document' object and call both methods.
interface Readable {
void read();
}
interface Writable extends Readable {
void write();
}
class Document implements Writable {
public void read() {
System.out.println("Reading document");
}
public void write() {
System.out.println("Writing document");
}
}
public class Main {
public static void main(String[] args) {
Document doc = new Document();
doc.read();
doc.write();
}
}Write a Java program that demonstrates a static method in an interface. Define an interface 'Calculator' with a static method 'square' that returns the square of an integer, and an abstract method 'display()'. Create a class 'MyCalculator' that implements Calculator and provides implementation for display(). In the main method, call the static method using the interface name and also create an object of MyCalculator to call display().
interface Calculator {
void display();
static int square(int n) {
return n * n;
}
}
class MyCalculator implements Calculator {
public void display() {
System.out.println("MyCalculator display method");
}
}
public class StaticInterfaceDemo {
public static void main(String[] args) {
int result = Calculator.square(7);
System.out.println("Square of 7 is: " + result);
MyCalculator mc = new MyCalculator();
mc.display();
}
}Write a Java program that declares two int variables a = 15 and b = 9, and uses a simple if statement to print "a + b is greater than 20" only when the sum of a and b is greater than 20.
public class Citizen {
public static void main(String[] args) {
int a = 15;
int b = 9;
if(a+b > 20) {
System.out.println("a + b is greater than 20");
}
}
}Write a Java program that demonstrates the use of a simple if statement. Declare an integer variable marks and set it to 75. If marks is greater than 60, print the message "Marks are above 60".
public class MarksExample {
public static void main(String[] args) {
int marks = 75;
if (marks > 60) {
System.out.print("Marks are above 60");
}
}
}Write a Java program that uses an if-else statement to check whether a given integer is even or odd. Use the number 17 and print "even number" if it is even, otherwise print "odd number".
public class IfElseEvenOdd {
public static void main(String[] args) {
int number = 17;
if (number % 2 == 0) {
System.out.println("even number");
} else {
System.out.println("odd number");
}
}
}Write a Java program that uses an if-else-if ladder to print a grade based on marks. Rules: marks below 40 -> "Fail"; 40 to 59 -> "Grade C"; 60 to 79 -> "Grade B"; 80 to 89 -> "Grade A"; 90 to 100 -> "Grade A+"; anything else -> "Invalid marks". Use marks = 72.
public class GradeLadder {
public static void main(String[] args) {
int marks = 72;
if (marks < 40) {
System.out.println("Fail");
} else if (marks >= 40 && marks < 60) {
System.out.println("Grade C");
} else if (marks >= 60 && marks < 80) {
System.out.println("Grade B");
} else if (marks >= 80 && marks < 90) {
System.out.println("Grade A");
} else if (marks >= 90 && marks <= 100) {
System.out.println("Grade A+");
} else {
System.out.println("Invalid marks");
}
}
}Write a Java program that demonstrates a nested if statement. A person is allowed to donate blood only if their age is at least 18 AND their weight is more than 45. Use an outer if on age and an inner if on weight. Use age = 22 and weight = 60, and print "Eligible to donate blood" when both conditions hold.
public class BloodDonationCheck {
public static void main(String[] args) {
int age = 22;
int weight = 60;
if (age >= 18) {
if (weight > 45) {
System.out.println("Eligible to donate blood");
}
}
}
}Write a Java program that defines a member inner class (a non-static class declared inside another class but outside any method). Create an outer class named 'Library' with a method 'display()' that prints 'Welcome to the Library'. Inside Library, define a member inner class 'Book' with a method 'show()' that prints 'Book: Java Programming'. In the main method, create an instance of Library, then create an instance of the inner class using the outer instance, and call both display() and show().
class Library {
void display() {
System.out.println("Welcome to the Library");
}
class Book {
void show() {
System.out.println("Book: Java Programming");
}
}
public static void main(String[] args) {
Library lib = new Library();
lib.display();
Library.Book b = lib.new Book();
b.show();
}
}Write a Java program named NameCompareDemo.java that demonstrates the String compareTo() method. Create the following strings: a1 = "tiger", a2 = "tiger", a3 = "zebra", a4 = "tiler", a5 = "apple". Print the result of a1.compareTo(a2), a1.compareTo(a3), a1.compareTo(a4) and a1.compareTo(a5), each on its own line.
public class NameCompareDemo {
public static void main(String args[]) {
String a1 = "tiger";
String a2 = "tiger";
String a3 = "zebra";
String a4 = "tiler";
String a5 = "apple";
System.out.println(a1.compareTo(a2)); // 0, both equal
System.out.println(a1.compareTo(a3)); // 't' - 'z' = 116 - 122 = -6
System.out.println(a1.compareTo(a4)); // 'g' - 'l' = 103 - 108 = -5
System.out.println(a1.compareTo(a5)); // 't' - 'a' = 116 - 97 = 19
}
}Write a Java program that demonstrates the use of the compareTo() method of the String class. The compareTo() method compares two strings lexicographically and returns an integer: 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the first string is smaller. In your program, create three strings: s1 = "Rahul", s2 = "Rahul", and s3 = "Amit". Then print the results of s1.compareTo(s2), s1.compareTo(s3), and s3.compareTo(s1).
public class StringCompareToDemo {
public static void main(String[] args) {
String s1 = "Rahul";
String s2 = "Rahul";
String s3 = "Amit";
System.out.println(s1.compareTo(s2)); // 0
System.out.println(s1.compareTo(s3)); // positive
System.out.println(s3.compareTo(s1)); // negative
}
}Write a Java program that shows what happens without exception handling. In the main method, compute int result = 100/0; and then print "rest of the code". Name the class NoHandlerDemo.
public class NoHandlerDemo {
public static void main(String[] args) {
int result = 100/0; // may throw ArithmeticException
System.out.println("rest of the code");
}
}Write a Java program that divides 80 by 0 inside a try block, catches the ArithmeticException and prints the exception object, then after the try-catch prints "rest of the code". Name the class DivideCatchDemo.
public class DivideCatchDemo {
public static void main(String[] args) {
try {
int data = 80 / 0; // may throw exception
}
// handling the exception
catch (ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code");
}
}Write a Java program that keeps a division inside a try block where no exception occurs (use 100/5), prints "rest of the code" after the division, and includes a catch block for ArithmeticException that prints the exception. Name the class SafeTryDemo.
public class SafeTryDemo {
public static void main(String[] args) {
try {
int result = 100 / 5; // no exception here
System.out.println("rest of the code");
}
// handling the exception (will not run here)
catch (ArithmeticException e) {
System.out.println(e);
}
}
}Write a Java program that tries to divide 96 by 0 inside a try block, catches the exception using the parent Exception class and prints the exception object, then prints "rest of the code". Name the class ParentCatchDemo.
public class ParentCatchDemo {
public static void main(String[] args) {
try {
int value = 96 / 0; // may throw exception
}
catch (Exception e) {
System.out.println(e);
}
System.out.println("rest of the code");
}
}Write a Java program that attempts to divide 84 by 0 inside a try block, catches the exception, and prints the custom message "Cannot divide by zero". Name the class CustomMessageDemo.
public class CustomMessageDemo {
public static void main(String[] args) {
try {
int result = 84 / 0; // may throw exception
}
catch (Exception e) {
// display the custom message
System.out.println("Cannot divide by zero");
}
}
}Write a Java program that stores i = 80 and j = 0. In a try block compute data = i / j (which throws an exception). In the catch block, resolve the situation by printing i / (j + 4). Name the class ResolveInCatch.
public class ResolveInCatch {
public static void main(String[] args) {
int i = 80;
int j = 0;
int data;
try {
data = i / j; // may throw ArithmeticException
} catch (Exception e) {
// resolving the exception in the catch block
System.out.println(i / (j + 4));
}
}
}Write a Java program that stores the marks {12, 24, 36, 48} in an int array, tries to print the element at index 9 (which does not exist), catches the resulting ArrayIndexOutOfBoundsException and prints the exception object, then prints "remaining code runs" after the try-catch block.public class MarksArrayDemo {
public static void main(String[] args) {
try {
int marks[] = {12, 24, 36, 48};
System.out.println(marks[9]); // may throw exception
}
// handling the array exception
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println("remaining code runs");
}
}Write a Java program that uses StringReader to read the string "Namaste India!!\nWelcome to Bharat." character by character and print each character to the console until the end of the stream.
import java.io.StringReader;
public class StringReaderDemo {
public static void main(String[] args) throws Exception {
String text = "Namaste India!!\nWelcome to Bharat.";
StringReader reader = new StringReader(text);
int k = 0;
while ((k = reader.read()) != -1) {
System.out.print((char) k);
}
}
}Write a Java program that creates a File object for the directory "C:/Users/priya/Documents", lists all files in it using listFiles(), and for each file prints its name, whether it can be written (canWrite()), whether it is hidden (isHidden()), and its length in bytes.
import java.io.*;
public class DirListing {
public static void main(String[] args) {
File dir = new File("C:/Users/priya/Documents");
File files[] = dir.listFiles();
if (files != null) {
for (File file : files) {
System.out.println(file.getName() + " Can Write: " + file.canWrite()
+ " Is Hidden: " + file.isHidden() + " Length: " + file.length() + " bytes");
}
}
}
}Write a Java program that uses the Scanner class to read a single line of input from the user. Prompt the user with 'Enter your city: ', read the full line using in.nextLine(), and then print 'City is: ' followed by the entered city. FileName: CityScanner.java
import java.util.*;
public class CityScanner {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your city: ");
String city = in.nextLine();
System.out.println("City is: " + city);
in.close();
}
}Write a Java program that declares an int array of size 4, instantiates it, initializes its elements to 15, 25, 35 and 45, and then traverses the array using a for loop with the array's length property, printing each element on a new line.
public class ArrayDemo {
public static void main(String[] args) {
int a[] = new int[4];
a[0] = 15;
a[1] = 25;
a[2] = 35;
a[3] = 45;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}Write a Java program that creates an int array holding the marks {7, 8, 9}, obtains the Class object of that array using getClass(), and prints the name of the array's class (the proxy class name) using getName().public class ArrayClassName {
public static void main(String[] args) {
int marks[] = {7, 8, 9};
Class c = marks.getClass();
String name = c.getName();
System.out.println(name);
}
}Write a Java program that declares a source char array containing the characters of the word 'placement' (i.e. {'p','l','a','c','e','m','e','n','t'}), declares a destination char array of length 5, copies 5 characters starting from index 2 of the source array into the destination array starting at index 0 using System.arraycopy(), and then prints the destination array as a string.public class ArrayCopyDemo {
public static void main(String[] args) {
char[] source = {'p', 'l', 'a', 'c', 'e', 'm', 'e', 'n', 't'};
char[] destination = new char[5];
System.arraycopy(source, 2, destination, 0, 5);
System.out.println(String.valueOf(destination));
}
}Write a Java program that creates an int array named marks with the values {21, 14, 7, 9}, prints the original array elements, then creates a clone of the array using the clone() method, prints the cloned array elements, and finally prints whether the original array and the cloned array are the same object (using ==).public class ArrayCloneDemo {
public static void main(String[] args) {
int marks[] = {21, 14, 7, 9};
System.out.println("Original array:");
for (int m : marks) {
System.out.println(m);
}
int clonedMarks[] = marks.clone();
System.out.println("Cloned array:");
for (int m : clonedMarks) {
System.out.println(m);
}
System.out.println("Are both references equal?");
System.out.println(marks == clonedMarks);
}
}Write a Java program to add two 2×3 matrices and print the resulting matrix. Use matrix A = {{2, 5, 7}, {1, 6, 8}} and matrix B = {{3, 4, 2}, {5, 2, 9}}.public class MatrixAdd {
public static void main(String[] args) {
int a[][] = {{2, 5, 7}, {1, 6, 8}};
int b[][] = {{3, 4, 2}, {5, 2, 9}};
int c[][] = new int[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}Write a Java program that declares, instantiates, and initializes an integer array in a single line with the values 5, 10, 15, 20. Then, use a for loop to print each element of the array on a new line.
public class ArrayInitDemo {
public static void main(String[] args) {
int[] arr = {5, 10, 15, 20};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}Write a Java program that uses a for-each loop to print all elements of an integer array. The array should contain the values 10, 20, 30, 40, 50. Use the for-each loop syntax to iterate and print each element on a new line.
public class ForEachDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}Write a Java program that uses a for-each loop to print all elements of an integer array containing the values 5, 10, 15, 20, 25.
public class ForEachDemo {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
for (int num : numbers) {
System.out.println(num);
}
}
}Write a Java program that passes an int array to a method and prints the smallest element of that array. In main, declare and initialize the array with the values 48, 12, 27, 9, 33 and pass it to the method.
public class MinArrayDemo {
static void findMin(int[] arr) {
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
System.out.println(min);
}
public static void main(String[] args) {
int[] a = {48, 12, 27, 9, 33};
findMin(a);
}
}Write a Java program that demonstrates passing an anonymous array to a method. Create a method that receives an int array and prints each element on its own line, then call it from main by passing an anonymous array containing the values 7, 14, 21, 28, 35.
public class AnonymousArrayDemo {
static void showArray(int[] nums) {
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
}
public static void main(String[] args) {
showArray(new int[]{7, 14, 21, 28, 35});
}
}Write a Java program that defines a method named getNumbers() which returns an integer array containing the values {5, 15, 25, 35, 45}. In the main method, call this method, store the returned array in a variable, and then print each element of the array using a for loop.public class ReturnArrayDemo {
static int[] getNumbers() {
return new int[]{5, 15, 25, 35, 45};
}
public static void main(String[] args) {
int[] arr = getNumbers();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}Write a Java program that declares and initializes a 2D array with the values {{3,5,7},{1,6,9},{8,2,4}}, then prints the array in matrix form (each row on its own line, values separated by a space).public class MatrixPrint {
public static void main(String[] args) {
int[][] mat = {{3,5,7},{1,6,9},{8,2,4}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
}Write a Java program that creates a jagged (ragged) 2D array with 3 rows, where row 0 has 2 columns, row 1 has 5 columns and row 2 has 3 columns. Fill the array with consecutive integers starting from 0 (row by row) and then print it row by row, with a space between values and a new line after each row.
public class JaggedDemo {
public static void main(String[] args) {
int[][] grid = new int[3][];
grid[0] = new int[2];
grid[1] = new int[5];
grid[2] = new int[3];
int value = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = value++;
}
}
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
}Write a Java program that generates a NullPointerException but does NOT provide a catch block specifically for NullPointerException. Inside a try block, declare a String variable set to null and print its length. Provide catch blocks for ArithmeticException (printing "Arithmetic Exception occurs") and ArrayIndexOutOfBoundsException (printing "ArrayIndexOutOfBounds Exception occurs"), followed by a catch block for Exception (printing "Parent Exception occurs"). After the try-catch, print "rest of the code".
public class MultipleCatchParentDemo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}Write a Java program that opens a file named "greeting.txt" (located in the current working directory) using FileInputStream, reads only the first character from the file, prints that character to the console, and then closes the stream. Handle any exception by printing the exception message.
import java.io.FileInputStream;
public class ReadOneChar {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("greeting.txt");
int ch = fin.read();
System.out.print((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}Write a Java program that opens a file named "notes.txt" (located in the current working directory) using FileInputStream and prints every character of the file to the console until the end of the file is reached. Handle any exception by printing the exception message.
import java.io.FileInputStream;
public class ReadAllChars {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("notes.txt");
int ch = 0;
while ((ch = fin.read()) != -1) {
System.out.print((char) ch);
}
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}Write a Java program that demonstrates a local inner class. Create an outer class named Shop with a private instance variable price = 250. In a method bill(), define a local inner class Receipt with a method show() that prints the price, then create an object of Receipt and call show(). The main method should create a Shop object and invoke bill().
public class Shop {
private int price = 250;
void bill() {
class Receipt {
void show() {
System.out.println(price);
}
}
Receipt r = new Receipt();
r.show();
}
public static void main(String[] args) {
Shop s = new Shop();
s.bill();
}
}Write a Java program that demonstrates the difference between the == operator and the equals() method for String objects. The == operator compares references, not the actual string contents. In your program, create three strings: s1 = "Priya", s2 = "Priya", and s3 = new String("Priya"). Then print the results of s1 == s2 and s1 == s3.public class StringEqualityDemo {
public static void main(String[] args) {
String s1 = "Priya";
String s2 = "Priya";
String s3 = new String("Priya");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
}
}Write a Java program to show that String is immutable when using concat(). Start with s1 = "java string". Call s1.concat("is immutable") without assigning the result and print s1. Then assign s1 = s1.concat(" is immutable so assign it explicitly") and print s1 again. Name the class ImmutableDemo.public class ImmutableDemo {
public static void main(String args[]) {
String s1 = "java string";
// concat() returns a new String; s1 itself does not change (immutable)
s1.concat("is immutable");
System.out.println(s1);
s1 = s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}
}Write a Java program that concatenates strings using chained concat() calls. Declare str1 = "Namaste", str2 = "Bharat", str3 = "Mitra". Build str4 by chaining concat() to join str1, a space, str2, a space and str3. Then build str5 = str1.concat("!!!") and str6 = str1.concat("@").concat(str2). Print str4, str5 and str6 each on its own line. Name the class ConcatChain.public class ConcatChain {
public static void main(String[] args) {
String str1 = "Namaste";
String str2 = "Bharat";
String str3 = "Mitra";
String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);
System.out.println(str4);
String str5 = str1.concat("!!!");
System.out.println(str5);
String str6 = str1.concat("@").concat(str2);
System.out.println(str6);
}
}Write a Java program that directly creates a thread using the Thread class constructor Thread(String name) with the name "Report thread", starts it, and then prints the thread's name obtained via getName().
public class ReportThread
{
public static void main(String[] args)
{
Thread t = new Thread("Report thread");
t.start();
String str = t.getName();
System.out.println(str);
}
}Write a Java program that creates a class named TaskRunner implementing Runnable. In its run() method it should print "Task is now executing ...". In main, create a Runnable object, wrap it in a Thread using the constructor Thread(Runnable r, String name) with the name "Payment thread", start the thread, then print the thread's name using getName().
public class TaskRunner implements Runnable
{
public void run()
{
System.out.println("Task is now executing ...");
}
public static void main(String[] args)
{
Runnable r1 = new TaskRunner();
Thread th1 = new Thread(r1, "Payment thread");
th1.start();
String str = th1.getName();
System.out.println(str);
}
}Write a Java program that prints the message "Welcome to Java Programming" to the console. Save the program in a file named Welcome.java.
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java Programming");
}
}Write a Java program that prints the message "Namaste Bharat" to the console. Save the program in a file named Greet.java.
public class Greet {
public static void main(String[] args) {
System.out.println("Namaste Bharat");
}
}Write a Java program that writes text into a file using BufferedOutputStream connected to a FileOutputStream. Create a FileOutputStream for the file "output.txt", wrap it in a BufferedOutputStream, write the string "Hello Mumbai learners." as bytes, then flush, close the buffered stream, close the file stream, and finally print "done".
import java.io.*;
public class BufferedOutputDemo {
public static void main(String[] args) throws Exception {
FileOutputStream fout = new FileOutputStream("output.txt");
BufferedOutputStream bout = new BufferedOutputStream(fout);
String s = "Hello Mumbai learners.";
byte b[] = s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("done");
}
}Write a Java program that stores the string "Welcome Bharat readers" in a String. Use the contains() method to check for "Bharat" and print the boolean result. Then check for "bharat" (lowercase) and print that boolean result too, to show that contains() is case-sensitive. Name the file CaseCheck.java.
public class CaseCheck {
public static void main(String[] args) {
String str = "Welcome Bharat readers";
boolean isContains = str.contains("Bharat");
System.out.println(isContains);
// Case Sensitive
System.out.println(str.contains("bharat")); // false
}
}Write a Java program that stores the sentence "Visit India Gate to see Delhi" in a String. Use the contains() method inside an if-else control structure to check whether the sentence contains "India Gate". If it does, print "This string contains India Gate"; otherwise print "Result not found". Name the file ContainsCheck.java.
public class ContainsCheck {
public static void main(String[] args) {
String str = "Visit India Gate to see Delhi";
if (str.contains("India Gate")) {
System.out.println("This string contains India Gate");
} else {
System.out.println("Result not found");
}
}
}Write a Java program that demonstrates a static nested class with an instance method. Create an outer class named College that has a static int field named strength set to 45. Inside it, define a static nested class named Department with an instance method display() that prints "strength is " followed by the value of the outer class's static field. In the main method, create an object of the nested class using the outer class name (College.Department) and call display().
class College {
static int strength = 45;
static class Department {
void display() {
System.out.println("strength is " + strength);
}
}
public static void main(String args[]) {
College.Department obj = new College.Department();
obj.display();
}
}Write a Java program that uses a simple for loop to print the first 8 multiples of 3, each on a new line (i.e., 3, 6, 9, ..., 24).
public class MultiplesOfThree {
public static void main(String[] args) {
for (int i = 1; i <= 8; i++) {
System.out.println(i * 3);
}
}
}Write a Java program that uses a nested for loop to print all pairs of row and column numbers where the outer loop variable r runs from 1 to 4 and the inner loop variable c runs from 1 to 2. Each pair should be printed on its own line as "r c" (row number, a space, then column number).
public class NestedLoopPairs {
public static void main(String[] args) {
for (int r = 1; r <= 4; r++) {
for (int c = 1; c <= 2; c++) {
System.out.println(r + " " + c);
}
}
}
}Write a Java program that demonstrates an infinite for loop. Use a for loop with no initialization, condition or update (i.e., for(;;)) and inside it print the statement "endless loop". Name the class LoopDemo.
public class LoopDemo {
public static void main(String[] args) {
// Using no condition in for loop
for (;;) {
System.out.println("endless loop");
}
}
}Write a Java program that demonstrates the sleep() method on a custom thread. Create a class named WorkerThread that extends Thread; in its run() method, loop with i from 1 to 4 (i.e., i < 5), and on each iteration make the thread sleep for 300 milliseconds (handling InterruptedException by printing the exception), then print the value of i. In main, create two WorkerThread objects and start both of them.
class WorkerThread extends Thread {
public void run() {
for (int i = 1; i < 5; i++) {
// the thread will sleep for 300 milliseconds
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[]) {
WorkerThread t1 = new WorkerThread();
WorkerThread t2 = new WorkerThread();
t1.start();
t2.start();
}
}Write a Java program that demonstrates the sleep() method of the Thread class on the main thread. The program should loop 5 times and, on each iteration, make the main thread sleep for 1000 milliseconds (1 second) before printing the loop variable. Catch any exception and print it. Name the class MainThreadSleepDemo.
public class MainThreadSleepDemo
{
public static void main(String[] args)
{
try
{
for (int i = 0; i < 5; i++)
{
Thread.sleep(1000);
System.out.println(i);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}Write a Java program that demonstrates the sleep() method of the Thread class when a negative sleeping time is passed. The program should loop 5 times, and inside the loop call Thread.sleep(-100), which throws an IllegalArgumentException. Catch the exception and print it. Name the class SleepNegativeDemo.
public class SleepNegativeDemo
{
public static void main(String[] args)
{
try
{
for (int i = 0; i < 5; i++)
{
Thread.sleep(-100);
System.out.println(i);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}Write a Java program that demonstrates autoboxing of a primitive into a wrapper object. Declare an int variable with the value 45, then convert it to an Integer in two ways: explicitly using Integer.valueOf(), and implicitly through autoboxing. Print the primitive int, the explicitly created Integer, and the autoboxed Integer separated by spaces.
public class AutoboxDemo {
public static void main(String[] args) {
// Converting int into Integer
int value = 45;
Integer explicitObj = Integer.valueOf(value); // explicit conversion
Integer autoObj = value; // autoboxing: compiler inserts Integer.valueOf(value)
System.out.println(value + " " + explicitObj + " " + autoObj);
}
}Write a Java program that demonstrates unboxing of a wrapper object into a primitive. Create an Integer wrapper object holding the value 7, then convert it to an int in two ways: explicitly using intValue(), and implicitly through unboxing. Print the wrapper object, the explicitly converted int, and the implicitly unboxed int separated by spaces.
public class UnboxDemo {
public static void main(String[] args) {
// Converting Integer to int
Integer num = new Integer(7);
int explicitVal = num.intValue(); // explicit conversion
int autoVal = num; // unboxing: compiler inserts num.intValue()
System.out.println(num + " " + explicitVal + " " + autoVal);
}
}Write a Java program that declares primitive variables of each type (byte, short, int, long, float, double, char, boolean) with the values 5, 15, 25, 35, 45.5F, 55.5D, 'z', false respectively. Convert each primitive into its corresponding wrapper object (autoboxing), print all the objects, then convert each object back to its primitive (unboxing) and print all the primitive values.
public class WrapperDemo {
public static void main(String[] args) {
byte b = 5;
short s = 15;
int i = 25;
long l = 35;
float f = 45.5F;
double d = 55.5D;
char c = 'z';
boolean bool = false;
// Autoboxing: primitives to wrapper objects
Byte byteObj = b;
Short shortObj = s;
Integer intObj = i;
Long longObj = l;
Float floatObj = f;
Double doubleObj = d;
Character charObj = c;
Boolean boolObj = bool;
System.out.println("---Printing object values---");
System.out.println("Byte object: " + byteObj);
System.out.println("Short object: " + shortObj);
System.out.println("Integer object: " + intObj);
System.out.println("Long object: " + longObj);
System.out.println("Float object: " + floatObj);
System.out.println("Double object: " + doubleObj);
System.out.println("Character object: " + charObj);
System.out.println("Boolean object: " + boolObj);
// Unboxing: wrapper objects to primitives
byte byteVal = byteObj;
short shortVal = shortObj;
int intVal = intObj;
long longVal = longObj;
float floatVal = floatObj;
double doubleVal = doubleObj;
char charVal = charObj;
boolean boolVal = boolObj;
System.out.println("---Printing primitive values---");
System.out.println("byte value: " + byteVal);
System.out.println("short value: " + shortVal);
System.out.println("int value: " + intVal);
System.out.println("long value: " + longVal);
System.out.println("float value: " + floatVal);
System.out.println("double value: " + doubleVal);
System.out.println("char value: " + charVal);
System.out.println("boolean value: " + boolVal);
}
}Write a Java program that creates a custom wrapper class named 'Meter' which wraps a primitive int (representing a distance in metres). The class should have a no-arg constructor, a constructor taking an int, getter and setter methods, and an overridden toString() that returns the stored value as a String. In main, create a Meter object with the value 25 and print it.
class Meter {
private int value;
Meter() {}
Meter(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
public class TestMeter {
public static void main(String[] args) {
Meter m = new Meter(25);
System.out.println(m);
}
}Write a Java program that defines a class named Greet and prints the line "Welcome to Java, Rohan" to the console when run.
class Greet {
public static void main(String args[]) {
System.out.println("Welcome to Java, Rohan");
}
}Write a Java program that prints the message "Namaste India" to the console. Use a class named Greet with a main method.
class Greet {
public static void main(String args[]) {
System.out.println("Namaste India");
}
}Write a Java program that prints "Namaste India" to the console using a main method written in an unusual but valid style: put the access modifier after the static modifier, use var-args (three dots) for the String parameter, and end the class declaration with an optional semicolon. The program must compile and run correctly.
class Bharat {
static public void main(String... args) {
System.out.println("Namaste India");
}
};Write a Java program that demonstrates the syntax of a nested interface declared within another interface. Define an interface named 'Vehicle' that contains a nested interface named 'Engine' with a method 'start()'. Then create a class 'Car' that implements 'Vehicle.Engine' and provides the implementation of 'start()' to print "Engine started". Finally, in a main method, instantiate 'Car' and call 'start()'.
interface Vehicle {
interface Engine {
void start();
}
}
class Car implements Vehicle.Engine {
public void start() {
System.out.println("Engine started");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.start();
}
}Write a Java program that demonstrates the syntax of a nested interface declared within a class. Define a class named 'Outer' that contains a nested interface named 'Inner' with a method 'show()'. Then create another class 'Demo' that implements 'Outer.Inner' and provides the implementation of 'show()' to print "Hello from nested interface". Finally, in a main method, instantiate 'Demo' and call 'show()'.
class Outer {
interface Inner {
void show();
}
}
class Demo implements Outer.Inner {
public void show() {
System.out.println("Hello from nested interface");
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
d.show();
}
}Write a Java program named WordCheck.java. Create four String variables: w1 = "delhi", w2 = "delhi", w3 = "DELHI", w4 = "agra". Print the result of w1.equals(w2), then w1.equals(w3), then w1.equals(w4), each on its own line.
public class WordCheck {
public static void main(String[] args) {
String w1 = "delhi";
String w2 = "delhi";
String w3 = "DELHI";
String w4 = "agra";
System.out.println(w1.equals(w2)); // true, same content and case
System.out.println(w1.equals(w3)); // false, case differs
System.out.println(w1.equals(w4)); // false, content differs
}
}Write a Java program named CityCompare.java. Create three String variables: c1 = "Mumbai", c2 = "Mumbai", c3 = "mumbai". First print the result of c1.equals(c2). Then use an if-else statement with c1.equals(c3): if they are equal print "cities match", otherwise print "cities differ".
public class CityCompare {
public static void main(String[] args) {
String c1 = "Mumbai";
String c2 = "Mumbai";
String c3 = "mumbai";
System.out.println(c1.equals(c2)); // true, same content and case
if (c1.equals(c3)) {
System.out.println("cities match");
} else {
System.out.println("cities differ");
}
}
}Write a Java program that demonstrates the finally block when no exception occurs. Inside a try block, compute the integer division 36/6 and print the result. Add a catch block for ArithmeticException that prints the exception message (it will not run here). Add a finally block that prints "cleanup done". After the try-catch-finally, print "program continues". Name the class FinallyDemo.
public class FinallyDemo {
public static void main(String[] args) {
try {
int result = 36 / 6;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("cleanup done");
}
System.out.println("program continues");
}
}Write a Java program that shows that changing a primitive parameter inside a method does not affect the original variable. Create a class named Counter with an int instance variable count set to 30. Add a method modify(int count) that sets count = count + 70 (only the local copy changes). In main, create a Counter object, print "before modify " followed by its count, call modify(300), then print "after modify " followed by its count.
class Counter {
int count = 30;
void modify(int count) {
count = count + 70; // changes will be in the local variable only
}
public static void main(String args[]) {
Counter c = new Counter();
System.out.println("before modify " + c.count);
c.modify(300);
System.out.println("after modify " + c.count);
}
}Write a Java program that demonstrates how passing an object to a method lets the method change the object's instance variable. Create a class named Account with an int instance variable balance set to 2000. Add a method update(Account acc) that adds 500 to acc.balance. In main, create an Account object, print "before update " followed by its balance, call update passing the object, then print "after update " followed by its balance.
class Account {
int balance = 2000;
void update(Account acc) {
acc.balance = acc.balance + 500; // changes the instance variable of the passed object
}
public static void main(String args[]) {
Account acc = new Account();
System.out.println("before update " + acc.balance);
acc.update(acc); // passing object
System.out.println("after update " + acc.balance);
}
}Write a Java program that shows what happens when you try to start the same thread twice. Create a class named TwiceStartDemo that extends Thread. Its run method should print "executing...". In the main method, create one instance of TwiceStartDemo, call start() on it, and then call start() again on the same instance. The program should demonstrate that the second start() throws an IllegalThreadStateException.
public class TwiceStartDemo extends Thread {
public void run() {
System.out.println("executing...");
}
public static void main(String[] args) {
TwiceStartDemo t = new TwiceStartDemo();
t.start();
t.start();
}
}Write a Java program that uses a for loop to print the numbers 1 to 10, but stops the loop (using the break statement) as soon as the number 7 is reached, so that 7 and later numbers are not printed.
public class StopAtSeven {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 7) {
break;
}
System.out.println(i);
}
}
}INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com