Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Query

 
Phillipe Rodrigues
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Anubhav Anand
Ranch Hand
Posts: 341
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic