Java Basics

... by Bittle in Java Tutorial January 12, 2019

Comparison operators

The main comparison operators include

  • < (less than)
  • > (Greater than)
  • == (equal to)


Pre and Post Increment/Decrement Operator

the shortcut for adding or subtracting 1 from a variable:

  • x++; // same as x = x + 1;
  • x--; // same as x = x - 1;

The place of the operator (either before of after the variable) can affect the result. Putting the operator before the variable means "first increment and then use the new value" (++x).

For example:

int x = 0;
int z = ++x;

System.out.println("x = "+x + ", z = " + z);

will output x = 1, z = 1, but

int x = 0;
int z = x++;

System.out.println("x = "+x + ", z = " + z);

will output

x = 1, z = 0! z gets the value of x and then x is changed.


Conditional Branching

Conditional branching uses comparison operators to compare values. Saying "If there is a dog, run away" would be conditional branching since you will only run away if a dog is present. Conditional branching includes if statements and loops:

int age = 16;
if(age < 21){
    System.out.println("You are too young to own a dog!");
} else{
    System.out.println("Wow you sure are old!");
}

output:

You are too young to own a dog!

If we increase the age to 22 then we get the output "Wow you sure are old!"


Loops

There are three main loop constructs: while, do-while, and for. They are helpful when repeating statements!

While loop

As long as the condition is true execute the statements inside the block (blocks are encapsulated by curly braces).

int x = 0; // assign 0 to x
while (x < 3) {
    // loop will run since 0 < 3
    System.out.println(x); // print current value of x
    x = x + 1; // add 1 to x to avoid being here infinitely
}

output:

0
1
2

Do-While loop

Do-while loops are similar to while loops but evaluate the expression after executing the block at least once. The block inside the do{} block will always execute at least once:

int x = 1;
do {
    System.out.println(x);
    x++;
} while (x < 1);

Non-enhanced For Loop

A for loop is used when you want to loop a certain number of times:

for (int x = 0; x < 4; x++) {
    System.out.println(x);
}

output:

0
1
2
3

Steps:

  1. Create a variable x and set it to 0
  2. Repeat while i is less than 4
  3. At the end of each loop iteration, add 1 to x

Enhanced For Loop

Enhanced for loops are used to easily iterate through elements in a collection (such as arrays).

int[] arr = {0, 6, 3, 2, 1};
for (int a : arr) {
    System.out.println(a);
}

output:

0
6
3
2
1

You will learn about arrays when we look into variables.

Comments (0)

Search Here