go to previous page   go to home page   go to next page hear noise highlighting

Answer:

  1. Are the sheets of paper separate objects?
    • Yes; each object has its own identity.
  2. Is the first sheet == the second sheet?
    • No; they are separate objects.
  3. Is the poem on each sheet the same as on the other?
    • Yes; the poem on the second sheet is a copy of the poem on the first.
  4. Is the first sheet equals() to the second sheet?
    • Yes; the poems on both sheets are equivalent.

String Literals

Strings are common in programs, so Java optimizes their use. Usually if you need a string in your program you create it as follows. Notice that new is not used:

String str = "String Literal" ;

This creates a string literal that contains the characters "String Literal". A string literal is an object of class String. The compiler keeps track of the literals in your program and will reuse the same object when it can. (The compiler will not try to reuse other types of objects. String literals are special.)

For example, say that a program contained the following statements:

String str1, str2;

str1 = "String Literal" ;
str2 = "String Literal" ;

Only one object is created, containing the characters "String Literal". This is safe, because strings are immutable, so the object str1 refers to will not change, and the object str2 refers to will not change, so if the data is always the same, only one object is needed to contain it. There is no need for two string objects whose content is equivalent.

Here is different situation:

String strA, strB;

strA = new String("My String") ;
strB = new String("My String") ;

Now two objects are created, containing equivalent data. The compiler does not reuse the first object.

It is assumed that because you explicitly used two new commands that you really want two separate objects.


QUESTION 23:

How many objects are created by the following code:

String msg1, msg2, msg3;

msg1 = "Look Out!" ;

msg2 = "Look Out!" ;

msg3 = "Look Out!" ;

go to previous page   go to home page   go to next page