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.
"There is a will,there is a way!"<br />SCJP1.4
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
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.
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
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
Joined: Aug 03, 2002
Posts: 7729
posted
0
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
Joined: Aug 05, 2003
Posts: 73
posted
0
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!
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.