Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the difference between String name="Java" and String name=new String("Java")

 
dev pandya
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference between String name="Java" and String name=new String("Java")
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dev,

Welcome to JavaRanch.


Here,'Java' is a string literal.and store in ???(Don't remember,i guess heap) JVM.

Here, You are creating a string object.

Now,If you write,

Here, compiler won't create one more string literal as it's already in heap(?) JVM.

Now, consider this,


Here, Two different objects are going to be created.
[ June 11, 2008: Message edited by: Vishal Pandya ]
 
aruna sydu
Ranch Hand
Posts: 98
MyEclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To save lots of object creations and heap space (memory where objecs are stored)A concept called String pool in java is used.
Because String once created are immutable,when ever a String is created in java it is placed in the String pool [you can assume as HashMap].

Example:
String s="java";
This object s is placed in String pool.

String another = "java";//allocated from string pool

The next time you refer to the same String you created earlier , It is first looked up in String pool and the same string is used instead of creating a new String object.

but

when you say

String another = new String("java");
A new Object is created and placed in String pool with out prior checking
whether that string literal already present in String pool.


Hope my explanation helps

Aruna




Originally posted by dev pandya:
what is the difference between String name="Java" and String name=new String("Java")
 
Padmarag Lokhande
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The correct term is : in Java the Strings are 'Interned'.
i.e., if a string exists in the pool, a reference to that string will be returned when you use name="java" and when you use new String("java"), then a new string is created and returned regardless of its prior existence.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic