Advanced Java Questions
Advanced Java Questions
Question
1. What is String in Java?
In Java, a String is an object that represents a sequence of characters. It is a built-in
class in Java and is used extensively for text processing and manipulation.
Java String class provides a lot of methods to perform operations on strings such
as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
javaCopy code
public class StringComparisonExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
javaCopy code
public class StringConcatenationExample {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe";
javaCopy code
public class SubstringExample {
public static void main(String[] args) {
String message = "Hello, World!";
String subMessage = message.substring(0, 5);
System.out.println(subMessage); // Output: Hello
}
}
javaCopy code
public class StringMethodsExample {
public static void main(String[] args) {
String str = "Hello, Java";
javaCopy code
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("Hello");
buffer.append(", ");
buffer.append("Java");
System.out.println(buffer); // Output: Hello, Java
}
}
Make all fields private and final to ensure they cannot be modified.
Ensure that any mutable objects used within the class are not directly accessible or
mutable.
javaCopy code
public final class ImmutablePerson {
private final String name;
private final int age;
javaCopy code
public class ToStringExample {
public static void main(String[] args) {
Person person = new Person("John", 30);
System.out.println(person); // Output: Person[name=John, age=30]
}
}
class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
javaCopy code
import java.util.StringTokenizer;
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
CharAt() Method
14. What is the purpose of the charAt() method in Java? Provide an example of its
usage.
The charAt() method is used to get the character at the specified index in a String.
Example:
javaCopy code
String str = "Hello";
char ch = str.charAt(2); // Returns 'l'
CompareTo() Method
15. How does the compareTo() method work in Java? Give an example.
The compareTo() method compares two strings lexicographically and returns an integer
value:
A positive value if the current string is lexicographically greater than the other
string.
A negative value if the current string is lexicographically less than the other
string.
Example:
Concat() Method
javaCopy code
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(str2); // Returns "HelloWorld"
Contains() Method
17. How does the contains() method work in Java? Show an example.
The contains() method checks if the current string contains the specified character
sequence and returns a boolean value.
Example:
javaCopy code
String str = "Hello, Java";
boolean containsJava = str.contains("Java"); // Returns true
18. What is the purpose of the endsWith() method in Java? Give an example.
The endsWith() method checks if the current string ends with the specified suffix and
returns a boolean value.
Example:
javaCopy code
String str = "Hello, Java";
boolean endsWithJava = str.endsWith("Java"); // Returns true
equal() Method
19. How do you compare two strings for equality using the equals() method in
Java?
The equals() method is used to compare the current string with the specified object
and returns a boolean value indicating whether they are equal.
Example:
javaCopy code
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // Returns true
equalIgnoreCase() Method
javaCopy code
String str1 = "hello";
String str2 = "HeLLo";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // Returns true
format() Method
21. Explain the use of the format() method in Java with an example.
The format() method is used to create a formatted string using the specified format and
arguments.
Example:
javaCopy code
String name = "John";
int age = 30;
String formattedString = String.format("My name is %s and I am %d years old.", name, a
ge);
// Returns "My name is John and I am 30 years old."
getBytes() Method
Example:
getChars() Method
23. How do you use the getChars() method in Java? Give an example.
he getChars() method copies characters from the current string to the destination
character array.
Example:
javaCopy code
String str = "Hello, Java";
char[] charArray = new char[5];
str.getChars(0, 5, charArray, 0); // Copies "Hello" to charArray
indexOf() Method
24. Explain the use of the indexOf() method in Java with an example.
The indexOf() method returns the index of the first occurrence of the specified substring
in the current string.
Example:
javaCopy code
String str = "Hello, Java";
int index = str.indexOf("Java"); // Returns 7
25. What is the purpose of the intern() method in Java? Provide an example.
The intern() method returns the canonical representation of the string from the string
pool if it is already present.
Example:
javaCopy code
String str1 = "Hello";
String str2 = new String("Hello").intern();
boolean isEqual = str1 == str2; // Returns true
isEmpty() Method
26. How do you check if a string is empty using the isEmpty() method in Java?
The isEmpty() method checks if the current string is empty (contains no characters) and
returns a boolean value.
Example:
javaCopy code
String str = "";
boolean isEmpty = str.isEmpty(); // Returns true
join() Method
27. Explain the purpose of the join() method in Java with an example.
The join() method joins the elements of the provided CharSequence sequence using
the specified delimiter and returns a new string.
javaCopy code
String[] names = {"John", "Doe", "Alice"};
String joinedString = String.join(", ", names); // Returns "John, Doe, Alice"
lastIndex() Method
28. How does the lastIndexOf() method work in Java? Provide an example.
The lastIndexOf() method returns the index of the last occurrence of the specified
substring in the current string.
Example:
javaCopy code
String str = "Hello, Java";
int lastIndex = str.lastIndexOf("Java"); // Returns 7
length() Method
29. What is the purpose of the length() method in Java? Give an example.
The length() method is used to get the length (number of characters) of the current
string.
Example:
javaCopy code
String str = "Hello, World!";
int length = str.length(); // Returns 13
30. Explain the use of the replace() method in Java with an example.
The replace() method replaces all occurrences of the specified old character with the
new character in the current string.
Example:
javaCopy code
String str = "Hello, World!";
String replacedStr = str.replace('o', 'x'); // Returns "Hellx, Wxrld!"
replaceAll() Method
Example:
javaCopy code
String str = "Hello, Java";
String replacedStr = str.replaceAll("a", "x"); // Returns "Hello, Jxvx"
split() Method
32. Explain the use of the split() method in Java with an example.
javaCopy code
String str = "apple, banana, orange";
String[] fruits = str.split(", ");
// Returns an array: ["apple", "banana", "orange"]
startsWith() Method
javaCopy code
String str = "Hello, Java";
boolean startsWithHello = str.startsWith("Hello"); // Returns true
substring() Method
javaCopy code
String str = "Hello, Java";
toChareArray() Method
35. What is the purpose of the toCharArray() method in Java? Provide an example.
The toCharArray() method converts the current string to a character array.
Example:
javaCopy code
String str = "Hello";
char[] charArray = str.toCharArray(); // Returns ['H', 'e', 'l', 'l', 'o']
toLowerCase() Method
36. How do you convert a string to lowercase using the toLowerCase() method in
Java?
The toLowerCase() method returns a new string with all the characters converted to
lowercase.
Example:
javaCopy code
String str = "Hello, World!";
String lowerCaseStr = str.toLowerCase(); // Returns "hello, world!"
toUpperCase() Method
Example:
javaCopy code
String str = "Hello, World!";
String upperCaseStr = str.toUpperCase(); // Returns "HELLO, WORLD!"
trim() Method
38. How does the trim() method work in Java? Show an example.
The trim() method removes leading and trailing whitespace from the current string.
Example:
javaCopy code
String str = " Hello, Java ";
String trimmedStr = str.trim(); // Returns "Hello, Java"
valueof() Method
39. What is the purpose of the valueOf() method in Java? Give an example.
The valueOf() method converts an object to its string representation.
Example:
javaCopy code
int number = 42;
Java Regex
import java.util.regex.*;
Exception Handling
1. What is exception handling in Java? How do you handle exceptions in Java?
Exception handling in Java allows the program to gracefully handle unexpected
situations or errors. It involves using try , catch , finally , and throw blocks.
Example:
class InnerClass {
void display() {
System.out.println("Data: " + data);
}
}
}
Java Multithreading
Java I/O
1. How do you read input from the user using Scanner class in Java?
You can use the Scanner class from java.util to read input from the user.
Example:
Java Networking
import java.io.*;
import java.net.*;
reader.close();
socket.close();
serverSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}Example (Client):
```java
import java.io.*;
import java.net.*;
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java AWT
1. What is AWT in Java? How do you create a simple window using Frame class?
AWT (Abstract Window Toolkit) is a GUI toolkit in Java. You can create a simple
window using the Frame class.
Example:
import java.awt.*;
1. How do you create a simple Swing application with a button and event
handling?
Swing is a GUI library in Java. You can create a simple Swing application with a
button and event handling using JFrame and JButton .
Example:
import javax.swing.*;
import java.awt.event.*;
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
JavaFX
import javafx.application.Application;
import javafx.scene.Scene;
Java Applet
import java.applet.Applet;
import java.awt.*;
Java Reflection
Example:
import java.lang.reflect.*;
Java Date
1. How do you work with dates in Java? How do you get the current date and
format it using SimpleDateFormat ?
In Java, you can work with dates using java.util.Date and SimpleDateFormat .
Example:
import java.util.*;
import java.text.*;
Example (Parsing):