| Author |
what is the difference between String name="Java" and String name=new String("Java")
|
dev pandya
Greenhorn
Joined: Jun 10, 2008
Posts: 14
|
|
|
what is the difference between String name="Java" and String name=new String("Java")
|
 |
Vikas Kapoor
Ranch Hand
Joined: Aug 16, 2007
Posts: 1374
|
|
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
Joined: Jan 21, 2008
Posts: 98
|
|
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")
|
Attitude Determines Altitude
SCJP4/SCWCD4/SCDJWS5/Preparing SCEA Part I
|
 |
Padmarag Lokhande
Ranch Hand
Joined: May 29, 2008
Posts: 87
|
|
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.
|
- Padmarag Lokhande
SCJP5 - http://blog.padmarag.com
|
 |
 |
|
|
subject: what is the difference between String name="Java" and String name=new String("Java")
|
|
|