Skip to content

Instantly share code, notes, and snippets.

@discoNeko
Last active July 3, 2016 05:54
Show Gist options
  • Save discoNeko/efb0959b4a842b390e86b686d15e9016 to your computer and use it in GitHub Desktop.
Save discoNeko/efb0959b4a842b390e86b686d15e9016 to your computer and use it in GitHub Desktop.

javaのint型long型の変換について

//long型変数 = int型変数 * int型変数;
int a = 1000000000;
int b = 1000000000;
long p = a * b;

と記述すると「a * b」でint型のオーバーフローが起こった場合、
オーバーフローした計算結果がlong型変数pに代入される。

「(long) a * b」や「1l * a * b」で
long型にキャストしておけばlong型としての計算結果が得られる。

import java.math.*;
 
public class Main {
	public static void main(String[] args){
		int a = 1000000000;
		int b = 1000000000;
		System.out.println(a+" "+b); //1000000000 1000000000
		long p1 = a*b;
		long p2 = 1l*a*b;
		long p3 = (long)1f*a*b;
		long p4 = (long)1.0*a*b;
		long p5 = (long)a*b;
		long p6 = (long)a*(long)b;
		System.out.println(p1); //-1486618624
		System.out.println(p2); //1000000000000000000
		System.out.println(p3); //1000000000000000000
		System.out.println(p4); //1000000000000000000
		System.out.println(p5); //1000000000000000000
		System.out.println(p6); //1000000000000000000
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment