Java catch multiple exceptions:
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.
- 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.
Example :
In this example, we generate NullPointerException, but didn't provide the corresponding exception type. In such case, the catch block containing the parent exception class Exception will invoked.
public class MultipleCatchBlock4 {
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");
}
}
Test it Now
Output:
Parent Exception occurs
rest of the code
Nested try block
The try block within a try block is known as nested try block in java.
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.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Nested try example
Let's see a simple example of java nested try block.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java throw keyword:
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
Throw keyword example:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
throws keyword
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 normal flow can be maintained.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
throws example:
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...
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception.
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...

String:
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
- By string literal
- By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).
Java String Example
java strings example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No. | Method | Description |
---|---|---|
1 | char charAt(int index) | returns char value for the particular index |
2 | int length() | returns string length |
3 | static String format(String format, Object... args) | returns a formatted string. |
4 | static String format(Locale l, String format, Object... args) | returns formatted string with given locale. |
5 | String substring(int beginIndex) | returns substring for given begin index. |
6 | String substring(int beginIndex, int endIndex) | returns substring for given begin index and end index. |
7 | boolean contains(CharSequence s) | returns true or false after matching the sequence of char value. |
8 | static String join(CharSequence delimiter, CharSequence... elements) | returns a joined string. |
9 | static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) | returns a joined string. |
10 | boolean equals(Object another) | checks the equality of string with the given object. |
11 | boolean isEmpty() | checks if string is empty. |
12 | String concat(String str) | concatenates the specified string. |
13 | String replace(char old, char new) | replaces all occurrences of the specified char value. |
14 | String replace(CharSequence old, CharSequence new) | replaces all occurrences of the specified CharSequence. |
15 | static String equalsIgnoreCase(String another) | compares another string. It doesn't check case. |
16 | String[] split(String regex) | returns a split string matching regex. |
17 | String[] split(String regex, int limit) | returns a split string matching regex and limit. |
18 | String intern() | returns an interned string. |
19 | int indexOf(int ch) | returns the specified char value index. |
20 | int indexOf(int ch, int fromIndex) | returns the specified char value index starting with given index. |
21 | int indexOf(String substring) | returns the specified substring index. |
22 | int indexOf(String substring, int fromIndex) | returns the specified substring index starting with given index. |
23 | String toLowerCase() | returns a string in lowercase. |
24 | String toLowerCase(Locale l) | returns a string in lowercase using specified locale. |
25 | String toUpperCase() | returns a string in uppercase. |
26 | String toUpperCase(Locale l) | returns a string in uppercase using specified locale. |
27 | String trim() | removes beginning and ending spaces of this string. |
28 | static String valueOf(int value) | converts given type into string. It is an overloaded method. |
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable.
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.Java String compare
1) String compare by equals() methodThe String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
Output:true true false false |
2) String compare by == operator
The = = operator compares references not values.
Output:true false
3) String compare by compareTo() method
The String compareTo() method compares values and returns an integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
- s1 == s2 :0
- s1 > s2 :positive value
- s1 < s2 :negative value
Output:0 1 -1
String Concatenation in Java
There are two ways to concat string in java:
- By + (string concatenation) operator
- By concat() method
1) String Concatenation by + (string concatenation) operator
Java string concatenation operator (+) is used to add strings. For Example:
Output:Sachin Tendulkar
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string. Syntax:
Let's see the example of String concat() method.
Sachin Tendulkar
Substring in Java
You can get substring from the given string object by one of the two methods:
- public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
- public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
- startIndex: inclusive
- endIndex: exclusive
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
SACHIN sachin Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
Sachin Sachin
Java String startsWith() and endsWith() method
true true
Java String charAt() method
The string charAt() method returns a character at specified index.
S h
Java String length() method
The string length() method returns length of the string.
6
Java String intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.
Output:
1010
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java String split()
The java string split() method splits this string against given regular expression and returns a char array.
Signature
There are two signature for split() method in java string.
Java String split() method example
The given example returns total number of words in a string excluding space only. It also includes special characters.
java string split method by javatpoint
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Important Constructors of StringBuffer class
Constructor | Description |
---|---|
StringBuffer() | creates an empty string buffer with the initial capacity of 16. |
StringBuffer(String str) | creates a string buffer with the specified string. |
StringBuffer(int capacity) | creates an empty string buffer with the specified capacity as length. |
Important methods of StringBuffer class
Modifier and Type | Method | Description |
---|---|---|
public synchronized StringBuffer | append(String s) | is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. |
public synchronized StringBuffer | insert(int offset, String s) | is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. |
public synchronized StringBuffer | replace(int startIndex, int endIndex, String str) | is used to replace the string from specified startIndex and endIndex. |
public synchronized StringBuffer | delete(int startIndex, int endIndex) | is used to delete the string from specified startIndex and endIndex. |
public synchronized StringBuffer | reverse() | is used to reverse the string. |
public int | capacity() | is used to return the current capacity. |
public void | ensureCapacity(int minimumCapacity) | is used to ensure the capacity at least equal to the given minimum. |
public char | charAt(int index) | is used to return the character at the specified position. |
public int | length() | is used to return the length of the string i.e. total number of characters. |
public String | substring(int beginIndex) | is used to return the substring from the specified beginIndex. |
public String | substring(int beginIndex, int endIndex) | is used to return the substring from the specified beginIndex and endIndex. |
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
- StringBuffer sb=new StringBuffer("Hello ");
- sb.append("Java");//now original string is changed
- System.out.println(sb);//prints Hello Java
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Important Constructors of StringBuilder class
Constructor | Description |
---|---|
StringBuilder() | creates an empty string Builder with the initial capacity of 16. |
StringBuilder(String str) | creates a string Builder with the specified string. |
StringBuilder(int length) | creates an empty string Builder with the specified capacity as length. |
Important methods of StringBuilder class
Method | Description |
---|---|
public StringBuilder append(String s) | is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. |
public StringBuilder insert(int offset, String s) | is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. |
public StringBuilder replace(int startIndex, int endIndex, String str) | is used to replace the string from specified startIndex and endIndex. |
public StringBuilder delete(int startIndex, int endIndex) | is used to delete the string from specified startIndex and endIndex. |
public StringBuilder reverse() | is used to reverse the string. |
public int capacity() | is used to return the current capacity. |
public void ensureCapacity(int minimumCapacity) | is used to ensure the capacity at least equal to the given minimum. |
public char charAt(int index) | is used to return the character at the specified position. |
public int length() | is used to return the length of the string i.e. total number of characters. |
public String substring(int beginIndex) | is used to return the substring from the specified beginIndex. |
public String substring(int beginIndex, int endIndex) | is used to return the substring from the specified beginIndex and endIndex. |
Java StringBuilder Examples
Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
No. | String | StringBuffer |
---|---|---|
1) | String class is immutable. | StringBuffer class is mutable. |
2) | String is slow and consumes more memory when you concat too many strings because every time it creates new instance. | StringBuffer is fast and consumes less memory when you cancat strings. |
3) | String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. | StringBuffer class doesn't override the equals() method of Object class. |
complete this below programs using String
How to compare two strings?
How to find occurance of a substring inside a string?
How to remove a particular character from a string?
How to replace a substring inside a string by another one ?
How to reverse a String?
How to search a word inside a string?
How to split a string into a number of substrings ?
How to convert a string totally into upper case?
How to concatenate two strings?
program to check whether the given string is palindrome or not
program to count no of characters without space.
program to count the words in the given sentence.
program to find the no of occurrence of each character in th given string.
program to make capital of first character each word in the given sentence.
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight wrapper classes are given below:
Primitive Type | Wrapper class |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.
Wrapper class Example: Primitive to Wrapper
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives.
Wrapper class Example: Wrapper to Primitive
Output:
3 3 3
Java Wrapper classes Example
Output:
---Printing object values--- Byte object: 10 Short object: 20 Integer object: 30 Long object: 40 Float object: 50.0 Double object: 60.0 Character object: a Boolean object: true ---Printing primitive values--- byte value: 10 short value: 20 int value: 30 long value: 40 float value: 50.0 double value: 60.0 char value: a boolean value: true
Custom Wrapper class in Java
Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper classes. We can also create a class which wraps a primitive data type. So, we can create a custom wrapper class in Java.
Output:
10
Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Methods of Object class
The Object class provides many methods. They are as follows: |
Method | Description |
---|---|
public final Class getClass() | returns the Class class object of this object. The Class class can further be used to get the metadata of this class. |
public int hashCode() | returns the hashcode number for this object. |
public boolean equals(Object obj) | compares the given object to this object. |
protected Object clone() throws CloneNotSupportedException | creates and returns the exact copy (clone) of this object. |
public String toString() | returns the string representation of this object. |
public final void notify() | wakes up single thread, waiting on this object's monitor. |
public final void notifyAll() | wakes up all the threads, waiting on this object's monitor. |
public final void wait(long timeout)throws InterruptedException | causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait(long timeout,int nanos)throws InterruptedException | causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait()throws InterruptedException | causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). |
protected void finalize()throws Throwable | is invoked by the garbage collector before object is being garbage collected. |
Object Cloning in Java
The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
Let's see the simple example of object cloning
Output:101 amit 101 amit
equals() and hashCode() methods in Java
Java.lang.object has two very important methods defined: public boolean equals(Object obj) and public int hashCode().
equals() method:
In java equals() method is used to compare equality of two Objects. The equality can be compared in two ways:
- Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is also known as shallow comparison.
- Deep Comparison: Suppose a class provides its own implementation of equals() method in order to compare the Objects of that class w.r.t state of the Objects. That means data members (i.e. fields) of Objects are to be compared with one another. Such Comparison based on data members is known as deep comparison.
Output:
Both Objects are equal.
Java toString() methodIf you want to represent any object as a string, toString() method comes into existence.The toString() method returns the string representation of the object. By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code. Understanding problem without toString() methodLet's see the simple code that prints reference.Output:Student@1fee6fc Student@1eed786 Example of Java toString() methodNow let's see the real example of toString() method.Output:101 Raj lucknow 102 Vijay ghaziabad |
Java Object getClass() Method
getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class.
Syntax
Returns
It returns the Class objects that represent the runtime class of this object.
Example 1
Output:
Class of Object obj is : java.lang.String
Java Object finalize() Method
Finalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.Syntax
Throw
Throwable - the Exception is raised by this methodExample 1
Output:2018699554 end of garbage collection finalize method calledJava Inner Classes
Java inner class or nested class is a class which is declared inside the class or interface.We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.Syntax of Inner class
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of 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.There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
- Non-static nested class (inner class)
- Member inner class
- Anonymous inner class
- Local inner class
- Static nested class
Java Member inner class
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
Java Member inner class example
In this example, we are creating msg() method in member inner class that is accessing the private data member of outer class.
Output:
data is 30
Internal code generated by the compiler
The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.
Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:
- Class (may be abstract or concrete).
- Interface
Java anonymous inner class example using class
Output:nice fruits
Internal working of given code
- A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
- An object of Anonymous class is created that is referred by p reference variable of Person type.
Internal class generated by the compiler
Java anonymous inner class example using interface
Output:
nice fruits
Internal working of given code
It performs two main tasks behind this code:
- A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
- An object of Anonymous class is created that is referred by p reference variable of Eatable type.
Internal class generated by the compiler
Java Local inner class
A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
Java local inner class example
Output:
30
Note:
1) Local inner class cannot be invoked from outside the method.
Example of local inner class with local variable
Output:
50
Java static nested class
A static class i.e. created inside a class is called static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.
- It can access static data members of outer class including private.
- Static nested class cannot access non-static (instance) data member or method.
Java static nested class example with instance method
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object.
Comments
Post a Comment