• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question 3 on javaprepare

 
may leung
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
What gets printed when the following code is compiled and run with the following command -
java test 2
Select the one correct answer.

public class test {
public static void main(String args[]) {
Integer intObj=Integer.valueOf(args[args.length-1]);
int i = intObj.intValue();
if(args.length > 1)
System.out.println(i);
if(args.length > 0)
System.out.println(i - 1);
else
System.out.println(i - 2);
}
}

The ans is 1. Can anyone explain to me why?
Thanks!!!
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Step through the code.
1. You are getting the value of the first argument passed on the command line and passing it into an Integer object.
2. You take that value and return it as an int with intObj.intValue(). So i = 2.
3. You check to see if the length of args is greater than 1, which it is not since there is only one value ("2") passed in so length = 1.
4. You check to see if the length of args is greater than 0 which it is since a value was passed in, so you take i-1 which is 1
Bill
 
may leung
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh!!
I'm clear now
Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic