How to return different values based on flags (with.Java)
In this article, we learned about How to return different values based on flags (with.Java)
Weโre going to learn by solving a coding test problem, doing a retrospective on the problem we solved, and looking at other ways to solve it. Letโs start with the problem.
Problem
Given two integers a, b and a boolean variable flag as parameters, write a solution function that returns a + b if flag is true or a - b if flag is false.
Example input and output
a: -4 b: 7 flag: true result: 3
In other words, since flag is true, it returns a + b = (-4) + 7 = 3.
My solution to the problem
class Solution {
public int solution(int a, int b, boolean flag) {
int answer = (flag) ? a+b : a-b;
return answer;
}
}
Solution
Utilize the ternary operator to perform the a+b, a-b operations based on the boolean value of flag.