Tech and Media Labs
This site uses cookies to improve the user experience.




Java Operations

Jakob Jenkov
Last update: 2015-02-25

By now you should have an idea about what Java variables are, how to declare them. It is time to look in more detail on what operations you can perform on variables.

Java operations are instructions that can read and write the values of variables, perform arithmetic on variables, and control the program flow.

Variable Operations

Java has a set of basic variable manipulation operations. You can assign values to variables, read the value of variables, and perform arithmetics on variable values. Finally, Java also has an operation that allows you to create (instantiate) objects, and assign a reference to the object to a variable.

Variable Assignment

Variable assignment is covered in the text on Java variables, but I will show you a short example here:

int age;
age = 25;

int yearBorn = 1975;

This example shows two variable assignments. The first line declares an int variable named age. The second line assigns the value 25 to the age variable. The third line creates an int variable named yearBorn and assigns the value 1975 to it in the same statement.

Variable Reading

Variable reading is also covered in the text on Java variables, but here is a short example:

String name = "Jakob";

String name2 = name;

This example first creates a variable named name and assigns the string value Jakob to it. In the second line the value of the name variable is assigned to the name2 variable. The value of the name variable is read, before it is assigned. This is one way you can read the value of a variable.

Variable Arithmetics

Variable arithmetic means performing calculations on variable values. Here is an example of adding to numbers (variables) in Java:

int sum = 123 + 456;

The + sign is used as addition operator. After executing this line the variable sum will contain the sum of 123 and 456.

Here is a more advanced addition example:

int price1 = 123;
int price2 = 456;

int total        = price1 + price2;
int totalPlusFee = total + 999;

The example first creates two int variables (integers - numbers) and assign them two different values. The third line of the example then adds the two price variables and assign the sum as value to the total variable. The last line of the example creates a variable named totalPlusFee and sets its value to the value of the total variable plus a fixed number (999).

Subtracting variables from each other is done using the - operator. Here is a quick subtraction example:

int diff = 456 - 123;

The variable diff will contain the value of 123 subtracted from 456 after executing this line.

Variable multiplication is done using the * operator. Here is a simple multiplication example:

 int result = 123 * 456;

The variable result will contain the value of 123 multiplied by 456 after executing this line.

Division is performed using the / operator. Here is a division example:

int result = 100 / 10;

The variable result will contain the result of dividing 100 by 10 after executing this line. Note, that since int is an integer type, all fractions in the result of the division will be cut off the final result.

Here is a slightly more complex arithmetic example:

int price  = 12;
int amount = 23;

int totalPrice = price * amount;

int discount = 20;  //20%
int totalAfterDiscount = (totalPrice * (100-discount)) / 100;

In this example two variables called price and amount are declared. Each is a assigned a value. Then a variable called totalPrice is created, and assigned the value of price * amount (price multiplied with amount).

Third, a discount variable is declared and assigned the value 20. This variable is to be interpreted as a percentage.

Fourth, the totalAfterDiscount variable is declared, and the total price without the 20% discount is calculated, and assigned to totalAfterDiscount.

Object Instantiation

Variables can point both to primitive values (int, float etc.) or to objects. An object is an instance of some class. You instantiate an object of a certain class using the new keyword. Here is an example:

MyClass myClassInstance = new MyClass();

This example declares a variable of the MyClass class (custom data type), and then creates a new MyClass instance and assigns a reference to this instance to myClassInstance variable.

Program Flow

Java also has set of operations targeted at controlling the program flow. Each of these operations are covered in more detail in their own texts, but I will shortly introduce them here.

if statements

Java if statements make a decisions between which of two blocks of code to execute. Here is a simple example:

int amount = 9;

if(amount > 9) {
    System.out.println("amount is greater than 9");
} else {
    System.out.println("amount is 9 or less)");
}

This example first declares a variable called amount, and assigns the value 9 to it.

What happens next is that the if statement compares the value of the amount variable to 9. If the value is above 9, then the first block of code (inside the { } ) is executed. Else, the second block of code (after the else keyword) is executed.

The if statement can thus be used to select which of two blocks to execute. Actually, the else block is optional, but the text on Java if explains all that in more detail.

switch statements

A switch statement works a bit like an if statement, except it can choose between more than two blocks of code to execute. Here is a simple example:

int amount = 9;

switch(amount) {
    case     0 : System.out.println("amount is  0"); break;
    case     5 : System.out.println("amount is  5"); break;
    case    10 : System.out.println("amount is 10"); break;
    default    : System.out.println("amount is something else");
}

This example first creates a variable named amount and assigns the value 9 to it.

Second, the example "switches" on the value of the amount variable. Inside the switch statement are 3 case statements and a default statement.

Each case statement compares the value of the amount variable with a constant value. If the amount variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break keyword after each statement. If no break keyword was place here, the execution could continue down the rest of the case statements. The break keyword makes execution jump out of the switch statement.

The default statement is executed if no other case statement before it matched the value of the variable being switched on.

The default statement is executed if no case statement matched the value of the amount variable. The default statement could also be executed if the case statements before it did not have a break command in the end.

Switch statements are covered in more detail in the text about Java switch statements.

for loops

A for loop repeats a block of code as long as some condition is true. Here is a simple example:

for(int i=0; i < 10; i++) {

   System.out.println("I is: " + i);

}

This example is a standard for loop. Inside the parantheses () after the for keyword, are three statements separated by semicolon (;).

The first statement declares an int variable named i and assigns it the value 0. This statement is only executed once, when the for loop starts.

The second statement compares the value of the i variable to the value 10. If the value of i is less than 10, then the for loop is executed one more time. This statement is executed for each iteration in the for loop.

The third statement increments the value of i. This statement is also executed once per iteration of the for loop.

The result of this for loop is thus, that the body of the loop is executed 10 times. Once for each of the values of i that are less than 10 (0 to 9).

Java for loops are useful when you need to repeat a certain set of operations multiple times. For instance, carry out some set of operations on each element in an array.

Java for loops are covered in more detail in the text about Java for loops.

while loops

Java while loops are similar to for loops. They execute a block of code while a certain condition is true. Here is a simple example:

int amount = 0;

while(amount < 10) {
    System.out.println("amount is " + amount);

    amount++;
}

This example first declares a variable named amount and assigns the value 0 to it.

Second, the while loop is executed. The while loop executes as long as the comparison inside the parantheses evaluates to true. That is, as long as the amount variable is less than 10.

Inside the while loop the amount variable is printed out in the first line. In the second line the amount variable is incremented. The ++ after the variable names means add 1 to the variable. When the amount variable reaches the value of 10, the condition inside the while loop parantheses no longer evaluates to true, and the while loop stops.

While loops are covered in more detail in the text about Java while loops.

Method Calls

Methods are groups of statements that can be executed as a single statement. Executing a method is also called invoking a method, or calling a method. Here is a simple example of a class that has two methods, where one method calls the other:

public class MyClass() {

    public void printBoth(String text1, String text2) {
        print(text1);
        print(text2);
    }

    public void print(String text) {
        System.out.print(text);
    }
}

This class contains two methods: printBoth() and print().

Notice how printBoth() calls the print() method two times, each time with a different of the parameters passed to the printBoth() method.

The print() method is thus a reusable block of code that can be called from anywhere. When the print() method is finished executing, the program jumps back to after the line that called the print() method. Methods can thus be used to jump to different parts of the program, and return from there again.

Methods are covered in more detail in the text on Java methods.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC