Skip to main content

Core Java part2



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:
  1. By string literal
  2. By new keyword


1) String Literal

Java String literal is created by using double quotes. For Example:
  1. String s="welcome";  
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:
  1. String s1="Welcome";  
  2. String s2="Welcome";//It doesn't create a new instance  
Java string literal

2) By new keyword

  1. String s=new String("Welcome");//creates two objects and one reference variable  
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

  1. public class StringExample{  
  2. public static void main(String args[]){  
  3. String s1="java";//creating string by java string literal  
  4. char ch[]={'s','t','r','i','n','g','s'};  
  5. String s2=new String(ch);//converting char array to string  
  6. String s3=new String("example");//creating java string by new keyword  
  7. System.out.println(s1);  
  8. System.out.println(s2);  
  9. System.out.println(s3);  
  10. }}  

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.MethodDescription
1char charAt(int index)returns char value for the particular index
2int length()returns string length
3static String format(String format, Object... args)returns a formatted string.
4static String format(Locale l, String format, Object... args)returns formatted string with given locale.
5String substring(int beginIndex)returns substring for given begin index.
6String substring(int beginIndex, int endIndex)returns substring for given begin index and end index.
7boolean contains(CharSequence s)returns true or false after matching the sequence of char value.
8static String join(CharSequence delimiter, CharSequence... elements)returns a joined string.
9static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)returns a joined string.
10boolean equals(Object another)checks the equality of string with the given object.
11boolean isEmpty()checks if string is empty.
12String concat(String str)concatenates the specified string.
13String replace(char old, char new)replaces all occurrences of the specified char value.
14String replace(CharSequence old, CharSequence new)replaces all occurrences of the specified CharSequence.
15static String equalsIgnoreCase(String another)compares another string. It doesn't check case.
16String[] split(String regex)returns a split string matching regex.
17String[] split(String regex, int limit)returns a split string matching regex and limit.
18String intern()returns an interned string.
19int indexOf(int ch)returns the specified char value index.
20int indexOf(int ch, int fromIndex)returns the specified char value index starting with given index.
21int indexOf(String substring)returns the specified substring index.
22int indexOf(String substring, int fromIndex)returns the specified substring index starting with given index.
23String toLowerCase()returns a string in lowercase.
24String toLowerCase(Locale l)returns a string in lowercase using specified locale.
25String toUpperCase()returns a string in uppercase.
26String toUpperCase(Locale l)returns a string in uppercase using specified locale.
27String trim()removes beginning and ending spaces of this string.
28static 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.
  1. class Testimmutablestring{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin";  
  4.    s.concat(" Tendulkar");//concat() method appends the string at the end  
  5.    System.out.println(s);//will print Sachin because strings are immutable objects  
  6.  }  
  7. }  
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.
Heap diagram

  1. class Testimmutablestring1{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin";  
  4.    s=s.concat(" Tendulkar");  
  5.    System.out.println(s);  
  6.  }  
  7. }  

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. By equals() method
  2. By = = operator
  3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
  1. class Teststringcomparison1{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="Sachin";  
  5.    String s3=new String("Sachin");  
  6.    String s4="Saurav";  
  7.    System.out.println(s1.equals(s2));//true  
  8.    System.out.println(s1.equals(s3));//true  
  9.    System.out.println(s1.equals(s4));//false  
  10.  }  
  11. }  
Output:true
       true
       false
  1. class Teststringcomparison2{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="SACHIN";  
  5.   
  6.    System.out.println(s1.equals(s2));//false  
  7.    System.out.println(s1.equalsIgnoreCase(s2));//true  
  8.  }  
  9. }  
Output:
false

2) String compare by == operator

The = = operator compares references not values.
  1. class Teststringcomparison3{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="Sachin";  
  5.    String s3=new String("Sachin");  
  6.    System.out.println(s1==s2);//true (because both refer to same instance)  
  7.    System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
  8.  }  
  9. }  

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
  1. class Teststringcomparison4{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin";  
  4.    String s2="Sachin";  
  5.    String s3="Ratan";  
  6.    System.out.println(s1.compareTo(s2));//0  
  7.    System.out.println(s1.compareTo(s3));//1(because s1>s3)  
  8.    System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
  9.  }  
  10. }  
