Learn Java Programming http://www.c4learn.com/javaprogramming Java Basic Tutorials | Step By Step Learn Java Sun, 12 May 2013 13:02:04 +0000 en-US hourly 1 http://wordpress.org/?v=3.5.1 Finally block : Exception Handling in Java Programming http://www.c4learn.com/javaprogramming/finally-block-exception-handling-in-java-programming/?utm_source=rss&utm_medium=rss&utm_campaign=finally-block-exception-handling-in-java-programming http://www.c4learn.com/javaprogramming/finally-block-exception-handling-in-java-programming/#comments Sun, 12 May 2013 12:42:01 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7971 In the previous chapter we have studied the nested try and catch blocks in this chapter we will be learning the finally block. Finally block : Exception Handling in Java Finally Block in always executed irrespective of exception is handled or not Finally is not a function, It is keyword in java Finally performs the(...)

The post Finally block : Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
In the previous chapter we have studied the nested try and catch blocks in this chapter we will be learning the finally block.

Finally block : Exception Handling in Java

  1. Finally Block in always executed irrespective of exception is handled or not
  2. Finally is not a function, It is keyword in java
  3. Finally performs the functions such as closing the stream or file and closing connections.
  4. Finally block always gets executed before terminating the program by JVM.
  5. Finally block should be after try and catch and is optional
  6. Each try block has minimum 0 and maximum 1 finally block.

Flowchart for finally block -

Finally Block in Java Programming

Finally block : Syntax

try {
-------
-------
} catch(Exception e) {
-------
-------
}
finally {

}

Tip 1 : Finally block is optional

In the program we can have minimum zero and maximum one finally block.

public class MyExceptionExample {
    public static void main(String[] a){
        
        try{
            int i = 10/0;
        } catch(Exception ex){
            System.out.println("Inside 1st catch Block");
        }
        

        try{
            int i = 10/10;
        } catch(Exception ex){
            System.out.println("Inside 2nd catch Block");
        } finally {
            System.out.println("Inside 2nd finally block");
        }
    }
}

In the 1st try block we can see that we don’t have finally block but in the 2nd try block we have finally block. So finally block is always optional.

finally {
    System.out.println("Inside 2nd finally block");
}

2nd try block does not throw any exception but still after the execution of try block code executes finally block

Output :

Inside 1st catch Block
Inside 2nd finally block

Tip 2 : Finally block is not executed in below two cases

  1. If following statement is included in the try block (Terminating code using system exit)
  2. System.exit(0);
    
  3. If the thread executing the try or catch code is interrupted or killed, the finally block may not execute [For more info]

The post Finally block : Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/finally-block-exception-handling-in-java-programming/feed/ 0
Nested Try Block Statement : Exception Handling in Java http://www.c4learn.com/javaprogramming/nested-try-block-statement/?utm_source=rss&utm_medium=rss&utm_campaign=nested-try-block-statement http://www.c4learn.com/javaprogramming/nested-try-block-statement/#comments Sun, 05 May 2013 04:05:42 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7969 Sometimes situation occurred, where we need to catch multiple conditions. In the previous tutorial we have learnt about the catching multiple exception using only one catch block. In this chapter we will be learning nested try block. Consider the following snippet - public class ExceptionExample { public static void main(String argv[]) { int result =(...)

The post Nested Try Block Statement : Exception Handling in Java appeared first on Learn Java Programming.

]]>
Sometimes situation occurred, where we need to catch multiple conditions. In the previous tutorial we have learnt about the catching multiple exception using only one catch block. In this chapter we will be learning nested try block. Consider the following snippet -

public class ExceptionExample {

    public static void main(String argv[]) {

     int result = 0;
     int arr[] = new int[5];

     arr[5] = 5;

     result = 100 / 0;
     System.out.println("Result of Division : " + result);

  }
}

In this example we can see that

arr[5] = 5;
result = 100 / 0;

both these lines will generate exception.If we put both these codes in same try block then it will generate one exception and the next code won’t be executed.

public class ExceptionExample {

    public static void main(String argv[]) {

     int num1 = 10;
     int num2 = 0;
     int result = 0;
     int arr[] = new int[5];

	try {
	     try {
	     arr[5] = 5;
	}catch (ArrayIndexOutOfBoundsException e) {
	System.out.println("Err: Array Out of Bound");
	}    

	try {
	     result = num1 / num2;
	}catch (ArithmeticException e) {
	     System.out.println("Err: Divided by Zero");
	}
	System.out.println("Result of Division : " + result);

   }catch (Exception e) {
        System.out.println("Exception Occured !");
   }

  }
}

In the above code each and every exception is handled. In order to handle each exception we need to use try block.

The post Nested Try Block Statement : Exception Handling in Java appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/nested-try-block-statement/feed/ 0
Catching multiple exception types using single catch block http://www.c4learn.com/javaprogramming/catching-multiple-exception-types-using-single-catch-block/?utm_source=rss&utm_medium=rss&utm_campaign=catching-multiple-exception-types-using-single-catch-block http://www.c4learn.com/javaprogramming/catching-multiple-exception-types-using-single-catch-block/#comments Tue, 23 Apr 2013 09:33:09 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7966 Consider following multiple catch blocks – Below example contain two catch blocks having two exceptions (i.e IOException and SQLException) Catching Multiple Exception in single catch : Whenever try block will thrown any exception of these type then and then only we can handle the exception. catch (IOException ex) { System.out.println("IO Exception"); throw ex; } catch(...)

The post Catching multiple exception types using single catch block appeared first on Learn Java Programming.

]]>
Consider following multiple catch blocks – Below example contain two catch blocks having two exceptions (i.e IOException and SQLException)

Catching Multiple Exception in single catch :

Whenever try block will thrown any exception of these type then and then only we can handle the exception.

catch (IOException ex) {
     System.out.println("IO Exception");
     throw ex;
} catch (SQLException ex) {
     System.out.println("SQL Exception");
     throw ex;
}
  1. If in a try block we need to handle multiple exceptions then we need to write exception handler for each type of exception.
  2. We can combine the multiple exceptions in catch block using Pipe (|) Operator.
catch (IOException|SQLException ex) {
    System.out.println("Exception thrown");
    throw ex;
}

above single catch block can handle IO as well as SQL exceptions. So it is better to use Pipe Operator to handle multiple exceptions instead of writing individual catch block for each exception. Also Refer this oracle guide for more information.

Parameter Accepted by Catch Block is Final :

  1. If a catch block handles more than one exception type, then the catch parameter is implicitly final.
  2. In this example, the catch parameter ex is final.
  3. We cannot assign any values to it within the catch block.
Note :We can use Pipe (|) to catch multiple exceptions only in Java SE 7 or in higher versions.

The post Catching multiple exception types using single catch block appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/catching-multiple-exception-types-using-single-catch-block/feed/ 0
Multiple Catch Blocks : Exception Handling in Java http://www.c4learn.com/javaprogramming/multiple-catch-blocks-exception-handling-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=multiple-catch-blocks-exception-handling-in-java http://www.c4learn.com/javaprogramming/multiple-catch-blocks-exception-handling-in-java/#comments Tue, 23 Apr 2013 07:38:55 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7964 We have already learnt about the try catch statements in java. Try-Catch statement is used to handle exceptions in java. Multiple Catch Blocks : Catching Multiple Exceptions public class ExceptionExample { public static void main(String argv[]) { int num1 = 10; int num2 = 0; int result = 0; int arr[] = new int[5]; try(...)

The post Multiple Catch Blocks : Exception Handling in Java appeared first on Learn Java Programming.

]]>
We have already learnt about the try catch statements in java. Try-Catch statement is used to handle exceptions in java.

Multiple Catch Blocks : Catching Multiple Exceptions

public class ExceptionExample {

    public static void main(String argv[]) {

     int num1 = 10;
     int num2 = 0;
     int result = 0;
     int arr[] = new int[5];

     try {
	 arr[0] = 0;
	 arr[1] = 1;
	 arr[2] = 2;
	 arr[3] = 3;
	 arr[4] = 4;
	 arr[5] = 5;

    result = num1 / num2;
    System.out.println("Result of Division : " + result);

    }catch (ArithmeticException e) {
	     System.out.println("Err: Divided by Zero");

    }catch (ArrayIndexOutOfBoundsException e) {
	     System.out.println("Err: Array Out of Bound");
    }

  }
}

Output :

Err: Array Out of Bound

In the above example we have two lines that might throw an exception i.e

arr[5] = 5;

above statement can cause array index out of bound exception and

result = num1 / num2;

this can cause arithmetic exception. To Handle these two different types of exception we have included two catch blocks for single try block.

}catch (ArithmeticException e) {
	 System.out.println("Err: Divided by Zero");

}catch (ArrayIndexOutOfBoundsException e) {
	 System.out.println("Err: Array Out of Bound");
}

Now Inside the try block when exception is thrown then type of the exception thrown is compared with the type of exception of each catch block.

If type of exception thrown is matched with the type of exception from catch then it will execute corresponding catch block.

Notes :

  1. At a time only single catch block can be executed. After the execution of catch block control goes to the statement next to the try block.
  2. At a time Only single exception can be handled.
  3. All the exceptions or catch blocks must be arranged in order. [Refer the Exception Hierarchy]

Catch Block must be arranged from Most Specific to Most General :

If we wrote catch block like this -

}catch (Exception e) {
	 System.out.println("Err: Exception Occurred");

}catch (ArrayIndexOutOfBoundsException e) {
	 System.out.println("Err: Array Out of Bound");
}
  1. All the exceptions will be catched in the First Catch block because Exception is superclass of all the exceptions.
  2. In the above program ArrayIndexOutOfBoundsException is an subclass of Exception Class.

Writing above code will throw following error message after compiling it -

Unreachable catch block for ArrayIndexOutOfBoundsException.It is already handled by the catch block for Exception

The post Multiple Catch Blocks : Exception Handling in Java appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/multiple-catch-blocks-exception-handling-in-java/feed/ 0
Try-Catch Block : Exception Handling in Java Programming http://www.c4learn.com/javaprogramming/try-catch-block-exception-handling-in-java-programming/?utm_source=rss&utm_medium=rss&utm_campaign=try-catch-block-exception-handling-in-java-programming http://www.c4learn.com/javaprogramming/try-catch-block-exception-handling-in-java-programming/#comments Mon, 22 Apr 2013 11:59:39 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7962 We have already learnt about the exception handling basics and different types of exception handling in java programming. Try Catch Block : We need to put code inside try block that might throw an exception. Try block must be within a method of a java class. try { //Statement 1; //Statement 2; //Statement 3; }catch(Exception(...)

The post Try-Catch Block : Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
We have already learnt about the exception handling basics and different types of exception handling in java programming.

Try Catch Block :

We need to put code inside try block that might throw an exception. Try block must be within a method of a java class.

try { 
      //Statement 1;
      //Statement 2;
      //Statement 3;
    }catch(Exception e) {
      //Exception Handling Code
    }

above is the syntax of try catch block in java. If an exception occurred during the execution of Statement 1..3 then it will call exception handling code.

Tips for Try-Catch Block :

  1. The code within try block may or may not raise an exception. If Try block does not throw any exception then catch block gets executed.
  2. The catch block contains an exception handler and some statements used to overcome that exception
  3. Each and every Try Block must have catch or finally statement associated with it.
Try Block Present Catch Block Present Finally Block Present Legal Statement
Present Present - Legal/Complete Try Block
Present - Present Legal/Complete Try Block
Present - - Illegal/Incomplete Try Block

Explanation with Example :

public class ExceptionExample {
    public static void main(String[] args) {
       int number1 = 50;
       int number2 = 0;
       int result;
       try { 
   	    result = number1 / number2;
	    System.out.println("Result of Division : " + ans);
	} catch(ArithmeticException e) {
	    System.out.println("Divide by Zero Error");
	}   
   }
}

Consider the above example – We know that division of any number with zero is not possible.If we attempt to divide any number by zero in java then it may cause an error.

result = number1 / number2;

above statement may cause an exception so we need to put that code inside try block. Whenever an exception occures the catch block gets executed.

} catch(ArithmeticException e) {
	    System.out.println("Divide by Zero Error");
	}

Inside catch we have simply displayed an error message i.e “Divide by Zero Error”.

Exception thrown and Type of Exception Object :

Exception thrown by try block is of type Arithmetic Exception so it can be catched inside the catch block because we have provided the handler of same type.

try { 
       result = number1 / number2;
       System.out.println("Result of Division : " + ans);
}catch(FileNotFoundException e) {
      System.out.println("Divide by Zero Error");
}

If we execute the above code instead then thrown exception is of type Arithmetic Exception and Exception Type provided into Catch block is of type FileNotFoundException then exception may not be catched. Thus above code can cause compile time error.

try { 
       result = number1 / number2;
       System.out.println("Result of Division : " + ans);
}catch(Exception e) {
      System.out.println("Divide by Zero Error");
}

In the above code we can catch all types of exception because Exception is superclass of all the exceptions. [Refer the Exception Hierarchy]

The post Try-Catch Block : Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/try-catch-block-exception-handling-in-java-programming/feed/ 0
Types of Exception and Exception Hierarchy : Java Programming http://www.c4learn.com/javaprogramming/types-of-exception-and-exception-hierarchy-java-programming/?utm_source=rss&utm_medium=rss&utm_campaign=types-of-exception-and-exception-hierarchy-java-programming http://www.c4learn.com/javaprogramming/types-of-exception-and-exception-hierarchy-java-programming/#comments Sun, 21 Apr 2013 10:32:55 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7929 In the previous tutorial we have learnt about the basics of java exceptions. In this tutorial we are looking one step forward i.e Different Types of Exception and Exception Hierarchy. Types of Exceptions in Java : In Java, there are multiple situations that can cause exception. These situations are divided into 4 different types -(...)

The post Types of Exception and Exception Hierarchy : Java Programming appeared first on Learn Java Programming.

]]>
In the previous tutorial we have learnt about the basics of java exceptions. In this tutorial we are looking one step forward i.e Different Types of Exception and Exception Hierarchy.

Types of Exceptions in Java :

Java Exceptions are divided into 3 types – Checked Exceptions,Unchecked Exceptions and Errors.
In Java, there are multiple situations that can cause exception. These situations are divided into 4 different types -
Situation Cause of Exception
Code Error Exceptions occurred due to wrong or invalid data. If user try to access the array element greater than size or something divided by zero error then these exceptions are called as code errors or data errors.
Standard Method Exception Exceptions may be thrown if we try to access the standard methods with invalid input parameter.
Own Exception User may generate his/her own exceptions depending on situation and type of code.
Java Errors Errors occurred due to JVM
below are the different types of Exception in Java -

A. Checked exceptions :

  1. A checked exception is an exception which is error or a problem occurred because of code written by programmer
  2. Checked Exception cannot be neglected by the programmer.
  3. Suppose we are opening the file and file is not present then exception occurred during the compile time can be considered as checked exception.
  4. These exceptions cannot be ignored at the time of compilation.
  5. Class that extend throwable class except RuntimeException and Error is considered as Checked exception.

B. Runtime exceptions:

  1. Classes that extent RuntimeException class is called as Runtime Exception.
  2. Runtime exceptions are ignored at the time of compliation.

C. Errors :

  1. These are not exceptions but the problems that are beyond the control of the user or the programmer.
  2. For example, Stack overflow, Virtual Machine Memory,AssertionError

Exception Hierarchy :

Exception Hierarchy  Java Programming

The post Types of Exception and Exception Hierarchy : Java Programming appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/types-of-exception-and-exception-hierarchy-java-programming/feed/ 0
Exception Handling in Java Programming http://www.c4learn.com/javaprogramming/exception-handling-in-java-programming/?utm_source=rss&utm_medium=rss&utm_campaign=exception-handling-in-java-programming http://www.c4learn.com/javaprogramming/exception-handling-in-java-programming/#comments Sun, 21 Apr 2013 02:58:23 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7919 Exception Handling in Java Programming : An exception is an event. Exception occurs during the execution of a program when normal flow of the program is Interrupted or disturbed. Exception Handling is machanism to handle the exceptions. How Exception Handling Works in Java ? When any error occures in a method then new object (i.e(...)

The post Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
Exception Handling in Java Programming :
  1. An exception is an event.
  2. Exception occurs during the execution of a program when normal flow of the program is Interrupted or disturbed.
  3. Exception Handling is machanism to handle the exceptions.

How Exception Handling Works in Java ?

  1. When any error occures in a method then new object (i.e Exception Object) is created by a method
  2. Exception Object contain information about error such as type of error and state of the program.
  3. Newly created exception object is passed to the Runtime System.
  4. Runtime system will handle the exception to keep system stable

Advantages of Exception Handling :

In the previous programming languages, whenever any illegal condition is executed then program flow gets disturbed. In java programming exception handling ensures that program should run smoother. Consider the following example -

public class ExceptionExample {
    public static void main(String[] args) {
       int num1 = 50;
       int num2 = 0;
       int ans;

       ans = num1 / num2;
       System.out.println("Result of Division : " + ans);
   }
}

In this example, we know that any number divided by 0 will cause program to go into unexpected situation. If program contain such unexpected statements then its better to handle these unexpected results. Below is the unexpected error output -

Exception in thread "main" java.lang.ArithmeticException: / by zero
      at DivideByZeroNoExceptionHandling.main(
           DivideByZeroNoExceptionHandling.java:7)

Now we have done slight modification in the program by providing exception handling code in the program -

public class ExceptionExample {
    public static void main(String[] args) {
       int num1 = 50;
       int num2 = 0;
       int ans;
       try { 
   	    ans = num1 / num2;
	    System.out.println("Result of Division : " + ans);
	} catch(ArithmeticException e) {
	    System.out.println("Divide by Zero Error");
	}   
   }
}

so the output of the above code will be -

Divide by Zero Error

The post Exception Handling in Java Programming appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/exception-handling-in-java-programming/feed/ 0
Java Concatenate Strings : [String Operations] http://www.c4learn.com/javaprogramming/java-concatenate-strings-string-operations/?utm_source=rss&utm_medium=rss&utm_campaign=java-concatenate-strings-string-operations http://www.c4learn.com/javaprogramming/java-concatenate-strings-string-operations/#comments Sat, 20 Apr 2013 07:42:36 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7928 In this chapter we will be learning Concatenating two strings in java programming. Concatenating two strings means combining two objects in java. Joining two Strings [Concatenate Strings] in Java : Consider the following example - public class ConcatenateString { public static void main(String[] args) { String Str1 = "I love"; String Str2 = "my country";(...)

The post Java Concatenate Strings : [String Operations] appeared first on Learn Java Programming.

]]>
In this chapter we will be learning Concatenating two strings in java programming. Concatenating two strings means combining two objects in java.

Joining two Strings [Concatenate Strings] in Java :

Consider the following example -

public class ConcatenateString {
    public static void main(String[] args) {
       String Str1 = "I love";
       String Str2 = "my country";
       String Str3 = "India";

       String myString; 
       myString = Str1 + Str2 + Str3;
       System.out.println("Complete Statement : " + myString);

       myString = Str3 + 10 + 10;
       System.out.println("Complete Statement : " + myString);

       myString = 10 + 10 + Str3;
       System.out.println("Complete Statement : " + myString);
   }
}

Output :

Complete Statement : I love my country India
Complete Statement : India1010
Complete Statement : 20India

Explanation of the Program :

In Java Programming when two strings will be combined together then it will create another object of string. Below are some thumb rules while adding or combining two strings.
Operand 1 Operand 2 Result of Concatenation
Integer String String
String String String
Integer Integer Integer


  1. ‘+’ operator has associtivity from left to right.
  2. Each time + operator will check the type of operands and then decide which operation to perform.
  3. If any of the operand is of type String then another type will converted to String using respective wrapper classes.

First Concatenation :

myString = Str1 + Str2 + Str3;
         = "I love " + "my country " + "India"
         = "I love my country " + "India"
         = "I love my country India"

Second Concatenation :

myString = Str3 + 10 + 10;
         = "India" + 10 + 10
         = "India10" + 10
         = "India1010"

Third Concatenation :

myString = 10 + 10 + Str3;
         = 10 + 10 + "India"
         = 20 + "India"
         = "20India"

The post Java Concatenate Strings : [String Operations] appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/java-concatenate-strings-string-operations/feed/ 0
Immutable String Objects : String Handling Java Tutorials http://www.c4learn.com/javaprogramming/immutable-string-objects-string-handling-java-tutorials/?utm_source=rss&utm_medium=rss&utm_campaign=immutable-string-objects-string-handling-java-tutorials http://www.c4learn.com/javaprogramming/immutable-string-objects-string-handling-java-tutorials/#comments Fri, 19 Apr 2013 09:59:53 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7926 Consider the following example - class ImmutableString { public static void main(String[] args) { String myString = new String("I am living in India"); System.out.println( myString ); myString.replaceAll( "India" , "USA" ); System.out.println( myString ); } } Output of Program : I am living in India I am living in India Explanation : Immutable String Objects(...)

The post Immutable String Objects : String Handling Java Tutorials appeared first on Learn Java Programming.

]]>

What is Immutable Objects ?

When you have a reference to an instance of an object, the contents of that instance cannot be altered

Consider the following example -

class ImmutableString {
public static void main(String[] args) {

	String myString = new String("I am living in India");
	System.out.println( myString );

	myString.replaceAll( "India" , "USA" );
	System.out.println( myString );

	}
}

Output of Program :

I am living in India
I am living in India

Explanation : Immutable String Objects

In the above example, we can see that

myString.replaceAll( "India" , "USA" );

it will create another string i.e -

I am living in USA

Immutable String Concept - Before Reference

though object is created for “I am living in USA” string but reference variable “myString” is still not referring to new string. We need to specify the reference explicitly using following assignment -

myString = myString.replaceAll( "India" , "USA" );

Immutable String Concept - After Referencing

class ImmutableString {
public static void main(String[] args) {

    String myString = new String("I am living in India");
    System.out.println( myString );

    myString = myString.replaceAll( "India" , "USA" );
    System.out.println( myString );

    }
}

and output will be like this -

I am living in India
I am living in USA

The post Immutable String Objects : String Handling Java Tutorials appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/immutable-string-objects-string-handling-java-tutorials/feed/ 0
Creating String Objects in Java Programming http://www.c4learn.com/javaprogramming/creating-string-objects-in-java-programming/?utm_source=rss&utm_medium=rss&utm_campaign=creating-string-objects-in-java-programming http://www.c4learn.com/javaprogramming/creating-string-objects-in-java-programming/#comments Thu, 18 Apr 2013 03:15:16 +0000 Pritesh http://www.c4learn.com/javaprogramming/?p=7922 In the last Chapter we have seen String literal in java programming. In this chapter we are looking one step forward to create String Object in Java Programming. In Java we can create String in two ways – One by using String Literals and another using new operator. Way 1 : Creating String Objects using(...)

The post Creating String Objects in Java Programming appeared first on Learn Java Programming.

]]>
In the last Chapter we have seen String literal in java programming. In this chapter we are looking one step forward to create String Object in Java Programming.

In Java we can create String in two ways – One by using String Literals and another using new operator.

Way 1 : Creating String Objects using Literals

Consider the following Code Statement -

class FirstProgram {
public static void main(String[] args) {

   String myName = "PRASHAN";
   System.out.println("Hello " + myName);

   myName = "PRABHU";
   System.out.println("Hello " + myName);
   }
}

Explanation :

String myName = "PRASHAN";

The above Statement will be pictorially represented below -
String Literal Assignment
Now when we assign another string literal to String Object then earlier string will be discarded.

myName = "PRABHU";

Assigning New String Literals to Object
Actual String can be stored anywhere in the heap but String Object – “myName” will locate the position of the String – “PRABHU” and stores the reference to that actual string.

Way 2 : Using new Operator

String name = new String("AKASH");

Consider the above code line –
Entity Object/Variable Memory Location
AKASH Object String Constant Pool
new String("AKASH") Object Non Heap Memory
myName Reference Variable -
*Reference Variable is Pointing to a String Object – new String(“AKASH”)

The post Creating String Objects in Java Programming appeared first on Learn Java Programming.

]]>
http://www.c4learn.com/javaprogramming/creating-string-objects-in-java-programming/feed/ 0