2

I have been going through String class in Java in depth. String in Java is backed by character array.

To create strings that have initial values, we call the constructor as:

     /* String creation */ 
        String s = new String("example");

The constructor code in the String class is:

        public String(String original) {
            this.value = original.value;
        }

Can some one please explain me the logic of "original.value". From the source code, I understand it returns character array. But how java generates it?

Prashanth
  • 95
  • 1
  • 8
  • 1
    "we call the constructor as:" No. `String s = "example";` is sufficient. – Andy Turner Sep 19 '17 at 18:31
  • `value` is [private](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) in String class. You can't access it. – Juan Carlos Mendoza Sep 19 '17 at 18:33
  • [`String.value`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/String.java#114) is `private`. See the duplicate to understand what that means. – Andy Turner Sep 19 '17 at 18:34
  • `"is giving compile time error"` - And surely that error is telling you what the problem is, no? – David Sep 19 '17 at 18:35
  • yeah. I know the value is private and can not access outside string class. The question is what is the output of the statement "original.value". Does it return character array? If yes, how? – Prashanth Sep 19 '17 at 18:46
  • @Prashanth its accessing the field `value` of the String original directly. `value` is a character array, this works like accessing any other variable. – puhlen Sep 19 '17 at 18:56

1 Answers1

5

The "foo" syntax has already constructed a String instance, it's syntactic sugar so that you don't have to write:

String foo = new String(new char[]{'f', 'o', 'o'});

So by the time you call new String("foo") you've already constructed a string once, and are now creating a copy of the first string - not "creat[ing] strings that have initial values".

Effective Java: Item 5 discusses this in more detail, and discourages ever using the new String(String) constructor.

dimo414
  • 47,227
  • 18
  • 148
  • 244