Learning Basic in Java If & Else to intermediate only

Here's an explanation:

An if statement has a condition, and a body. The body has some code, and the condition has some expression. The statements in the body only execute (that is, the code in the body is only run by the program), if the condition is true. So if the condition expression evaluates to be true, then the code runs. If it's false, then it skips executing the code inside.

The condition is inside a set of parenthesis after the if, I.e.: if(condition)

The condition is a boolean expression, which is a fancy way of saying "something that can be true or false".

For example, if you wanted your if statement to run every time you ran the program, you could so something like this: if(3 > 2) because the condition is always true. Or you could simply say if(true). Obviously, if you want your if statement to be true always, you probably don't even need one, because you can just write the code normally for it to execute each time.

If you have one line of code to execute after an if statement, like a print statement, you can write it like this:

if(condition) System.out.println("condition is true");

Ussualy we wrap the code inside braces, and you have to if you want more than one line to be apart of the if statement: if(condition) { Statement1; Statement2; ... }

/r/learnprogramming Thread Parent