hereral/Clara-Training-Data huggingface dataset:
Question: Could you provide Java String replaceAll() example: replace character?
Answer: Let's see an example to replace all the occurrences of a single character.

FileName: ReplaceAllExample1.java

public class ReplaceAllExample1{  
public static void main(String args[]){  
String s1="javatpoint is a very good website";  
String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"  
System.out.println(replaceString);  
}}  

Output:
jevetpoint is e very good website
Question: Could you provide Java String replaceAll() example: replace word?
Answer: Let's see an example to replace all the occurrences of a single word or set of words.

FileName: ReplaceAllExample2.java
public class ReplaceAllExample2{  
public static void main(String args[]){  
String s1="My name is Khan. My name is Bob. My name is Sonoo.";  
String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"  
System.out.println(replaceString);  
}}  

Output:
My name was Khan. My name was Bob. My name was Sonoo.
Question: Java String replaceAll() example: remove white spaces?
Answer: Let's see an example to remove all the occurrences of white spaces.

FileName: ReplaceAllExample3.java
public class ReplaceAllExample3{  
public static void main(String args[]){  
String s1="My name is Khan. My name is Bob. My name is Sonoo.";  
String replaceString=s1.replaceAll("\\s","");  
System.out.println(replaceString);  
}}  

Output:
MynameisKhan.MynameisBob.MynameisSonoo.
Question: What is Java String split()?
Answer: The java string split() method splits this string against given regular expression and returns a char array.
Question: Could you provide Java String split() method example?
Answer: The given example returns total number of words in a string excluding space only. It also includes special characters.

public class SplitExample{  
public static void main(String args[]){  
String s1="java string split method by javatpoint";  
String[] words=s1.split("\\s");//splits the string based on whitespace  
//using java foreach loop to print elements of string array  
for(String w:words){  
System.out.println(w);  
}  
}}  

java
string
split
method
by
javatpoint
Question: Could you provide Java String split() method with regex and length example?
Answer: public class SplitExample2{  
public static void main(String args[]){  
String s1="welcome to split world";  
System.out.println("returning words:");  
for(String w:s1.split("\\s",0)){  
System.out.println(w);  
}  
System.out.println("returning words:");  
for(String w:s1.split("\\s",1)){  
System.out.println(w);  
}  
System.out.println("returning words:");  
for(String w:s1.split("\\s",2)){  
System.out.println(w);  
}  
  
}} 

returning words:
welcome 
to 
split 
world
returning words:
welcome to split world
returning words:
welcome 
to split world
Question: What is Java String startsWith()?
Answer: The Java String class startsWith() method checks if this string starts with the given prefix. It returns true if this string starts with the given prefix; else returns false.
Question: Could you provide Java String startsWith() method example?
Answer: The startsWith() method considers the case-sensitivity of characters. Consider the following example.

FileName: StartsWithExample.java
public class StartsWithExample  
{    
// main method  
public static void main(String args[])  
{    
// input string  
String s1="java string split method by javatpoint";    
System.out.println(s1.startsWith("ja"));  // true  
System.out.println(s1.startsWith("java string"));   // true  
System.out.println(s1.startsWith("Java string"));  // false as 'j' and 'J' are different   
}  
}    

Output:
true
true
false
Question: Can you provide an example of Java String startsWith(String prefix, int offset) Method?
Answer: It is an overloaded method of the startWith() method that is used to pass an extra argument (offset) to the function. The method works from the passed offset. Let's see an example.

FileName: StartsWithExample2.java
public class StartsWithExample2 {    
    public static void main(String[] args) {    
        String str = "Javatpoint";    
        // no offset mentioned; hence, offset is 0 in this case.  
        System.out.println(str.startsWith("J")); // True    
  
         // no offset mentioned; hence, offset is 0 in this case.  
        System.out.println(str.startsWith("a")); // False   
        // offset is 1  
        System.out.println(str.startsWith("a",1)); // True    
    }    
}    

Output:
true
false
true
Question: What is Java String substring()?
Answer: The Java String class substring() method returns a part of the string.

We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.

There are two types of substring methods in Java string.
Question: Can you provide an example of Java String substring() method?
Answer: FileName: SubstringExample.java

public class SubstringExample{  
public static void main(String args[]){  
String s1="javatpoint";  
System.out.println(s1.substring(2,4));//returns va  
System.out.println(s1.substring(2));//returns vatpoint  
}}  

Output:
va
vatpoint
Question: Can you provide an example of Applications of substring() Method
Answer: 1) The substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as "singh". The following program shows the same.

FileName: SubstringExample3.java
public class SubstringExample3   
{  
// main method  
public static void main(String argvs[])  
{  
String str[] =  
{  
"Praveen Kumar",  
"Yuvraj Singh",  
"Harbhajan Singh",  
"Gurjit Singh",  
"Virat Kohli",  
"Rohit Sharma",  
"Sandeep Singh",  
"Milkha Singh"  
};  
  
String surName = "Singh";  
int surNameSize = surName.length();  
  
int size = str.length;  
  
for(int j = 0; j < size; j++)  
{  
    int length = str[j].length();  
    // extracting the surname  
    String subStr = str[j].substring(length - surNameSize);  
      
    // checks whether the surname is equal to "Singh" or not  
    if(subStr.equals(surName))  
    {  
        System.out.println(str[j]);  
    }  
}  
  
}  
}  
Output:
Yuvraj Singh
Harbhajan Singh
Gurjit Singh
Sandeep Singh
Milkha Singh


2) The substring() method can also be used to check whether a string is a palindrome or not.

FileName: SubstringExample4.java
public class SubstringExample4   
{  
public boolean isPalindrome(String str)  
{  
int size = str.length();  
  
// handling the base case  
if(size == 0 || size == 1)  
{  
// an empty string   
// or a string of only one character   
// is always a palindrome  
return true;  
}  
String f = str.substring(0, 1);  
String l = str.substring(size - 1);  
// comparing first and the last character of the string  
if(l.equals(f))  
{  
// recursively finding the solution using the substring() method  
// reducing the number of characters of the by 2 for the next recursion  
return isPalindrome(str.substring(1, size - 1));  
}  
return false;  
}  
// main method  
public static void main(String argvs[])  
{  
// instantiating the class SubstringExample4   
SubstringExample4 obj = new SubstringExample4();  
String str[] =  
{  
"madam",  
"rock",  
"eye",  
"noon",  
"kill"  
};  
int size = str.length;  
  
for(int j = 0; j < size; j++)  
{  
if(obj.isPalindrome(str[j]))  
{  
System.out.println(str[j] + " is a palindrome.");  
}  
else  
{  
System.out.println(str[j] + " is not a palindrome.");  
}  
}  
}  
}  

Output:
madam is a palindrome.
rock is not a palindrome.
eye is a palindrome.
noon is a palindrome.
kill is not a palindrome.
Question: What is Java String toCharArray()?
Answer: The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
Question: Can you provide an example of Java String toCharArray() method?
Answer: public class StringToCharArrayExample{  
public static void main(String args[]){  
String s1="hello";  
char[] ch=s1.toCharArray();  
for(int i=0;i<ch.length;i++){  
System.out.print(ch[i]);  
}  
}}  

Output:
hello
Question: What is Java String toLowerCase()?
Answer: The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default locale.
Question: Can you provide an example of Java String toLowerCase() method?
Answer: public class StringLowerExample{  
public static void main(String args[]){  
String s1="JAVATPOINT HELLO stRIng";  
String s1lower=s1.toLowerCase();  
System.out.println(s1lower);  
}}  

Output:
javatpoint hello string
Question: Could you provide Java String toLowerCase(Locale locale) Method Example?
Answer: This method allows us to pass locale too for the various langauges. Let's see an example below where we are getting string in english and turkish both.

import java.util.Locale;  
public class StringLowerExample2 {  
    public static void main(String[] args) {  
        String s = "JAVATPOINT HELLO stRIng";    
        String eng = s.toLowerCase(Locale.ENGLISH);  
        System.out.println(eng);  
        String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot  
        System.out.println(turkish);  
    }  
}  

Output:
javatpoint hello string
javatpo?nt hello str?ng
Question: What is Java String toUpperCase()?
Answer: The java string toUpperCase() method returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter.

The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It internally uses the default locale.
Question: Can you provide an example of Java String toUpperCase() method?
Answer: public class StringUpperExample{  
public static void main(String args[]){  
String s1="hello string";  
String s1upper=s1.toUpperCase();  
System.out.println(s1upper);  
}}  

Output:
HELLO STRING
Question: What is Java String trim()?
Answer: The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.
Question: Can you provide an example of Java String trim() Method?
Answer: FileName: StringTrimExample.java

public class StringTrimExample{  
public static void main(String args[]){  
String s1="  hello string   ";  
System.out.println(s1+"javatpoint");//without trim()  
System.out.println(s1.trim()+"javatpoint");//with trim()  
}}  

Output
hello string   javatpoint
hello stringjavatpoint
Question: What is Java String valueOf()?
Answer: The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.
Question: Could you provide an example of Java String valueOf() method?
Answer: public class StringValueOfExample{  
public static void main(String args[]){  
int value=30;  
String s1=String.valueOf(value);  
System.out.println(s1+10);//concatenating string with 10  
}}  

Output:
3010
Question: Could you provide Java String valueOf(boolean bol) Method Example?
Answer: This is a boolean version of overloaded valueOf() method. It takes boolean value and returns a string. Let's see an example.

public class StringValueOfExample2 {  
    public static void main(String[] args) {          
        // Boolean to String  
        boolean bol = true;    
        boolean bol2 = false;    
        String s1 = String.valueOf(bol);    
        String s2 = String.valueOf(bol2);  
        System.out.println(s1);  
        System.out.println(s2);  
    }  
}  

Output:
true
false
Question: Could you provide Java String valueOf(char ch) Method Example?
Answer: This is a char version of overloaded valueOf() method. It takes char value and returns a string. Let's see an example.

public class StringValueOfExample3 {  
    public static void main(String[] args) {  
        // char to String         
        char ch1 = 'A';    
        char ch2 = 'B';  
        String s1 = String.valueOf(ch1);    
        String s2 = String.valueOf(ch2);  
        System.out.println(s1);  
        System.out.println(s2);  
    }  
}  

Output:
A
B
Question: Can you provide an example of Java String valueOf(float f) and valueOf(double d)?
Answer: This is a float version of overloaded valueOf() method. It takes float value and returns a string. Let's see an example.

public class StringValueOfExample4 {  
    public static void main(String[] args) {  
        // Float and Double to String  
        float f  = 10.05f;    
        double d = 10.02;  
        String s1 = String.valueOf(f);    
        String s2 = String.valueOf(d);  
        System.out.println(s1);  
        System.out.println(s2);  
    }  
}  

Output:
10.05
10.02
Question: Can you provide an example of Java String valueOf() Complete?
Answer: Let's see an example where we are converting all primitives and objects into strings.

public class StringValueOfExample5 {  
    public static void main(String[] args) {  
        boolean b1=true;  
        byte b2=11;    
        short sh = 12;  
        int i = 13;  
        long l = 14L;  
        float f = 15.5f;  
        double d = 16.5d;  
        char chr[]={'j','a','v','a'};  
        StringValueOfExample5 obj=new StringValueOfExample5();  
        String s1 = String.valueOf(b1);    
        String s2 = String.valueOf(b2);    
        String s3 = String.valueOf(sh);    
        String s4 = String.valueOf(i);    
        String s5 = String.valueOf(l);    
        String s6 = String.valueOf(f);    
        String s7 = String.valueOf(d);    
        String s8 = String.valueOf(chr);    
        String s9 = String.valueOf(obj);    
        System.out.println(s1);  
        System.out.println(s2);  
        System.out.println(s3);  
        System.out.println(s4);  
        System.out.println(s5);  
        System.out.println(s6);  
        System.out.println(s7);  
        System.out.println(s8);  
        System.out.println(s9);  
    }  
} 
 
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55
Question: What is Java Regex?
Answer: The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.

It is widely used to define the constraint on strings such as password and email validation. After learning Java regex tutorial, you will be able to test your regular expressions by the Java Regex Tester Tool.

Java Regex API provides 1 interface and 3 classes in java.util.regex package.
Question: What are the java.util.regex package?
Answer: The Matcher and Pattern classes provide the facility of Java regular expression. The java.util.regex package provides following classes and interfaces for regular expressions.

1.MatchResult interface
2.Matcher class
3.Pattern class
4.PatternSyntaxException class
Question: Wha is Matcher class?
Answer: Matcher class Method

Method: boolean matches()
Description: test whether the regular expression matches the pattern.

Method: boolean find()
Description: finds the next expression that matches the pattern.

Method: boolean find(int start)
Description: finds the next expression that matches the pattern from the given start number.

Method: String group()
Description: returns the matched subsequence.


Method: int start()
Description: returns the starting index of the matched subsequence.

Method: int end()
Description: returns the ending index of the matched subsequence.

Method: int groupCount()
Description: returns the total number of the matched subsequence.
Question: What is Pattern class?
Answer: It is the compiled version of a regular expression. It is used to define a pattern for the regex engine.


Pattern Class Method

Method: static Pattern compile(String regex)
Description: compiles the given regex and returns the instance of the Pattern.

Method: Matcher matcher(CharSequence input)
Description: creates a matcher that matches the given input with the pattern.

Method: static boolean matches(String regex, CharSequence input)
Description: It works as the combination of compile and matcher methods. It compiles the regular expression and matches the given input with the pattern.

Method: String[] split(CharSequence input)
Description: splits the given input string around matches of given pattern.

Method: String pattern()
Description: returns the regex pattern.
Question: Could you provide Example of Java Regular Expressions?
Answer:  There are three ways to write the regex example in Java.

import java.util.regex.*;  
public class RegexExample1{  
public static void main(String args[]){  
//1st way  
Pattern p = Pattern.compile(".s");//. represents single character  
Matcher m = p.matcher("as");  
boolean b = m.matches();  
  
//2nd way  
boolean b2=Pattern.compile(".s").matcher("as").matches();  
  
//3rd way  
boolean b3 = Pattern.matches(".s", "as");  
  
System.out.println(b+" "+b2+" "+b3);  
}}  
Output
true true true
Question: Could you provide Regular Expression . Example?
Answer: The . (dot) represents a single character.

import java.util.regex.*;  
class RegexExample2{  
public static void main(String args[]){  
System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)  
System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)  
System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)  
System.out.println(Pattern.matches(".s", "amms"));//false (has more than 2 char)  
System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)  
}}
Question: What are the Regex Character classes?
Answer: Regex Character Class methods

Method: [abc]
Description: a, b, or c (simple class)

Method: [^abc]
Description: Any character except a, b, or c (negation)

Method: [a-zA-Z]
Description: a through z or A through Z, inclusive (range)

Method:  [a-d[m-p]]
Description: a through d, or m through p: [a-dm-p] (union)

Method: [a-z&&[def]]
Description: d, e, or f (intersection)

Method: [a-z&&[^bc]]
Description: a through z, except for b and c: [ad-z] (subtraction)

Method: [a-z&&[^m-p]]
Description: a through z, and not m through p: [a-lq-z](subtraction)
Question: Could you provide Regular Expression Character classes Example?
Answer: import java.util.regex.*;  
class RegexExample3{  
public static void main(String args[]){  
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)  
System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)  
System.out.println(Pattern.matches("[amn]", "ammmna"));//false (m and a comes more than once)  
}}
Question: What are the Regex Quantifiers?
Answer: The quantifiers specify the number of occurrences of a character.

Regex Description methods

Method: X?
Description: X occurs once or not at all

Method:  X+
Description: X occurs once or more times
 
Method: X*
Description: X occurs zero or more times

Method: X{n}
Description: X occurs n times only

Method: X{n,}
Description: X occurs n or more times

Method: X{y,z}
Description: X occurs at least y times but less than z times
Question: Could you provide Regular Expression Character classes and Quantifiers Example?
Answer: import java.util.regex.*;  
class RegexExample4{  
public static void main(String args[]){  
System.out.println("? quantifier ....");  
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)  
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)  
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)  
  
System.out.println("+ quantifier ....");  
System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)  
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)  
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)  
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)  
  
System.out.println("* quantifier ....");  
System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)  
  
}}
Question: What are the Regex Metacharacters?
Answer: The regular expression metacharacters work as shortcodes.

Regex Metacharacters

Regex: .
Description: Any character (may or may not match terminator)

Regex: \d
Description: Any digits, short of [0-9]

Regex: 
Description:

Regex: \D
Description: Any non-digit, short for [^0-9]

Regex: \s
Description: Any whitespace character, short for [\t\n\x0B\f\r]

Regex: \S
Description: Any non-whitespace character, short for [^\s]
Regex: \w
Description: Any word character, short for [a-zA-Z_0-9]

Regex: \W
Description: Any non-word character, short for [^\w]

Regex: \b
Description: A word boundary

Regex: \B
Description: A non word boundary
Question: Can you provide an example of Regular Expression Metacharacters?
Answer: import java.util.regex.*;  
class RegexExample5{  
public static void main(String args[]){  
System.out.println("metacharacters d....");\\d means digit  
  
System.out.println(Pattern.matches("\\d", "abc"));//false (non-digit)  
System.out.println(Pattern.matches("\\d", "1"));//true (digit and comes once)  
System.out.println(Pattern.matches("\\d", "4443"));//false (digit but comes more than once)  
System.out.println(Pattern.matches("\\d", "323abc"));//false (digit and char)  
  
System.out.println("metacharacters D....");\\D means non-digit  
  
System.out.println(Pattern.matches("\\D", "abc"));//false (non-digit but comes more than once)  
System.out.println(Pattern.matches("\\D", "1"));//false (digit)  
System.out.println(Pattern.matches("\\D", "4443"));//false (digit)  
System.out.println(Pattern.matches("\\D", "323abc"));//false (digit and char)  
System.out.println(Pattern.matches("\\D", "m"));//true (non-digit and comes once)  
  
System.out.println("metacharacters D with quantifier....");  
System.out.println(Pattern.matches("\\D*", "mak"));//true (non-digit and may come 0 or more times)  
  
}}
Question: What is Exception Handling in Java?
Answer: The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between checked and unchecked exceptions.
Question: What is Exception in Java?
Answer: Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Question: What is Exception Handling?
Answer: Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Question: What is the Advantage of Exception Handling?
Answer: The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions. Let's consider a scenario:

statement 1;  
statement 2;  
statement 3;  
statement 4;  
statement 5;//exception occurs  
statement 6;  
statement 7;  
statement 8;  
statement 9;  
statement 10;  
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.
Question: What are the Types of Java Exceptions?
Answer: There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1.Checked Exception
2.Unchecked Exception
3.Error
Question: What is the Difference between Checked and Unchecked Exceptions?
Answer: 1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
Question: What is Java Exception Keywords? 
Answer: 
Java provides five keywords that are used to handle the exception. The following table describes each.
Java Exception Keywords

Keyword: try
Description: The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.

Keyword: catch
Description: The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

Keyword: finally
Description: The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.

Keyword: throw
Description: The "throw" keyword is used to throw an exception.

Keyword: throws
Description: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.
Question: Can you provide an example of Java Exception Handling Example?
Answer: et's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.

JavaExceptionExample.java

public class JavaExceptionExample{  
  public static void main(String args[]){  
   try{  
      //code that may raise exception  
      int data=100/0;  
   }catch(ArithmeticException e){System.out.println(e);}  
   //rest code of the program   
   System.out.println("rest of the code...");  
  }  
}  
Output:

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Question: What are Common Scenarios of Java Exceptions?
Answer: There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException  
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

String s=null;  
System.out.println(s.length());//NullPointerException  
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.

String s="abc";  
int i=Integer.parseInt(s);//NumberFormatException  
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException
Question: What is the purpose of Java try block?
Answer: Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.
Question: What is the function of a catch block in Java?
Answer: Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch block with a single try block.
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:

Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed.
Question: what is the Problem without exception handling?
Answer: Let's try to understand the problem if we don't use a try-catch block.
public class TryCatchExample1 {  
  
    public static void main(String[] args) {  
          
        int data=50/0; //may throw exception   
          
        System.out.println("rest of the code");  
          
    }  
      
}  
Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
Question: what is Java Multi-catch block?
Answer: A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Points to remember
-At a time only one exception occurs and at a time only one catch block is executed.
-All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
Question: What is Java Nested try block?
Answer: In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack.

For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).

Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.
Question: Why use nested try block?
Answer: Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....    
//main try block  
try    
{    
    statement 1;    
    statement 2;    
//try catch block within another try block  
    try    
    {    
        statement 3;    
        statement 4;    
//try catch block within nested try block  
        try    
        {    
            statement 5;    
            statement 6;    
     }    
        catch(Exception e2)    
        {    
//exception message  
        }    
  
    }    
    catch(Exception e1)    
    {    
//exception message  
    }    
}    
//catch block of parent (outer) try block  
catch(Exception e3)    
{    
//exception message  
}    
....
Question: What is Java finally block?
Answer: Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.
Question: Why use Java finally block?
Answer: -finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
-The important statements to be printed can be placed in the finally block.
Question: What is Java throw Exception?
Answer: In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time instead of runtime and we can create custom exceptions making the code recovery and debugging easier.
Question: What is Java throw keyword?
Answer: The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. We will discuss custom exceptions later in this section.

We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set the condition and throw exception using throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

throw new exception_class("error message");  
Let's see the example of throw IOException.

throw new IOException("sorry device error");   
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is the sub class of Throwable and the user-defined exceptions usually extend the Exception class.
Question: What is Java Exception Propagation?
Answer: An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.
Question: Can you give me an example of Exception Propagation?
Answer: Exception Propagation Example
TestExceptionPropagation1.java

