Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is "empty String"?

 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all:
Puzzles come again.
Which correctly create an array of five empty Strings?
A. String a [] = new String [5];
for (int i = 0; i < 5; a[i++] = "");
B. String a [] = {"", "", "", "", ""};
C. String a [5];
D. String [5] a;
E. String [] a = new String [5];
for (int i = 0; i < 5; a[i++] = null);
Answer: a,b
Adding the following codes to output the String array:
for(i=0;i<5;i++)
{
println(a[i])
}
For option A: null
null
null
null
null
For option B: nothing happened but five empty lines.
A & B are both right answers via the same means(put "" to each item in the array). But why output about the array is different at all !?
What is "empty String" in the question on earth?
Thanks.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a string with no characters. Consider the string "a", now remove the character 'a' from the string. It's now empty: "". An empty string can be created in Java by a literal: String s = ""; or less efficiently by using the no-argument constructor: String s = new String();
Note that String s; does not create an empty string, but a reference to no string, a null reference.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi roger
it seems it might be depending upon jdk. because i ran the option A on my machine with j2sdk1.4.1_02 and i get empty strings in output as option B.
regards
maulin
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Barry
i c ur point but it seems roger is having question as he expected same output as option B in option A which is logically correct and i'm able to produce that output but he seems doesn't get that output.
regards
maulin
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I confirm that both a and b print correctly. I can only guess that the for-loop was omitted in the case of option a.
 
Roger Zhao
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,Maulin,Barry:
I try this puzzle codes on J2K1.4 environment. It runs well.
Same results come out both A & B.

Thank you both!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic