Studying Java ~ Part 8 ~ Cast

1.First of all

This time, "** Cast **"!

Casting is also called type conversion, and is the process of converting types (int, byte, double, etc.).

Convert int type to byte type! Convert double type to int type! Convert short type to long type!

etc... ~~ Since this kind of processing will be necessary eventually, I will write an article as soon as possible as a basic part ~~ ~~ And the object type is omitted ... ~~

Let's study this cast!

2. Cast

2.1. Basic cast concept

The reason why the cast is necessary in the first place is ...

For example, assigning the value of a byte type variable to an int type variable "** can **" This is because the byte type and the int type are similar types, the byte type is small and the int type is large.

キャプチャ_31.png

Here's what happens when you source the above example.

Main.java


public class Main {
	public static void main(String[] args) {

		//byte type declaration
		byte b = 100;
		//int type declaration
		int i = b; //int ← byte substitution

	}
}

Can be assigned normally


On the contrary, when assigning from int type to byte type, what happens is an error!

キャプチャ_32.png

The reason for the error is that the int type cannot fit in the byte type more than the byte type.

Main.java


public class Main {
	public static void main(String[] args) {

		//int type declaration
		int i = 100;
		//byte type declaration
		byte b = i; //byte ← int error occurs

	}
}

If you try to assign a double or float type value to an integer such as an int type, you will still get an error. The integer type does not include decimal points, right? Since the range that can be expressed is different, it will be an angry error saying "Match the type!".

2.2. Forcibly cast

But that's it! I really have to cast! If you need a ** strong will , you must use " cast **".

** Casting is an impossible type conversion, so it is not recommended and should not be abused. ** **

How to write the cast Write (type) before the variable. Please enter the type you want to convert.

With the previous error,

byte b = i;

Rewrite

byte b = (byte)i;

OK! !!

Main.java


public class Main {
	public static void main(String[] args) {

		//int type declaration
		int i = 100;
		//byte type declaration
		byte b = (byte)i; //byte ← int No error occurs because I cast it! !! !!

	}
}

2.3. Cast with side effects

Also, since the type is forcibly changed, if you cast the double type to the int type, there is a side effect that only the integer part value is assigned, so be careful! Then, I would like to actually see the situation.

Main.java


public class Main {
	public static void main(String[] args) {

		//Double type declaration&Initialization
		double doubleNumber = 15.88d;

		//int type declaration
		int intNum;

		//Cast to int type&Substitution
		intNum = (int) doubleNumber;

		//Display the value after casting
		System.out.println(intNum); //intNum is an integer of 15

	}
}

When casting a double type to an int type, the .88d in 15.88d is eliminated and only 15 is assigned to intNum.

There are many other side effects, so be careful ... (horror style)

2.4. Implicit and explicit casts

There are two types of casts.

--When Java casts behind the scenes --When explicitly writing the cast content in the source (explicit means casting using ())

The difference between these two is

--When there is no problem even if the former does not explicitly cast --The latter is when problems occur if you do not explicitly cast

It has become.

Previously introduced "[Primitive type](https://qiita.com/koukonko/items/e2714f404b9e369b01b7#21-%E3%83%97%E3%83%AA%E3%83%9F%E3%83%86" % E3% 82% A3% E3% 83% 96% E5% 9E% 8B) "top-to-bottom assignments do not need to be explicitly cast, but bottom-to-top assignments are explicit. Need to cast.

For the time being, here is a simple table related to numerical values.

Mold Box range
byte -128 ~ 127
short -32768 ~ 32767
int -2147483648 ~ 2147483647
long -9223372036854775808 ~ 9223372036854775807
float 32bit single precision floating point number
double 64-bit double precision floating point number

The source also includes examples of implicit and explicit casts.

Main.java


public class Main {
	public static void main(String[] args) {

		//Implicit cast
		byte b = 1;		 // byte ← int
		short s = b; 	 // short ← byte
		int i = s;		 // int ← short
		long l = i; 	 // long ← int
		float f = l; 	 // float ← long
		double d = f; 	 // double ← float

		//Explicit cast required
		f = (float) d; 	 // float ← double
		l = (long) f; 	 // long ← float
		i = (int) l; 	 // int ← long
		s = (short) i; 	 // short ← int
		b = (byte) s; 	 // byte ← short

	}
}

It will be like that. ~~ Please tell me if it's hard to see ~~

3. Conclusion

This is the end of the cast. Cut up to the basic part! !!

There are scenes where casts are also used for object types, but I will omit them. I'm wondering if it should be understood later.

And I'm having a lot of trouble with the composition ...

Next time I will write "scope". ~~ I think it would be impossible if I didn't study control statements, but I would like to devise a way to have them skip and then come back ~~

If you have any mistakes or questions, please do not hesitate to throw Masakari. I will do my best to stab you! It is helpful because you can react quickly on Twitter.

Then, I'll do my best next time!

Next time → "Study Java-Part 9-Scope"

Recommended Posts

Studying Java ~ Part 8 ~ Cast
Studying Java ―― 3
Studying Java ―― 9
Studying Java ―― 4
Studying Java -5
Studying Java ―― 1
Studying Java # 0
Studying Java ―― 8
Studying Java ②
Studying Java ―― 7
Studying Java ―― 2
Studying Java ①
Studying Java -10
Studying Java 8 (Optional)
java practice part 1
Studying java9 (jShell)
Studying Java 8 (Stream)
Studying Java 8 (Collector / Collectors)
Studying Java 8 (see method)
Studying Java 8 (see constructor)
Studying Java 8 (lambda expression)
45 Java Performance Optimization Techniques (Part 1)
Java and Iterator Part 1 External Iterator
Apache Hadoop and Java 9 (Part 1)
Java Servlet / JSP Request Scope Part 1
Java to learn with ramen [Part 1]
Studying Java # 6 (How to write blocks)
Java Servlet / JSP Request Scope Part 2
Basic usage of java Optional Part 1
Java
Studying Java 8 (StaticIF and Default methods)
Server processing with Java (Introduction part.1)
Creating lexical analysis in Java 8 (Part 2)
Studying Java 8 (String Joiner and join)
Java
GAE / Java8 trial (Part 6: "Deployment failure")
Studying java9 (dropWhile, takeWhile and Stream.ofNullable)
Creating lexical analysis in Java 8 (Part 1)
Kotlin Class part.2 to send to Java developers
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Studying Java 8 (date API in java.time package)
Call GitHub API from Java Socket API part2
[# 1 Java] Basics of Java-Major premise before studying-
Studying how to use the constructor (java)
Getting Started with Java Starting from 0 Part 1
AWS Lambda with Java starting now Part 1
Studying java (Basic Information Technology Engineer Examination)
GAE / Java8 trial (Part 4: "Datastore access logic")
Creating a matrix class in Java Part 1