*
The moose likes Beginning Java and the fly likes String Query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Query" Watch "String Query" New topic
Author

String Query

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
What is the o/p for the below programs and why?

1 Program:

String abc = new String();
System.out.println(abc); ......// why the o/p?

2 Program:

String[] cba = new String[2];
for(int i =0;i<cba.length;i++){
System.out.println(cba[i]) ...//why the o/p
}

Why is the difference between these 2 o/ps'?


Thanks,
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2716
    
    6

Hi,
The reason is obvious, in the first program, you create the String object,
but in the second one, you are creating the array object not the individual string objects, you should get identical behavior if you create the array objects also.


Hope this helps


SCJP, SCWCD.
|Asking Good Questions|
Anubhav Anand
Ranch Hand

Joined: May 18, 2007
Posts: 341



This outputs a blank string. This is because of the definition of String constructor of Java which initilizes a String objects as empty character sequences. Well as the String objects are immtable so this constructor has no relevance.



In this case you are defining a String Array. Now this leads to blank String objects but, two null Array objects. Thus it results into two null String array objects. hence the output for the loop is null.

hope that helps
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String Query