Arithmetic operators to increase or decrease values in Java

Java

In Java there are a couple of arithmetic operators that will allow us to increase (++) or decrease (- -) in a unit the value of a variable. These two operators can be placed before (prefixes) or after (suffixes) of the variable. In this way, we can increase the value of a variable of type int in the following way:

For example, to add 2 to a variable «a», the «normal» way to get it would be:

a = a + 2;

but there is a short form in Java:

a += 2;

Just as we have the operator += to increase the value of a variable, we can use -= to decrease it, /= to divide it by a certain number, *= to multiply it by a number, and so on.

For example, to multiply by 10 the value of the variable «b» we would do

b *= 10;

We can also increase or decrease the value of a variable by one unit, using the operators increment (++) and decrement (–). So, to add 1 to the value of «a», we can use any of these three ways:

a = a+1;
a += 1;
a++;
Increment and Decrement
Increment and Decrement

The increment and decrement operators can be written before or after the variable. Thus, it is the same to write these two lines:

a++;
++a;

But there is a difference if this value is assigned to another variable at the same time that increases / decreases:

int c = 5;
int b = c++;

results in c = 6 and b = 5, because the value is assigned to «b» before increasing «c», while

int c = 5;
int b = ++c;

results in c = 6 and b = 6 (the value is assigned to «b» after increasing «c»).

 

Arithmetic operators to increase or decrease
Arithmetic operators to increase or decrease

Therefore, to avoid unexpected side effects, it is better not to increase one variable while assigning its value to another, but to do it in two steps.

 

Proposed Exercise 1: Calculate by hand the result of the following operations with integers, and then create a program that shows the result.

a = 5;

a++;

a*=2;

a-=3;

a%=5;

a=a+7;

 

Other types of numeric data

Not only can you store whole numbers of up to 9 digits. Java also allows us to use other types of numeric data:

Name

Do you support decimals?

Min value

Max value

Precision

Size

byte

no

-128

127 1 byte

short

no

-32.768

32.767

2 bytes

int

no

-2.147.483.648

2.147.483.647

4 bytes

long

no

-9.223.372.036.854.775.808

9..223.372.036.854.775.807

8 bytes

float

Yes

1.401298E-45

3.402823E38

6-7 digits

4 bytes

double

Yes

4.94065645841247E-324

1.79769313486232E308

14-15 digits

8 bytes

The data of type byte, short, int and long serve to store whole numbers, of greater or smaller size. If that size overflows, the program will be interrupted with an error, as in this example:

// OverflowByte.java
// Example of overflow of a variable
// Arithmetic operators to increase or decrease values, Aitor Alcaniz
 
class OverflowByte { 
    public static void main( String args[] ) { 
byte data= 100;

        System.out.print( "The data initially is:" );
        System.out.println( data);

        data += 100; 

        System.out.print( "If we add 100, the data now is:" );
        System.out.println( data);
    }
}

What would it show?

The data initially is: 100
If we add 100, the data now is: -56

On the other hand, the data float and double allow to store real numbers with decimal figures, which can store the numbers incorrectly if they have more figures than allowed by this type of data, as in this example:

// PrecisionFloat.java
// Ejemplo de límite de precisión de un dato float
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

class PrecisionFloat { 
    public static void main( String args[] ) { 
        float data= 1.23456789f;

        System.out.print( "The data initially is:" );
        System.out.println( data);

        data+= 1000; 

        System.out.print( "If we add 1000, the data is now:" );
        System.out.println( data);
    }
}

What would he write?

The data initially is: 1.2345679
If we add 1000, the data now is: 1001.23456

To request data of these types, we can use a Scanner with .nextByte, .nextShort, .nextLong, .nextFloat or .nextDouble

For example, you could add two real numbers in a similar way as we have seen for two whole numbers:

// SumFloat.java
// Sum of two real numbers
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

import java.util.Scanner;
 
class SumFloat { 
 
    public static void main( String args[] ) { 
 
        Scanner input;
        float numberOne, numberTwo;
 
        input = new Scanner(System.in);

        System.out.print( "Enter the first real number: " );
        numberOne= input.nextFloat();

        System.out.print( "Enter the second real number: " );
        numberTwo= input.nextFloat(); 
 
        System.out.print( "Its sum is: " );
        System.out.println( numberOne+numberTwo);
    }
}

An example of its possible result (showing the possible losses of precision) could be:

Enter the first real number: 2,3
Enter the second real number: 3.56
Its sum is: 5.8599997

Proposed exercise 2: Create a program that calculates and displays the sum of two two-digit numbers (byte type) that the user enters.

// SumByte.java
// Sum of two byte numbers
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

import java.util.Scanner;

class SumByte {

    public static void main( String args[] ) {

        Scanner input;
        byte byteOne, byteTwo;

        input = new Scanner(System.in);
        System.out.print( "Enter the first byte number: " );
        byteOne = input.nextByte();
        System.out.print( "Enter the second byte number: " );
        byteTwo= input.nextByte();

        System.out.print( "Its sum is: " );
        System.out.println( byteOne +byteTwo);
    }
}

Proposed exercise 3: Create a program that asks the user for their year of birth and the current year (using short data) and find the difference of both to obtain their age.

// CalculateAge.java
// Calculate the age
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

import java.util.Scanner;

class  CalculateAge {

    public static void main( String args[] ) {

        Scanner input;
        short birth, currentYear;

        input = new Scanner(System.in);
        System.out.print( "Enter the year of birth: " );
        birth = input.nextShort();
        System.out.print( "Enter the current year: " );
        currentYear = input.nextShort();

        System.out.print( "the age is: " );
        System.out.println( currentYear - birth );
    }
}

Proposed Exercise 4: Create a program that calculates and shows the division of two double precision real numbers entered by the user.

// DivisionDouble.java
// Division of two doble numbers
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

import java.util.Scanner;

class  DivisionDouble {

    public static void main( String args[] ) {

        Scanner input;
        double numberOne, numberTwo;

        input = new Scanner(System.in);
        System.out.print( "Enter the first real number: " );
        numberOne= input.nextDouble();
        System.out.print( "Enter the second real number: " );
        numberTwo= input.nextDoublet();

        System.out.print( "Its division is: " );
        System.out.println( numberOne/numberTwo);
    }
}

Proposed Exercise 5: Create a program that asks the user for a length in miles (for example, 3) and calculate its equivalence in kilometers, using float data (1 mile = 1,609 km).

// MilesToKm.java
// Pass miles to kilometers
// Arithmetic operators to increase or decrease values, Aitor Alcaniz

import java.util.Scanner;

class  MilesToKm {

    public static void main( String args[] ) {

        Scanner keyboard;
        float milesNumber;

        keyboard = new Scanner(System.in);

        System.out.print( "Enter the number of miles: " );
        milesNumber = keyboard.nextFloat();

        System.out.print( milesNumber+" miles in meters is: "+(1.609*milesNumber));
    }
}

Publicar comentario