0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaで「キャスト演算子と型変換ルール」の動作を確認してみた

Posted at

概要

Javaで「キャスト演算子と型変換ルール」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

JSample11_1.java
class JSample11_1{
  public static void main(String[] args){
    float f = 10;
    double d = 1234L;

    System.out.println("f=:" + f);
    System.out.println("d=:" + d);
  }
}
JSample11_2.java
class JSample11_2{
  public static void main(String[] args){
    int i1 = 123456789;
    float f1 = i1;
    System.out.println("i1=:" + i1);
    System.out.println("f1=:" + f1);

    long l2 = 1234567890123456789L;
    float f2 = l2;
    double d2 = l2;

    System.out.println("l2=:" + l2);
    System.out.println("f2=:" + f2);
    System.out.println("d2=:" + d2);
  }
}
JSample11_3.java
class JSample11_3{
  public static void main(String[] args){
    double d = 123.0;
    int i = (int)d;
    float f = (float)d;

    System.out.println("d=:" + d);
    System.out.println("i=:" + i);
    System.out.println("f=:" + f);
  }
}
JSample11_4.java
class JSample11_4{
  public static void main(String[] args){
    long l1 = 1234567890123456789L;
    int i1 = (int)l1;
    float f2 = 123.45f;
    int i2 = (int)f2;

    System.out.println("l1=:" + l1);
    System.out.println("i1=:" + i1);
    System.out.println("f2=:" + f2);
    System.out.println("i2=:" + i2);
  }
}

以下のコマンドを実行しました。

$ javac JSample11_1.java
$ java JSample11_1 
f=:10.0
d=:1234.0
$ javac JSample11_2.java
$ java JSample11_2 
i1=:123456789
f1=:1.23456792E8
l2=:1234567890123456789
f2=:1.23456794E18
d2=:1.23456789012345677E18
$ javac JSample11_3.java
$ java JSample11_3 
d=:123.0
i=:123
f=:123.0
$ javac JSample11_4.java
$ java JSample11_4 
l1=:1234567890123456789
i1=:2112454933
f2=:123.45
i2=:123

まとめ

何かの役に立てばと。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?