This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How does Stack and Heap work for Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How does Stack and Heap work for Strings" Watch "How does Stack and Heap work for Strings" New topic
Author

How does Stack and Heap work for Strings

lahiru dharmasena
Greenhorn

Joined: Sep 17, 2008
Posts: 6
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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
lahiru dharmasena
Greenhorn

Joined: Sep 17, 2008
Posts: 6
Thanks Ilja Preuss.
 
rocket mass heater kickstarter
 
subject: How does Stack and Heap work for Strings