my dog learned polymorphism
The moose likes Java in General and the fly likes String handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String handling" Watch "String handling" New topic

String handling

Lalit Kapoor

Joined: Jun 06, 2004
Posts: 20
In the code below:

String str1 = "Hello";
String str2 = "Hello";
if(str1 == str2)
System.out.println("str1 == str2 is true");

The output is:
str1 == str2 is true

Could you tell me why this is the output?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

String literals -- i.e., occurrences in your source code of double-quoted Strings -- are pooled in the JVM. For each string literal, there will be one and only one instance of a String object used to represent it. This is described in JLS 3.10.5.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: String handling
It's not a secret anymore!