File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a strange code

 
rainbow
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at below question:
Examine the following code which includes an inner class:

public final class Test4 implements A {
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();
}
}

What is the result:
A. Prints out "Sample"
B. Program produces no output but terminates correctly.
C. Program does not terminate.
D. The program will not compile
Select the most appropriate answer.
Please pay attention to the bold sentence,it runs strangely.

 
deekasha gunwant
Ranch Hand
Posts: 396
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi rainbow,
Assuming that interface A is available. The answer will be 'B' i.e. the program terminates correctly and produces no output. the culprit here is the ; in following line
if (Test4.this.flag) ;
if u remove the ; then u'll see the o/p sample printed on your console.
regards
deekasha
 
rainbow
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi:
The code shouldn't include "implements A",it's a mistake.Ignore this,the correct answer should be A.if remove ";",the result will be B.It is truth.If you don't beleive it,you can try to run it.
 
Rong Chen
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is kind of a joke.
i don't think it will appear in Sun's exam.
but good to remember, anyway...
 
Geek
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello rainbow,
Didn't get what was strange about the code. When you had ";" after the if statement the conditional statement ended with the ";", so sample() was executed as it was the next statement.
On the other hand when u removed the ";", sample() was in the conditional statement and becuase the value of flag is false, the execution of sample() is skipped and hence you get nothing printed. Got that ??
Geek
ps: i hope u understood my long and convoluted sentences
[This message has been edited by Geek (edited September 14, 2000).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic