Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the code can't be compiled

 
nick magic
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given:
1. public class test {
2. public static void main(string[]args){
3. string foo = args [1];
4. string foo = args [2];
5. string foo = args [3];
6. }
7. }
And command line invocation:
C:\>java Test red green blue
What is the result?
A. Baz has the value of ��
B. Baz has the value of null
C. Baz has the value of �red�
D. Baz has the value of �blue�
E. Bax has the value of �green�
F. The code does not compile.
G. The program throws an exception.

The answer is G. But i test the code in the java1.5.0 run environment, when i compile the code, it reports the error: in the L4,L5, the foo have been defined
So i wonder wether i could choose F instead of G? thanks
 
Alex Khvatov
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code would throw a runtime exception because the program refers to an unexisting array index. The command line arguments are represented by a zero based array, so if you're passing three elements to the program, the last one would be at the index two not three.
Alex
 
Alex Khvatov
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another correction. Here you're defining a 'string' which is not a correct name for a String class. The code would not comple because of 'string' and not 'String'.
Alex
 
Alex Khvatov
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... And you can't have multiple definitions of the same local variable.
Alex
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that's the point of the OP's question. The program won't compile so it can't throw an exception.
 
Thai Son Cung
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think F is the correct answer. The program will be conpilation fail!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic