Describe the effect of the following Java statements String

Describe the effect of the following Java statements

String sentence;                                   //line 1

sentence = \"Java Programming\";      //line 2

sentence = new String(\"Java Programming\");    //line 3

Solution

Answer:

String sentence; String object declaration. By default the value of String object is null.

sentence = \"Java Programming\"; We are assing a value to String object with out new operation. So this String object is nothing but String leteral. it will store in String literal pool memory. If you assing a same value to another string literal then same memory location reference wii be gien to new string literal. So when you apply \"==\" operator on two string literals it will return true.

String a = \"abc\";

String b = \"abc\";

if( a == b) it will return true

sentence = new String(\"Java Programming\"); We are assing a value to String object with new operation. It is nothing but a String object that will store in Heap memory. When we assing same value to another object that is created by new operation then different memory location will be provided for new object. Henc when we perform \"==\" operator on both objects it will return false

String a = \"abc\";

String b = \"abc\";

if( a == b) it will return false

if(a.equals(b)) it will return true.

\"==\" will check only equality but equals method will check equality and type.

Describe the effect of the following Java statements String sentence; //line 1 sentence = \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site