Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

command line arguments

 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I found this Q on the mock test at javaprepare:


<blockquote>
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);
}
}
<blockquote>


I think it should print 2 but it prints 1. Can anyone explain why?
Thanks,
Shashi
 
Kourosh Keshavarzi
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What arguments are you passing when you run the program?
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops!! I'm really sorry! I ran the prog as follows:
C:\java java test 2
Thanks,
Shashi
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mistake again! I mean
c:\java>java test 2
Thanks,
Shashi
 
Matt DeLacey
Ranch Hand
Posts: 318
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, so there is one command line argument (the number 2). Therefore, the first if statement will fail because the length is not greater than 1, it IS 1. The second will succeed and so it will print i - 1. Since i=2, it will print 1.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
args.length = 1
Integer intObj=Integer.valueOf(args[args.length-1]); = the value at args[0] = what you passed in which is 2.
int i = intObj.intValue(); so i = 2;
if(args.length > 1)
System.out.println(i); //no- 1 is not > 1
if(args.length > 0)
System.out.println(i - 1); // yes 1 is > 0 so print out i - 1
(which is 2-1=1)
else
System.out.println(i - 2);
} //endif
So 1 is correct.
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, all!
I was under the impression that test and 2 were both the arguments!! 2 is the only argument and test is the class file. My bad.
Thanks once again.
Shashi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic