Hello Java-ers,
In the previous two tutorials, we learned about installing the JDK, Installing/CreatingAProject in Eclipse IDE, and data types in Java.
In this tutorial, we will be learning about if/else statements.
--------------------------------------
In Java, an if statement can be interpretted as
if(This condition is true){
doSomething();
}else if(another condition is true){
doSomethingElse();
}else{
otherConditionsAreFalseDoThisOtherThing();
}
So lets write our first if/else statement:
(Assuming that you (the reader) have already created a Java project and file for this)
lets make a program that checks to see if an int variable equals the number "5":
public class numCheck{
public static void main(String[] args){
int num = 12;
if(num == 5){
System.out.println("Num equals 5");
}else{
System.out.println("Num does not equal 5");
}
}
}
(If you prefer organized code, press Ctrl+Shift+O (Windows), Cmd+Shift+O (OSX), Ctrl+Shift+O (Linux))
You can find the code for this on Github HERE
-----------------
You don't need the brackets (its not required, but adding them doesn't harm anything) after the if/else statement, only if the doSomething() statements are only one line, with just one semi-colon at the end.
Its only when you have multi-lined statements within an if statement, you Must have brackets.
Just updated your iPhone to iOS 18? You'll find a ton of hot new features for some of your most-used Apple apps. Dive in and see for yourself:
1 Comment
Great tutorial, thanks! +1
Share Your Thoughts