File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does Stack and Heap work for Strings

 
lahiru dharmasena
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi i'm new to java.

class Q82{
public static void main(String []arg){
String a= "A";
String b= "B";

System.out.println(("A"+"B")=="AB");
System.out.println((a+b)=="AB");
System.out.println(("A"+"B")==(a+b));
}

}

this will give out put: true, false, false.

this is understandable since Strings are objects and can not use == to compare the content.
but if you use "final" to the String a, b

class Q82{
public static void main(String []arg){
final String a= "A";
final String b= "B";

System.out.println(("A"+"B")=="AB");
System.out.println((a+b)=="AB");
System.out.println(("A"+"B")==(a+b));
}

}
the out put will be : true, true, true.

my question is how the "final" keyword effect the behavior of stack and heap

thanks in advance
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't. It effects how much optimization the compiler is able to do.

When a and b are final, the compiler recognizes that a + b is a compile time constant, calculates its value and puts the result into the byte code.

So, the difference between your two code examples is that the first executes the concatenation at runtime, whereas the second executes it at compile time.
 
lahiru dharmasena
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ilja Preuss.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic