STEPHEN bui
STEPHEN bui

Reputation: 628

Short form of if/else in Java

How can i write this if/else expression in short form using ternary operator ?

int value1 = 5,value2 = 0;
if (value2 == 0) {
} else {
   value1 = value1 / value2;
} 

Upvotes: 0

Views: 5581

Answers (4)

PEHLAJ
PEHLAJ

Reputation: 10126

Use ternary operator

value1 = value2 == 0 ? value2 : value1 / value2;

Upvotes: 0

Akshay Kumar S
Akshay Kumar S

Reputation: 333

ternary operator syntax is

condition?true statement:false satatement;

for your code use

value2 == 0? : value1 / value2;

Upvotes: 0

holi-java
holi-java

Reputation: 30676

the simplest way is just invert condition and using if statement only:

if(value2 != 0) {
  value1 = value1 / value2;
} 

Upvotes: 3

Darshan Mehta
Darshan Mehta

Reputation: 30809

You don't need to take any action on value if value2 is 0, so you can write a ternary operator that assigns value1 to value1 if value2 is 0, and value1 / value2 otherwise, e.g.:

value1 = value2 != 0 ? value1 / value2 : value1;

Upvotes: 3

Related Questions