class TestExceptionPropagation1{  
  void m(){  
    int data=50/0;  
  }  
  void n(){  
    m();  
  }  
  void p(){  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");}  
  }  
  public static void main(String args[]){  
   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  
Output:

exception handled
       normal flow...
Question: What is Java throws keyword?
Answer: The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{  
//method code  
}
Question: What is the Advantage of Java throws keyword?
Answer: Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.
Question: Can you give me an example of Java throws?
Answer: Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws keyword.

Testthrows1.java

import java.io.IOException;  
class Testthrows1{  
  void m()throws IOException{  
    throw new IOException("device error");//checked exception  
  }  
  void n()throws IOException{  
    m();  
  }  
  void p(){  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");}  
  }  
  public static void main(String args[]){  
   Testthrows1 obj=new Testthrows1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  
Output:

exception handled
normal flow...
Question: What is the Difference between throw and throws in Java?
Answer: Difference between throw and throws in Java

Basis of Differences: Definition
Throw: Java throw keyword is used throw an exception explicitly in the code, inside the function or the block of code.
Throws: Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.


Basis of Differences: Type of exception Using throw keyword, we can only propagate unchecked exception i.e., the checked exception cannot be propagated using throw only.
Throw: Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only.
Throws:


Basis of Differences: Syntax
Throw: The throw keyword is followed by an instance of Exception to be thrown.
Throws: The throws keyword is followed by class names of Exceptions to be thrown.


Basis of Differences:  Declaration
Throw: throw is used within the method.
Throws: throws is used with the method signature.



Basis of Differences: Internal implementation
Throw: We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions.
Throws: We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException.
Question: What is the Difference between final, finally and finalize in Java?
Answer: Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality. The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Along with this, there are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:

Key:  Definition
Final: final is the keyword and access modifier which is used to apply restrictions on a class, method or variable.
Finally: finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not.
Finalize: finalize is the method in Java which is used to perform clean up processing just before object is garbage collected.

Key: Applicable to
Final: Final keyword is used with the classes, methods and variables.
Finally: Finally block is always related to the try and catch block in exception handling.
Finalize: finalize() method is used with the objects.

Key: Functionality
Final: (1) Once declared, final variable becomes constant and cannot be modified.
(2) final method cannot be overridden by sub class.
(3) final class cannot be inherited.
Finally: (1) finally block runs the important code even if exception occurs or not.
(2) finally block cleans up all the resources used in try block
Finalize: finalize method performs the cleaning activities with respect to the object before its destruction.

Key: Execution
Final: Final method is executed only when we call it.
Finally: Finally block is executed as soon as the try-catch block is executed.
It's execution is not dependant on the exception.
Finalize: finalize method is executed just before the object is destroyed.
Question: Can you give an example of Java final?
Answer: FinalExampleTest.java

public class FinalExampleTest {  
    //declaring final variable  
    final int age = 18;  
    void display() {  
      
    // reassigning value to age variable   
    // gives compile time error  
    age = 55;  
    }  
      
    public static void main(String[] args) {  
      
    FinalExampleTest obj = new FinalExampleTest();  
    // gives compile time error  
    obj.display();  
    }  
}
Question: Can you give me an example of Java finally?
Answer: Let's see the below example where the Java code throws an exception and the catch block handles that exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.

FinallyExample.java

public class FinallyExample {    
      public static void main(String args[]){   
      try {    
        System.out.println("Inside try block");  
      // below code throws divide by zero exception  
       int data=25/0;    
       System.out.println(data);    
      }   
      // handles the Arithmetic Exception / Divide by zero exception  
      catch (ArithmeticException e){  
        System.out.println("Exception handled");  
        System.out.println(e);  
      }   
      // executes regardless of exception occurred or not   
      finally {  
        System.out.println("finally block is always executed");  
      }    
      System.out.println("rest of the code...");    
      }    
    }
Question: Can you give me an example of Java finalize?
Answer: FinalizeExample.java

public class FinalizeExample {    
     public static void main(String[] args)     
    {     
        FinalizeExample obj = new FinalizeExample();        
        // printing the hashcode   
        System.out.println("Hashcode is: " + obj.hashCode());           
        obj = null;    
        // calling the garbage collector using gc()   
        System.gc();     
        System.out.println("End of the garbage collection");     
    }     
   // defining the finalize method   
    protected void finalize()     
    {     
        System.out.println("Called the finalize() method");     
    }     
}
Question: What is Exception Handling with Method Overriding in Java?
Answer: There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:

-If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
-If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
-If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
Question: What is Java Custom Exception?
Answer: In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.

In this section, we will learn how custom exceptions are implemented and used in Java programs.
Question: Why use custom exceptions?
Answer: Java exceptions cover almost all the general type of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

-To catch and provide specific treatment to a subset of existing Java exceptions.
-Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.
In order to create custom exception, we need to extend Exception class that belongs to java.lang package.

Consider the following example, where we create a custom exception named WrongFileNameException:

public class WrongFileNameException extends Exception {  
    public WrongFileNameException(String errorMessage) {  
    super(errorMessage);  
    }  
}  
Note: We need to write the constructor that takes the String as the error message and it is called parent class constructor.
Question: What is Java Inner Classes (Nested Classes)?
Answer: Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.

Additionally, it can access all the members of the outer class, including private data members and methods.

Syntax of Inner class
class Java_Outer_class{  
 //code  
 class Java_Inner_class{  
  //code  
 }  
}
Question: What is the Advantage of Java inner classes?
Answer: There are three advantages of inner classes in Java. They are as follows:

1.Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
2.Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3.Code Optimization: It requires less code to write.
Question: What does Java Inner class need?
Answer: Sometimes users need to program a class in such a way so that no other class can access it. Therefore, it would be better if you include it within other classes.

If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class. That way all the outer class can access all the objects of the inner class.
Question: What is the Difference between nested class and inner class in Java?
Answer: An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
Question: Can you give me the Types of Nested classes?
Answer: There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.
o	Non-static nested class (inner class)
1.	Member inner class
2.	Anonymous inner class
3.	Local inner class
o	Static nested class

Type: Member inner class
Description: : A class created within class and outside method.


Type: : Anonymous inner class
DescriptionA class created for implementing an interface or extending class. The java compiler decides its name.

Type: local inner class
Description: A class was created within the method.

Type: static nested class
DescriptionA static class was created within the class.
Type: nested interface
Description: An interface created within class or interface.
Question: What is Java Member Inner class?
Answer: A non-static class that is created inside a class but outside a method is called member inner class. It is also known as a regular inner class. It can be declared with access modifiers like public, default, private, and protected.

Syntax:

class Outer{  
 //code  
 class Inner{  
  //code  
 }  
}
Question: Can you give me an example of Java Member Inner Class?
Answer: In this example, we are creating a msg() method in the member inner class that is accessing the private data member of the outer class.

TestMemberOuter1.java

class TestMemberOuter1{  
 private int data=30;  
 class Inner{  
  void msg(){System.out.println("data is "+data);}  
 }  
 public static void main(String args[]){  
  TestMemberOuter1 obj=new TestMemberOuter1();  
  TestMemberOuter1.Inner in=obj.new Inner();  
  in.msg();  
 }  
}  
Output:

data is 30