954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Conditional Expression in JAVA

I am a new programmer in Java and now I am facing the following problem. If u please answer my queries it will be very much helpful to me.


Can I use the following code :

(a == 2) ? return 4 : return 5;

instead of the following code :

if(a == 2)
return 4;
else
return 5;

niamul
Newbie Poster
12 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

no you can't, at least not in that form.
The conditional expression returns a value, it cannot terminate a method.

Instead you would use

return (a==2)?4:5;
jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Thank u .
I have used your suggested from and got the required result.

niamul
Newbie Poster
12 posts since Dec 2004
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You