Tech With Tim Logo
Go back

Operators

Another Way to Create Variables

Continuing from last video... I would like to show you an alternative to create a variable. We can actually declare and allocate the space for a variable without giving it a value. To do this we simply omit assigning it a value. However, we need to ensure that we give our variable a value later in the program before we reference it.

package tutorial;

public class Main {
    
    public static void main(String[] args) {
        int x;
        x = 7;
        // An alternative method to create the variable x and assign it to value 7
    }

}

Operators

There are a series of arithmetic operators that we can apply to variables and data within out programs. Some operations (such as multiplication and division) are only defined for numbers (ints and doubles). However, we can actually use the + operator on Strings to concatenate them. The list of common arithmetic operators is seen below.

+   // addition 
-   // subtraction 
*   // multiplication
/   // division
%   // modulus (remainder)

An example of these operators in use can be seen below.

int x = 5;
int y = 7;
int z = 56;
int sum = x + y + z;
int val = x - y / z;
int val2 = x * x;
int val3 = 5 + 7 * z;

Operations With Doubles

Whenever performing these operation with doubles we must ensure we are storing the value to our expression in a float typed variable. Whenever even one double is present in a mathematical expression the result is always a double.

double x = 5.6;
int y = 7;
int z = 56;
double sum = x + y + z;
double val = x - y / z;
double val2 = x * x;
int val3 = 5 + 7 * z;

Order of Operations

These operators can be used in conjunction with one another, this means they need some order of precedence. They follow the standard order of operations B brackets E exponents D division M multiplication & modulus A addition S subtraction

double x = 5.0;
int y = 7;
int z = 56;
double val = (x + y) / z;
// Here 5.0 + 7 is evaluated first and then that sum is divided by 56, hence 12.0/56

Operations on Strings

The + operator is supported on String data types. When we add two strings that is now as concatenation. The string that is being added will be appended to the other string.

String x = "hello";
String y = "tim";
String z = x + y; //this is "hellotim"
Design & Development by Ibezio Logo