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;

Dani AI

Generated

Short answer and context: was on the right track for — the ?: operator is an expression that produces a value, not a control statement. You cannot put a return keyword inside the operator operands; the operator must yield a value that the surrounding statement (for example an assignment or a return) uses.

Practical uses (examples):

int chosen = condition ? computeFirst() : computeSecond();

System.out.println(condition ? "yes" : "no");

Notes and common pitfalls:

  • Types must be compatible. If one branch is an integer and the other is a floating-point literal, the result will be promoted to a floating type at compile time. With reference types the compiler picks a common type according to the language rules. See the JLS for precise rules.
  • Only one branch is evaluated at runtime (the branch chosen by the condition), so side effects occur only in the executed branch.
  • The operator is right-associative, so chains without parentheses can be hard to read. a ? b : c ? d : e is parsed as a ? b : (c ? d : e).
  • Favor readability: use the ternary for short, simple choices. If branches contain multiple statements or complex logic, a plain if/else is clearer.

References: the Java Language Specification section on the conditional operator and the Oracle tutorial provide the authoritative behavior and type rules: Java Language Specification — Conditional Operator and The Conditional Operator (Oracle Java Tutorial).

Recommended Answers

All 2 Replies

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;

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.