End of Year Puzzle

This page discusses - End of Year Puzzle

Ads

Tutorials   

Puzzle in Java

Here am going to write a question as a puzzle, it is also very similar to the those questions you find in the SCJP (Sun Certified Java Programmer)  examination

public class LittleFuzzy {
	public int method(int x) {
		int val = x;
		try {
			return val;
		} finally {
			val = x + x;
		}
	}

	public static void main(String[] args) {
		LittleFuzzy littleFuzzy = new LittleFuzzy();
		System.out.println(littleFuzzy.method(10));
	}
}
1

Review the program clearly and think what would be the output.

If I change this program a little bit then is output will change or not ?

public class LittleFuzzy {
	private int val;

	public int method(int x) {
		val = x;
		try {
			return val;
		} finally {
			val = x + x;
		}
	}

	public static void main(String[] args) {
		LittleFuzzy littleFuzzy = new LittleFuzzy();
		System.out.println(littleFuzzy.method(10));
	}
}

The output will not change it will be the same. Because when you use the return key word it return the value at that time and it ignores the rest of the part of a method. Therefore the output will be 10 in both the cases.

Advertisements

Share on Google+Share on Google+

End of Year Puzzle

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: End of Year Puzzle  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads