Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javatutorials End of Year Puzzle

Related Tutorials


 
 

Share on Google+Share on Google+

End of Year Puzzle

Advertisement
This page discusses - End of Year Puzzle

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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: End of Year Puzzle  

Post your Comment


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