[Java] Calculation mechanism, operators and type conversion

How Java compute works

5 + 4

This remains unexplained. Java will give you the answer of 9 by adding 5 and 4.

Then

5 + 4 - 3

If so, how does Java do the calculations? : thinking: First of all

Add 5 and 4 to get 9. Then subtract 9 -3 to get 6.

By the way, these 5 and 4 and 3 are called ** operand **.

The process that Java performs calculations according to an expression is called ** evaluation **. The calculation result obtained by using the operands and operators is called ** garbled **. In the case of 5 + 4 --3 in the previous formula, first evaluate 5 + 4 and turn it into 9. Then evaluate 9-3 and turn it into 6. It's like: smile:

5 + 4 * 3

A formula with a mixture of multiplications. Same order as learned at school: smile:

First, evaluate it with 4 ✕ 3 and it turns into 12. Then it evaluates 5 + 12 and turns into 17.

(5 + 4) * 3

Again, the order is the same as I learned at school: smile: First, calculate the contents of (). Evaluate (5 + 4) and turn it into 9. Then evaluate 9 ✕ 3 and turn it into 27.

.


5 / 4

What happens in this case? : thinking: The answer is 1.25 if calculated normally. However, it does not appear in 1.25. The correct answer is 1.

The reason is simple: smile: This is because it is a calculation between integers. The part after the decimal point is truncated.

So, if you want to display after the decimal point

5.0 / 4 or 5 / 4.0 or 5.0 / 4.0

And either or both will be displayed as 1.25 if reduced to a decimal: smile:

Assignment operator

: sunny: Assign the contents of the right operand to the variable of the left operand

I explained it a little difficult, but I hope it will be easier if you remember variables.

Example.java


number = 10;

This is the one: sweat_smile: The right operand is 10 here. The left operand is the number here. So substitute 10 for number: smile:

Assignment operators are available in combination with other operators besides =.

Example a + = 5 (meaning a = a + 5) a-= 5 (meaning a = a-5)

Such. The meaning is to add 5 to a and assign it to a. Subtract 5 from a and assign it to a. It will be.

If a contains 6 as the initial value 6 + 5 is calculated first to get 11, and 11 is assigned to a. In the case of subtraction, 6-5 is calculated first to become 1, and 1 is assigned to a.

Increment and decrement operators

I explained that the assignment operator is a + = 5 (meaning a = a + 5). If you want to increase only 1, there are other ways to write it.

Increment operator.


a++;

Synonymous with a + = 1 or a = a + 1: smile: Increasing the value of this variable by 1 is called the increment operator.

Decrement operator.


a--;

Contrary to the increment operator Decreasing the value of a variable by 1 is called the decrement operator.

Basically, the increment / decrement operator is not used with other operators. If you use them together, a slight calculation error will occur. Therefore, unless there are some circumstances, it is better to use it alone. (Do not mix with other operators such as a ++ * 50, only a ++; when using)

Type conversion

.


5 / 4

If you want to display the decimal point calculation at the time of this calculation

5.0 / 4 or 5 / 4.0

I think I told you to fill in. This is also called type conversion.

What exactly is this type conversion? ?? : thinking: That is to say, ** type conversion is the conversion of a data type (int, double, etc.) to another data type. ** **

So even if you enter 5.0 / 4, your computer will do it for you.

Ah, yes yes. You should ask for 5.0 / 4.0.

It automatically interprets and displays the answer as 1.25. It automatically converts the type from a decimal / integer to a decimal / decimal.

Type conversion from integer to integer

Then can you automatically convert anything? : thinking: That's not the case.

Model name Range of storable integers
byte -Integer between 128 and 127
short -Integer between 32768 and 32767
int -An integer from 2147483648 to 2147483647
long -An integer from 9223372036854775808 to 9223372036854775807

If you look at the figure above For byte, an integer between -128 and 127 For short, an integer between -32768 and 32767 It has become.

I'd like you to imagine a little ...

Byte is a small box because the range of integers that can be stored is smaller than that of short. Since short has a larger range of integers than bytes, it should be a large box.

Small boxes can be stored in large boxes. However, large boxes cannot be stored in small boxes. It sticks out or the box itself breaks.

Along with this, type conversion can be done from small to large. However, in principle, type conversion is not possible from large to small, with exceptions.

Integer → decimal

As explained in 5.0 / 4, it can be represented by a decimal number, so type conversion is possible. You can type convert from integer to float, and you can type from integer to double.

Decimal → Decimal

Along with integers, the size of the box is relevant. Because double has a larger box than float Type conversion is possible from float to double, Type conversion is not possible from double to float.

Decimal → integer

I'm sorry to have come up many times, but I think that the answer calculated when I set it to 5.0 / 4 was 1.25. In other words, type conversion is not possible from decimal to integer.

Type conversion summary

Here I would like to announce the 6 best box sizes: tada :: raised_hands: The 1st box is the largest and the 6th box is the smallest.

Jajan!

Ranking :gift:Box size best 6:gift:
First place double
2nd place float
3rd place long
4th int
5th place short
6th place byte

Is this a little easier to imagine?

Byte-kun in 6th place has the smallest box, so you can change the type from 1st place to 5th place in a box larger than you. Long, who is in 3rd place, cannot change the type of the box smaller than himself from 4th to 6th. You can change the type to the 1st and 2nd boxes, which are larger than you. The 1st place double is the owner of the largest box, so it is impossible to change the type.

I'm going to write about how to change the type now: sweat_smile:

Example.java


public class Main {
	public static void main(String[] args) {
		int number = 5;
		double decimal = number;
		System.out.println(decimal);
	}
}

On the third line, I assigned the integer 5 to the variable number. It is an integer because its type is int.

In the 4th line, I assigned the variable number to the variable decimal. Since the type is double, it is converted to a decimal.

console.


5.0

Decimal division of integer variables

Example.java


public class Main {
    public static void main(String[] args) {
        int number1 = 5;
        int number2 = 2;
        System.out.println(number1 / number2);
    }
}

As mentioned above, the result of dividing integer variables is the integer 2. If you want to represent decimal numbers properly ...? : thinking:

It's not a mistake to change the int type to double type, It is troublesome to change each time.

Example.java


System.out.println((double)number1 / number2);

It's OK if you add (double) before the variable in the formula: smile: By the way, it's okay to put (double) before number2: smile:

** It is called a cast because it is manually forcibly converted in this way. ** **

From large mold to small mold

In principle, type conversion is not possible from large to small, with exceptions. I told you. Strictly speaking, it can be done. This is: sweat_smile: The "exception" part: sweat_smile: This is also called a cast because it forcibly converts the type. ** **

Int-kun, who is the 4th largest in the box size. Double-kun, who has the largest box, is trying to convert to int.

(Type name of conversion destination) Expression

You can force type conversion with.

Example.java


public class Main {
	public static void main(String[] args) {
		int number = (int)5.8;
		System.out.println(number);
	}
}

console.


5

Decimal 5.8 is now integer 5: smile:

If you can change from a large type to a small type, you don't have to worry about it: thinking: I think, but I don't recommend this very much. ..

This is because some of the data that is being forced into a small mold may be lost, or the missing part may lead to a malfunction. So don't use it unless you really have to use it as a last resort: sweat_smile:

Recommended Posts

[Java] Calculation mechanism, operators and type conversion
Java type conversion
Java study # 3 (type conversion and instruction execution)
[Java] Date type conversion
[Java] List type / Array type conversion
[Java] Precautions for type conversion
[Java] Type conversion speed comparison
Java Primer Series (Type Conversion)
Java for beginners, expressions and operators 1
Java reference mechanism (stack and heap)
Java for beginners, expressions and operators 2
Conversion between Kotlin nullable and Java Optional
Java date data type conversion (Date, Calendar, String)
[Easy-to-understand explanation! ] Reference type type conversion in Java
[Java ~ Variable definition, type conversion ~] Study memo
Notes on operators using Java ~ String type ~
[Basic knowledge of Java] About type conversion
Java 8 LocalDateTime type conversion stuff (String, java.util.Date)
Type conversion from java BigDecimal type to String type
Java review (2) (calculation, escape sequence, evaluation rule, type conversion, instruction execution statement)
[Introduction to Java] About type conversion (cast, promotion)
Optional Type conversion and return value (null support)
[JAVA] Stream type
Java Optional type
[Processing x Java] Data type and object-oriented programming
Java and JavaScript
XXE and Java
Java type conversion (String, int, Date, Calendar, etc.)
Java-automatic type conversion
Java variable declaration, initialization, data type (cast and promotion)
Learn for the first time java # 3 expressions and operators
About Java basic data types and reference type memory
Mutual conversion between Java objects and JSON using Moshi
Getters and setters (Java)
[Java] Thread and Runnable
Java learning 2 (learning calculation method)
Java true and false
Organize Java GC mechanism
[Java] String comparison and && and ||
[Java] Data type ①-Basic type
Uri → String, String → Uri type conversion
Comparison operators and conditionals
[Java, Kotlin] Type Variance
Java class type field
Type determination in Java
Java study # 1 (typical type)
Java --Serialization and Deserialization
[Java] Arguments and parameters
timedatectl and Java TimeZone
[Java] Branch and repeat
[Java] About enum type
[Java] Variables and types
java (classes and instances)
[Java] Overload and override
Endian conversion with JAVA
Basic operators and operations
Find the address class and address type from the IP address with Java
[Java Bronze] Learning memo (interface, static method, type conversion, etc.)