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){
}else if(another condition is true){

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");
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.

Learn How To Code with Null Byte's Beginner's Python Course.

Buy Now for $99.99 >

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