• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

Naveen's mock exam qn 3??

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What gets printed when the following code is compiled and run with the following arguments -
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);
}
}


Answers
a.test
b.test -1
c.0
d.1
e.2
Answer is 1 ,please explain how??
thanks
Ann
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class test {
public static void main(String args[]) {
Integer intObj=Integer.valueOf(args[args.length-1]); //args[1-1] will have 2 intobj's value will be 2
int i = intObj.intValue();//i=2
if(args.length > 1) //False
System.out.println(i);
if(args.length > 0) //True
System.out.println(i - 1); //2-1 ie 1 will be printed
else
System.out.println(i - 2);
}
}
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mary is right. I read the question wrong at first. When you said with the following arguments java test 2, I took that as all of those as arguments. Like you would type java test java test 2 on the command line. In that case you would get
2
1
as your answer, as the first condition args.length > 1 is true. But you would still get 1 as your answer because you are taking the value of the last argument which is 2, turning into a primative, int, and then subtracting 1 from it.
I think the question should have been worded:
What gets printed when the following code is compiled and run with the following statement?
 
Ann , Varghese
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you mary & bill.
reply
    Bookmark Topic Watch Topic
  • New Topic