Mastering the use of conditions is one of the 5 fundamental skills of building algorithms:
Conditions are the only way developers have to tell the computer how to make decisions in real time, much like how human brains work.
Let's say we are building a program to help us choose what to store and we hate the color blue, we can tell the computer to avoid blue using a condition like this:
If color is not blue, then... do something.
Else... do nothing or exit.
The decision statements are: ʻif-then-else
The structure of the ʻif-then-else` statements is:
The expression indicated in the
if statement is evaluated. If the expression is true, the block of then statements will be executed and if the expression is false, the block of else statements will be executed.
The else part does not have to exist. In this case we would have an if-then statement.
this way we could have the following source code:
The if-then-else statements can be nested and thus we would find an if-then-elseif statement, which would have the following structure:
In this way we can have the following code:
For cases in which there are many paths of execution in an if statement we have the switch statement. The switch statement evaluates an expression and will execute the block of statements that matches the value of the expression.
The value of the expression must be numeric. Although from Java SE 7 you can already use expressions whose evaluation is strings.
The structure of the switch statement is:
It is important to see that the break statement is used. The break statement causes the switch statement to be exited and therefore the rest of the statements are not evaluated. Therefore its use is mandatory at the end of each of the blocks.
A clear example in which we can use the switch statement is to evaluate the value of a month in numerical terms and convert it to a string. This code would be as follows:
The example above was a simple condition, but in real life, choosing what to do involves a combination of several conditions to make the final decision, for example: Let's look at this algorithm that tells a computer how to decide what to wear on Valentine's Day. Valentine:
If you want to represent this algorithm in Java, it will look something like this:
The most efficient way to learn: Join a cohort with classmates like yourself, live streamings, coding jam sessions, live mentorships with real experts and keep the motivation.
From zero to getting paid as a developer, learn the skills of the present and future. Boost your professional career and get hired by a tech company.
Start a career in data science and analytics. A hands-on approach with interactive exercises, chat support, and access to mentorships.
Keep your motivation with this 30 day challenge. Join hundreds of other developers coding a little every day.
Start with Python and Data Science, Machine Learning, Deep Learning and maintaining a production environment in A.I.