• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cannot understand the output

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

This question is from Wizlabs 1.4 . In this I am not able to understand what will be the output.Question is as follows :

What will happen when you attempt to compile/run the following code?

public class MyClass
{
public static void main(String args[])
{
int total=0;

for(int i=0,j=10;total>30;++i,--j)
{
System.out.println("i="+i+":j="+j);
total+=(i+j);
}

System.out.println("Total"+total);
}
}



A. Produce a runtime error.
B. Produce a compile time error
c. Print out "Total 0"
D. Generate the following as output:
i=0 : j=10
i=1 : j=9
i=2 : j=8
Total30
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think c is the correct answer. The pitfall is here

int total=0;
for(int i=0,j=10;total>30;++i,--j)

The condition will be false for the very first time so the loop will never get executed...
 
Aparna Misri
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh yes...you are right Ankit....
Now I got it...
Thanks a lot
 
Aparna Misri
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ankit,
If I replace "total>30" with "total<30" in the same question what will be the output.
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
answer D?
 
Let me tell you a story about a man named Jed. He made this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic