Try-Catch in Java:
Basic Try-Catch Syntax:
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling that specific exception
System.out.println("Cannot divide by zero.");
}
Multiple Catch Blocks:
try {
String str = null;
System.out.println(str.length()); // Throws NullPointerException
} catch (NullPointerException e) {
System.out.println("Null value found!");
} catch (Exception e) {
System.out.println("Some other exception: " + e.getMessage());
}
Finally Block:
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println("Number: " + num);
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
} finally {
if (scanner != null) {
scanner.close();
System.out.println("Scanner closed.");
}
}
Catch All Exceptions:
try {
// risky code
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
StringBuffer Methods:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // "Hello World"
sb.insert(5, ","); // "Hello, World"
sb.replace(0, 5, "Hi"); // "Hi, World"
sb.delete(3, 5); // "Hi World"
sb.reverse(); // "dlroW iH"
String result = sb.toString();
Common String Methods:
String s = "hello,world,java";
String[] parts = s.split(","); // ["hello", "world", "java"]
String replaced = s.replace("java", "python");// "hello,world,python"
String sub = s.substring(0, 5); // "hello"
int len = s.length(); // 17
char c = s.charAt(1); // 'e'
int idx = s.indexOf("world"); // 6
boolean hasJava = s.contains("java"); // true
String upper = s.toUpperCase(); // "HELLO,WORLD,JAVA"
String lower = s.toLowerCase(); // "hello,world,java"
String t = " abc ".trim(); // "abc"
Java Coding Round Template:
import java.util.*; // Import for Scanner (input handling) and other utility classes
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String inputString = scanner.nextLine();
System.out.println("Enter an integer:");
int inputInt = scanner.nextInt();
System.out.println("Enter a decimal number:");
double inputDouble = scanner.nextDouble();
System.out.println("Enter two integers:");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int sum = num1 + num2;
double result = inputDouble * 2;
System.out.println("Sum of the two integers: " + sum);
System.out.println("Double of the decimal number: " + result);
scanner.close();
}
}
Check if Input is Integer:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter something:");
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println("You entered integer: " + num);
} else {
String input = scanner.next(); // Consume the invalid input
System.out.println("Not an integer: " + input);
}
scanner.close();