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