Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is string an object or literal ?

 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi..

can any body tell me what is String an object or literal ?

i mean what is the difference when we declare string as

String a = new String("abc text");
String b= "xyz text";

???


and are call to functions in java are "call by refernce" or "call by value"

i mean if i pass say

someobject.someMethod("abc_text");
someobject.someMethod(a); // a declared above
someobject.someMethod(b); // b declared above

and here

someMethod(String s)
{
s="change in text"; // is that will change the original value ?
}


is that will change the original value ?

thanx and regards
amit


pls give answer in details so all dought of will be clear ....
 
Mike DeStefano
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String is an Object
 
Mike DeStefano
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether you declare it formally by saying

new String("blah blah blah")

or by saying

x = "blah blah blah"

This is the same thing. Java did this for convenience.

String is referenced by address and is not like and int or double (that is, not a primitive)... char is a primitive. String is simply an array of chars for the most part.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a difference between String s = "abc" and String s = new String("abc"). Please see the following JavaRanch article regarding String literals...

http://www.javaranch.com/journal/200409/Journal200409.jsp#a1
[ December 29, 2004: Message edited by: marc weber ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java, when an object reference is passed as an argument, what's really being passed is a copy of the reference. This copy becomes local to the method (so in that sense, it's a value); but it still points to the same object (so in that sense, it's a reference).


But remember, Strings are immutable. (See link above.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic