How to Java: E3 (If/Else Statements)

E3 (If/Else Statements)

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.

Want to start making money as a white hat hacker? Jump-start your white-hat hacking career with our 2020 Premium Ethical Hacking Certification Training Bundle from the new Null Byte Shop and get over 60 hours of training from ethical hacking professionals.

Buy Now (90% off) >

Our Best Hacking & Security Guides

New Null Byte posts — delivered straight to your inbox.

1 Comment

Great tutorial, thanks! +1

Share Your Thoughts

  • Hot
  • Latest