File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String Query" Watch "String Query" New topic

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'?

Amit Ghorpade

Joined: Jun 06, 2007
Posts: 2851

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

|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
I agree. Here's the link:
subject: String Query
It's not a secret anymore!