• 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
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

A question of JTest.

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello.
Give:
class Test4 {

class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}

private boolean flag = false;

public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();
}
public static void main(String args []) {
new Test4();
}
}
1) Prints out "Sample"
2) Program produces no output but terminates correctly.
3) Program does not terminate.
4) The program will not compile
I thought the answer is 2), but when I run these codes, the result is 1), why?
 
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Michael,
The trick is on the ";" after the if statement which terminates the if clause there, so the sample() got invoked regardless flag status,
if you remove the ";" after the if statement, the result would be (2).
regards

Originally posted by Michael Zhang:
Hello.
Give:
class Test4 {

class Inner {
void test() {
if (Test4.this.flag); {
sample();
}
}
}

private boolean flag = false;

public void sample() {
System.out.println("Sample");
}
public Test4() {
(new Inner()).test();
}
public static void main(String args []) {
new Test4();
}
}
1) Prints out "Sample"
2) Program produces no output but terminates correctly.
3) Program does not terminate.
4) The program will not compile
I thought the answer is 2), but when I run these codes, the result is 1), why?

 
Michael Zhang
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks chichih.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic