Ishmael
Ishmael

Reputation: 235

What does the new Operator and String do in this program?

I am beginner to Java, and I am reading up on Arrays from the tutorial at Oracle.

My question involves this code:

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

Specifically,

 System.out.println(new String(copyTo));

What does new String(copyTo) exactly do, or rather why use new and String? What are they doing together? (I understand that they print out "caffein" but only in a very general sense.

Upvotes: 2

Views: 934

Answers (4)

jhc
jhc

Reputation: 1769

The function println only accepts the type String. What you have is a char array.

The new keyword indicates that String is a constructor of the class String (as in construction of a new String object).

In the Android Developers site you have a list of all the constructors possible: http://developer.android.com/reference/java/lang/String.html

Specifically, the one you are using is:

String(char[] data)

Upvotes: 0

Fritz
Fritz

Reputation: 10055

It creates a new String object containing the text defined by the char array you pass as a parameter. It's just another of the constructors defined in the String class, take a look at it:

public String(char value[]) {
    this.offset = 0;
    this.count = value.length;
    this.value = StringValue.from(value); //returns a copy of the char array
                                          //by using Array.copyOf
}

Aside from looking at the JavaDoc, diging into String's code can help you to comprehend how does it work. this.value is the internal array used to allocate the chars that conform the String.

Upvotes: 0

PermGenError
PermGenError

Reputation: 46438

What does new String(copyTo) exactly do,

It creates a new String object. String class has an Constructor which accepts an char array, which converts the char Array into string literal.

new String(char[] arr) Source

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

Upvotes: 2

Eng.Fouad
Eng.Fouad

Reputation: 117685

The JavaDoc is your friend:

public String(char[] value)

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.

Parameters:

value - The initial value of the string

Upvotes: 6

Related Questions