Output:0
       1
       -1

String Concatenation in Java

 There are two ways to concat string in java:
  1. By + (string concatenation) operator
  2. By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:
  1. class TestStringConcatenation1{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin"+" Tendulkar";  
  4.    System.out.println(s);//Sachin Tendulkar  
  5.  }  
  6. }  
Output:Sachin Tendulkar

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string. Syntax:
  1. public String concat(String another)  
Let's see the example of String concat() method.
  1. class TestStringConcatenation3{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin ";  
  4.    String s2="Tendulkar";  
  5.    String s3=s1.concat(s2);  
  6.    System.out.println(s3);//Sachin Tendulkar  
  7.   }  
  8. }  
Sachin Tendulkar

Substring in Java

You can get substring from the given string object by one of the two methods:
  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  2. 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

  1.   String s="SachinTendulkar";  
  2.    System.out.println(s.substring(6));//Tendulkar  
  3.    System.out.println(s.substring(0,6));//Sachin  


Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
  1. String s="Sachin";  
  2. System.out.println(s.toUpperCase());//SACHIN  
  3. System.out.println(s.toLowerCase());//sachin  
  4. System.out.println(s);//Sachin(no change in original)  
SACHIN
sachin
Sachin

Java String trim() method

The string trim() method eliminates white spaces before and after string.
  1. String s="  Sachin  ";  
  2. System.out.println(s);//  Sachin    
  3. System.out.println(s.trim());//Sachin  
  Sachin  
Sachin

Java String startsWith() and endsWith() method

  1. String s="Sachin";  
  2.  System.out.println(s.startsWith("Sa"));//true  
  3.  System.out.println(s.endsWith("n"));//true  
true
true

Java String charAt() method

The string charAt() method returns a character at specified index.
  1. String s="Sachin";  
  2. System.out.println(s.charAt(0));//S  
  3. System.out.println(s.charAt(3));//h 
S
h

Java String length() method

The string length() method returns length of the string.
  1. String s="Sachin";  
  2. System.out.println(s.length());//6  

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.
  1. String s=new String("Sachin");  
  2. String s2=s.intern();  
  3. System.out.println(s2);//Sachin  
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.
  1. int a=10;  
  2. String s=String.valueOf(a);  
  3. System.out.println(s+10);  
Output:
1010

Java String replace() method

The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
  1. String s1="Java is a programming language. Java is a platform. Java is an Island.";    
  2. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"    
  3. System.out.println(replaceString);    
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.
  1. public String split(String regex)  
  2. and,  
  3. public String split(String regex, int limit)  

Java String split() method example

The given example returns total number of words in a string excluding space only. It also includes special characters.
  1. public class SplitExample{  
  2. public static void main(String args[]){  
  3. String s1="java string split method by javatpoint";  
  4. String[] words=s1.split("\\s");//splits the string based on whitespace  
  5. //using java foreach loop to print elements of string array  
  6. for(String w:words){  
  7. System.out.println(w);  
  8. }  
  9. }}  

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

ConstructorDescription
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 TypeMethodDescription
public synchronized StringBufferappend(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 StringBufferinsert(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 StringBufferreplace(int startIndex, int endIndex, String str)is used to replace the string from specified startIndex and endIndex.
public synchronized StringBufferdelete(int startIndex, int endIndex)is used to delete the string from specified startIndex and endIndex.
public synchronized StringBufferreverse()is used to reverse the string.
public intcapacity()is used to return the current capacity.
public voidensureCapacity(int minimumCapacity)is used to ensure the capacity at least equal to the given minimum.
public charcharAt(int index)is used to return the character at the specified position.
public intlength()is used to return the length of the string i.e. total number of characters.
public Stringsubstring(int beginIndex)is used to return the substring from the specified beginIndex.
public Stringsubstring(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

  1. StringBuffer sb=new StringBuffer("Hello ");  
  2. sb.append("Java");//now original string is changed  
  3. 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.
  1. class StringBufferExample2{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello ");  
  4. sb.insert(1,"Java");//now original string is changed  
  5. System.out.println(sb);//prints HJavaello  
  6. }  
  7. }  

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.
  1. class StringBufferExample3{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello");  
  4. sb.replace(1,3,"Java");  
  5. System.out.println(sb);//prints HJavalo  
  6. }  
  7. }  

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
  1. class StringBufferExample4{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello");  
  4. sb.delete(1,3);  
  5. System.out.println(sb);//prints Hlo  
  6. }  
  7. }  

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.
  1. class StringBufferExample5{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer("Hello");  
  4. sb.reverse();  
  5. System.out.println(sb);//prints olleH  
  6. }  
  7. }  

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.
  1. class StringBufferExample6{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. }  
  10. }  

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.
  1. class StringBufferExample7{  
  2. public static void main(String args[]){  
  3. StringBuffer sb=new StringBuffer();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. sb.ensureCapacity(10);//now no change  
  10. System.out.println(sb.capacity());//now 34  
  11. sb.ensureCapacity(50);//now (34*2)+2  
  12. System.out.println(sb.capacity());//now 70  
  13. }  
  14. }  

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

ConstructorDescription
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

MethodDescription
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.

  1. lass StringBuilderExample{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.append("Java");//now original string is changed  
  5. System.out.println(sb);//prints Hello Java  
  6. }  
  7. }  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.
  1. class StringBuilderExample2{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello ");  
  4. sb.insert(1,"Java");//now original string is changed  
  5. System.out.println(sb);//prints HJavaello  
  6. }  
  7. }  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
  1. class StringBuilderExample3{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.replace(1,3,"Java");  
  5. System.out.println(sb);//prints HJavalo  
  6. }  
  7. }  

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
  1. class StringBuilderExample4{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.delete(1,3);  
  5. System.out.println(sb);//prints Hlo  
  6. }  
  7. }  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.
  1. class StringBuilderExample5{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder("Hello");  
  4. sb.reverse();  
  5. System.out.println(sb);//prints olleH  
  6. }  
  7. }  

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.
  1. class StringBuilderExample6{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. }  
  10. }  

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.
  1. class StringBuilderExample7{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. sb.ensureCapacity(10);//now no change  
  10. System.out.println(sb.capacity());//now 34  
  11. sb.ensureCapacity(50);//now (34*2)+2  
  12. System.out.println(sb.capacity());//now 70  
  13. }  
  14. }  

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.StringStringBuffer
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 TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble


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
  1. //Java program to convert primitive into objects  
  2. //Autoboxing example of int to Integer  
  3. public class WrapperExample1{  
  4. public static void main(String args[]){  
  5. //Converting int into Integer  
  6. int a=20;  
  7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
  8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  9.   
  10. System.out.println(a+" "+i+" "+j);  
  11. }}  
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
  1. //Java program to convert object into primitives  
  2. //Unboxing example of Integer to int  
  3. public class WrapperExample2{    
  4. public static void main(String args[]){    
  5. //Converting Integer to int    
  6. Integer a=new Integer(3);    
  7. int i=a.intValue();//converting Integer to int explicitly  
  8. int j=a;//unboxing, now compiler will write a.intValue() internally    
  9.     
  10. System.out.println(a+" "+i+" "+j);    
  11. }}    
Output:
3 3 3

Java Wrapper classes Example

  1. //Java Program to convert all primitives into its corresponding   
  2. //wrapper objects and vice-versa  
  3. public class WrapperExample3{  
  4. public static void main(String args[]){  
  5. byte b=10;  
  6. short s=20;  
  7. int i=30;  
  8. long l=40;  
  9. float f=50.0F;  
  10. double d=60.0D;  
  11. char c='a';  
  12. boolean b2=true;  
  13.   
  14. //Autoboxing: Converting primitives into objects  
  15. Byte byteobj=b;  
  16. Short shortobj=s;  
  17. Integer intobj=i;  
  18. Long longobj=l;  
  19. Float floatobj=f;  
  20. Double doubleobj=d;  
  21. Character charobj=c;  
  22. Boolean boolobj=b2;  
  23.   
  24. //Printing objects  
  25. System.out.println("---Printing object values---");  
  26. System.out.println("Byte object: "+byteobj);  
  27. System.out.println("Short object: "+shortobj);  
  28. System.out.println("Integer object: "+intobj);  
  29. System.out.println("Long object: "+longobj);  
  30. System.out.println("Float object: "+floatobj);  
  31. System.out.println("Double object: "+doubleobj);  
  32. System.out.println("Character object: "+charobj);  
  33. System.out.println("Boolean object: "+boolobj);  
  34.   
  35. //Unboxing: Converting Objects to Primitives  
  36. byte bytevalue=byteobj;  
  37. short shortvalue=shortobj;  
  38. int intvalue=intobj;  
  39. long longvalue=longobj;  
  40. float floatvalue=floatobj;  
  41. double doublevalue=doubleobj;  
  42. char charvalue=charobj;  
  43. boolean boolvalue=boolobj;  
  44.   
  45. //Printing primitives  
  46. System.out.println("---Printing primitive values---");  
  47. System.out.println("byte value: "+bytevalue);  
  48. System.out.println("short value: "+shortvalue);  
  49. System.out.println("int value: "+intvalue);  
  50. System.out.println("long value: "+longvalue);  
  51. System.out.println("float value: "+floatvalue);  
  52. System.out.println("double value: "+doublevalue);  
  53. System.out.println("char value: "+charvalue);  
  54. System.out.println("boolean value: "+boolvalue);  
  55. }}  
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.
  1. //Creating the custom wrapper class  
  2. class Javatpoint{  
  3. private int i;  
  4. Javatpoint(){}  
  5. Javatpoint(int i){  
  6. this.i=i;  
  7. }  
  8. public int getValue(){  
  9. return i;  
  10. }  
  11. public void setValue(int i){  
  12. this.i=i;  
  13. }  
  14. @Override  
  15. public String toString() {  
  16.   return Integer.toString(i);  
  17. }  
  18. }  
  19. //Testing the custom wrapper class  
  20. public class TestJavatpoint{  
  21. public static void main(String[] args){  
  22. Javatpoint j=new Javatpoint(10);  
  23. System.out.println(j);  
  24. }}  
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:
MethodDescription
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 CloneNotSupportedExceptioncreates 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 InterruptedExceptioncauses 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 InterruptedExceptioncauses 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 InterruptedExceptioncauses the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwableis 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
  1. class Student implements Cloneable{  
  2. int rollno;  
  3. String name;  
  4.   
  5. Student(int rollno,String name){  
  6. this.rollno=rollno;  
  7. this.name=name;  
  8. }  
  9.   
  10. public Object clone()throws CloneNotSupportedException{  
  11. return super.clone();  
  12. }  
  13.   
  14. public static void main(String args[]){  
  15. try{  
  16. Student s1=new Student(101,"amit");  
  17.   
  18. Student s2=(Student)s1.clone();  
  19.   
  20. System.out.println(s1.rollno+" "+s1.name);  
  21. System.out.println(s2.rollno+" "+s2.name);  
  22.   
  23. }catch(CloneNotSupportedException c){}  
  24.   
  25. }  
  26. }  

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.
import java.io.*;
  
class Employee
{
      
    public String name;
    public int id;
          
    Employee(String name, int id) 
    {
              
        this.name = name;
        this.id = id;
    }
      
    @Override
    public boolean equals(Object obj)
    {
          
    // checking if both the object references are 
    // referring to the same object.
    if(this == obj)
            return true;
          
             
        if(obj == null || obj.getClass()!= this.getClass())
            return false;
          
        // type casting of the argument. 
        Employee emp= (Employee) obj;
          
        // comparing the state of argument with 
        // the state of 'this' Object.
        return (emp.name == this.name && emp.id == this.id);
    }
      
    @Override
    public int hashCode()
    {
                 
        return this.id;
    }
      
}
  
//Driver code
class Test
{
      
    public static void main (String[] args)
    {
      
        // creating the Objects of Geek class.
        Employee e1= new Employee("aa", 1);
        Employee e2= new Employee("aa", 1);
          
        // comparing above created Objects.
        if(e1.hashCode() == e2.hashCode())
        {
  
            if(e1.equals(e2))
                System.out.println("Both Objects are equal. ");
            else
                System.out.println("Both Objects are not equal. ");
      
        }
        else
        System.out.println("Both Objects are not equal. "); 
    
}
Output:
Both Objects are equal.

Java toString() method

If 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() method

Let's see the simple code that prints reference.
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  String city;  
  5.   
  6.  Student(int rollno, String name, String city){  
  7.  this.rollno=rollno;  
  8.  this.name=name;  
  9.  this.city=city;  
  10.  }  
  11.   
  12.  public static void main(String args[]){  
  13.    Student s1=new Student(101,"Raj","lucknow");  
  14.    Student s2=new Student(102,"Vijay","ghaziabad");  
  15.      
  16.    System.out.println(s1);//compiler writes here s1.toString()  
  17.    System.out.println(s2);//compiler writes here s2.toString()  
  18.  }  
  19. }  
Output:Student@1fee6fc
       Student@1eed786

Example of Java toString() method

Now let's see the real example of toString() method.
  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  String city;  
  5.   
  6.  Student(int rollno, String name, String city){  
  7.  this.rollno=rollno;  
  8.  this.name=name;  
  9.  this.city=city;  
  10.  }  
  11.    
  12.  public String toString(){//overriding the toString() method  
  13.   return rollno+" "+name+" "+city;  
  14.  }  
  15.  public static void main(String args[]){  
  16.    Student s1=new Student(101,"Raj","lucknow");  
  17.    Student s2=new Student(102,"Vijay","ghaziabad");  
  18.      
  19.    System.out.println(s1);//compiler writes here s1.toString()  
  20.    System.out.println(s2);//compiler writes here s2.toString()  
  21.  }  
  22. }  

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

  1. public final Class<?> getClass()  

Returns

It returns the Class objects that represent the runtime class of this object.

Example 1

  1. public class JavaObjectgetClassExample2{  
  2.     public static void main(String[] args)   
  3.     {   
  4.         Object obj1 = new String("Facebook");   
  5.         Class a = obj1.getClass();   
  6.         System.out.println("Class of Object obj is : a.getName());   
  7.     }   
  8. }  

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

  1. protected void finalize() throws Throwable  

Throw

Throwable - the Exception is raised by this method

Example 1

  1. public class JavafinalizeExample1 {  
  2.      public static void main(String[] args)   
  3.     {   
  4.         JavafinalizeExample1 obj = new JavafinalizeExample1();   
  5.         System.out.println(obj.hashCode());   
  6.         obj = null;   
  7.         // calling garbage collector    
  8.         System.gc();   
  9.         System.out.println("end of garbage collection");   
  10.   
  11.     }   
  1.     @Override  
  2.     protected void finalize()   
  3.     {   
  4.         System.out.println("finalize method called");   
  5.     }   
  6. }  
Output:
2018699554
end of garbage collection 
finalize method called





Java 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

  1. class Java_Outer_class{  
  2.  //code  
  3.  class Java_Inner_class{  
  4.   //code  
  5.  }  
  6. }  

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)
    1. Member inner class
    2. Anonymous inner class
    3. 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:
  1. class Outer{  
  2.  //code  
  3.  class Inner{  
  4.   //code  
  5.  }  
  6. }  

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.
  1. class TestMemberOuter1{  
  2.  private int data=30;  
  3.  class Inner{  
  4.   void msg(){System.out.println("data is "+data);}  
  5.  }  
  6.  public static void main(String args[]){  
  7.   TestMemberOuter1 obj=new TestMemberOuter1();  
  8.   TestMemberOuter1.Inner in=obj.new Inner();  
  9.   in.msg();  
  10.  }  
  11. }  
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.
  1. import java.io.PrintStream;  
  2. class Outer$Inner  
  3. {  
  4.     final Outer this$0;  
  5.     Outer$Inner()  
  6.     {   super();  
  7.         this$0 = Outer.this;  
  8.     }  
  9.     void msg()  
  10.     {  
  11.         System.out.println((new StringBuilder()).append("data is ")  
  12.                     .append(Outer.access$000(Outer.this)).toString());  
  13.     }  
  14. }  


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:
  1. Class (may be abstract or concrete).
  2. Interface

Java anonymous inner class example using class

  1. abstract class Person{  
  2.   abstract void eat();  
  3. }  
  4. class TestAnonymousInner{  
  5.  public static void main(String args[]){  
  6.   Person p=new Person(){  
  7.   void eat(){System.out.println("nice fruits");}  
  8.   };  
  9.   p.eat();  
  10.  }  
  11. }  
Output:
nice fruits

Internal working of given code

  1. Person p=new Person(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. 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.
  2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner$1 extends Person  
  3. {  
  4.    TestAnonymousInner$1(){}  
  5.    void eat()  
  6.     {  
  7.         System.out.println("nice fruits");  
  8.     }  
  9. }  

Java anonymous inner class example using interface

  1. interface Eatable{  
  2.  void eat();  
  3. }  
  4. class TestAnnonymousInner1{  
  5.  public static void main(String args[]){  
  6.  Eatable e=new Eatable(){  
  7.   public void eat(){System.out.println("nice fruits");}  
  8.  };  
  9.  e.eat();  
  10.  }  
  11. }  
Output:
nice fruits

Internal working of given code

It performs two main tasks behind this code:
  1. Eatable p=new Eatable(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. 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.
  2. An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner1$1 implements Eatable  
  3. {  
  4. TestAnonymousInner1$1(){}  
  5. void eat(){System.out.println("nice fruits");}  
  6. }  

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

  1. public class localInner1{  
  2.  private int data=30;//instance variable  
  3.  void display(){  
  4.   class Local{  
  5.    void msg(){System.out.println(data);}  
  6.   }  
  7.   Local l=new Local();  
  8.   l.msg();  
  9.  }  
  10.  public static void main(String args[]){  
  11.   localInner1 obj=new localInner1();  
  12.   obj.display();  
  13.  }  
  14. }  
Output:
30


Note:

1) Local inner class cannot be invoked from outside the method.

Example of local inner class with local variable

  1. class localInner2{  
  2.  private int data=30;//instance variable  
  3.  void display(){  
  4.   int value=50;//local variable must be final till jdk 1.7 only  
  5.   class Local{  
  6.    void msg(){System.out.println(value);}  
  7.   }  
  8.   Local l=new Local();  
  9.   l.msg();  
  10.  }  
  11.  public static void main(String args[]){  
  12.   localInner2 obj=new localInner2();  
  13.   obj.display();  
  14.  }  
  15. }  

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

  1. class TestOuter1{  
  2.   static int data=30;  
  3.   static class Inner{  
  4.    void msg(){System.out.println("data is "+data);}  
  5.   }  
  6.   public static void main(String args[]){  
  7.   TestOuter1.Inner obj=new TestOuter1.Inner();  
  8.   obj.msg();  
  9.   }  
  10. }  

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

Popular posts from this blog

Java Collections

Collections in Java The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has: Interfaces and classes. Algorithm. Hierarchy of Collection Framework The  java.util  package contains all the classes and interfaces for the Collection framework. Iterable Interface The Iterable interface is the root interface for all the collection classes. It contains only one abstract method. i.e., Iterator<T> iterator()   It returns the iterator over the elements of type T. Collection Interface The Collection interface is the interface which is implemented by all the classes in the collection framework. It declares the methods that every collection will have.  Methods of Collection interface There are many methods declared in the Collection interface. They are as follows: No. Method Description 1 public boolean add(E e) It is used to insert an element ...

C Programming

C Programming: ----------------- C is a general purpose programming language founded by Dennis Ritche in 1972 at Bell labs. Language: ------- Langue is a vocabulary and set of  gamer rules to community human in the world. 1)Learn alphabets(a-z) 2)Form words(i,we,he she,they ,the ete) 3)Form sentence by set of gramer rules. 4)Paragraph. ex: I go to office everyday at 10 am. Programming language: Programming language is a vocabulary and set of gramer rules to instruct the computer to perform various task. 1)learn alphabets,numbers,special symbols(a-z,0-9,@,$,^) 2)int a,b,c; 3)c=a+b; 4)program c can be defines as follows: 1.mother language.  Most of the compilers,JVM's and kernels are written in c.  Most of the languages follow c syntax. 2.Procedure oriented language.  A procedure is know as function,methods,routine or sub routine.A procedure language specifies a series of steps for the program to perform tasks. 3.Structured language. Struc...