| Author |
Please Help: bizarre output
|
Dibbo Khan
Ranch Hand
Joined: Dec 19, 2004
Posts: 147
|
|
Hello everyone, I have no idea why the output is 343 instead of 344, this is question 65 of the epractice exams for J2SE 5.0, could someone please help explain why this is the case to me, I think all the autoboxing syntax is correct??? Thank you to everyone for your anticipated help. public class X { static long story; public static void main(String[] args) { if(story == 0) { Long tale = 343L; story = go(tale); } System.out.print(story); } static long go(Long t) { return t++; } }
|
MCPD (Enterprise Application Developer, Windows Developer, Web Developer - .NET 2.0), MCTS (Windows Apps, Web Apps and Disbributed Applications - .NET 2.0), MCITP (Database Developer & Business Intelligence Developer - SQL Server 2005), MCAD, MSCD.net, SCJP 5, SCWCD 1.4, SCBCD, SCMAD, SCDJWS, SCJA
|
 |
nagaraj raja
Ranch Hand
Joined: Aug 06, 2005
Posts: 36
|
|
hai, here u used post increment ie return i++ means first it will perform operation then i will print the increment value here if u use instead of i++ use ++i then it will increment by 1 and print ok
|
 |
K Krishna Kishore
Greenhorn
Joined: Aug 09, 2005
Posts: 12
|
|
Line 8 calls go method supplying the value of 343 to variable "t". Line 15 returns the value of t to the main method. Now since the post increment operator is used it first returns the value and the incremets the value of t. So variable story in the main method gets the value of 343 and then varibale t becomes 344 but dies soon after due to its scope. If you want the output to be 344 you need to use the pre increment opetator (++t) which would first increment the value of the variable "t" to 344 and then return it. Hope this helps.
|
 |
Dibbo Khan
Ranch Hand
Joined: Dec 19, 2004
Posts: 147
|
|
|
Thank you both very much for your help
|
 |
Mahesh Kumar Kumar
Greenhorn
Joined: Jul 14, 2005
Posts: 8
|
|
|
It Doesn't Compile
|
 |
Dibbo Khan
Ranch Hand
Joined: Dec 19, 2004
Posts: 147
|
|
It does compile, just make sure your class name and file name are the same. public class X { static long story; public static void main(String[] args) { if(story == 0) { Long tale = 343L; story = go(tale); } System.out.print(story); } static long go(Long t) { return t++; } } This was compiled using Netbeans 4.1
|
 |
Kayalvizhi Umashankar
Greenhorn
Joined: Aug 04, 2005
Posts: 25
|
|
It will compile if "Long" is changed to "long" Kayal
|
 |
Dharmesh Gangani
Ranch Hand
Joined: Feb 20, 2004
Posts: 30
|
|
|
Yes, It will compile only if "Long" is changed to "long".
|
-=-=-=-=-=-=-=-=-=-<br />Thanks & Regards,<br />Dharmesh G.
|
 |
Dibbo Khan
Ranch Hand
Joined: Dec 19, 2004
Posts: 147
|
|
This is for SCJP 5.0, Long is valid because of autoboxing, I used Netbeans 4.1 which uses JDK 5
|
 |
 |
|
|
subject: Please Help: bizarre output
|
|
|