This article is about how and when to use the if-else ternary operator in our java program or any other programming language. My approach here is to elaborate on this to ease the new programmers to write less as the shorthand if-else is often used to replace our traditional if and else statement. The ternary operator in java is not an operator but an if-else statement that works on three operands. Let’s try to go in more depth. There are some subheadings I am adding to be more ease for you to quickly access.
2. What does it consist of?
What is it and why is it?
The ternary word means three in number, So here ternary operator means that it works on three operands. Now, what is the operator and what is an operand these terms used to confuse me many times during when I started? Let’s focus on the given image for a second.
An operator is something that is present in between two operands that decide the performance of an operation between those two operands. Now coming to why is it to be used for that let me open up the above into if-else conditions.
You see on the editor screen that the one line of the ternary operator is replaced by 6 lines total. Java is such a language where you have to write a lot and that’s the power of it that’s why it is best for beginners to learn Java, as their the first language to get started with. So after seeing the above example we can surely say that replacing six lines with a single one makes you write less and also provide faster execution when both performing for the same result and on top of everything it increases the program readability.
What does it consist of?
Let’s understand with a picture,
So here we can see three boxes, these boxes are the analogy after the “int a” of the previous examples on the right-hand side of =.
So coming to the example, we know that it is a conditional statement that depends on a condition to decide the flow of the program and conditions can either be true or false, Here the “IF BOX” is a Boolean expression that can be true or false and depending upon that program direction will go in the “DO THIS BOX1” or “DO THIS BOX2”.
Relating to the first example we have taken if the condition in IF BOX is true then the “a” will be assigned with the value of first DO THIS BOX and if IF BOX is not true then it is assigned with the value of second DO THIS BOX.
Hope it is helpful to you.
[full-width]
0 Comments