LoginSignup
0
0

More than 3 years have passed since last update.

Javaの変数・データ型についてのまとめ

Last updated at Posted at 2021-04-29

Javaでよく使われる変数についてまとめた個人的なメモです。
Javaでは、基本的に 型 + 変数名 で変数を定義します。

文字... char

一文字だけの文字を扱う場合は、charを使います。

MyApp.java
char a = 'a';
char b = '花';

charを用いる時は変数の値をシングルクオーテーション '' で囲わなければならない点に注意が必要です。

文字列... String

MyApp.java
String message = "Hello World!";

String変数に代入する値はダブルクオーテーション "" で囲います。
また、特殊文字として\nの改行や、\tでタブを使う事が可能です。

MyApp.java
String message = "Hello\nWorld\t!";

バックスラッシュ\は、Macの場合option + ¥を押すことで入力できます。

整数... byte / short / int / long

データ型
byte 8ビット整数 -128~127
short 16ビット整数 -32,768~32,767
int 32ビット整数 -2,147,483,648~2,147,483,647
long 64ビット整数 -9,223,372,036,854,775,808~9,223,372,036,854,775,807

通常は int 型 がよく使われます。

MyApp.java
int x = 10;
long y = 1234567891234L;

long 型の変数に int 型の範囲を超える数値を代入する場合は末尾に「L」を記述する必要があります。

浮動小数点数... float / double

データ型
float 32ビット単精度浮動小数点数
double 64ビット倍精度浮動小数点数

通常は double 型がよく使われます。

MyApp.java
double d = 1234.567;
float f = 3.14F;

float 型の変数に数値を代入する場合、それぞれのデータ型の扱える範囲の数値であってもそのまま記述するとエラーとなる為、 float 型の値に浮動小数点数を記述する場合は末尾に「F」を付ける必要があります。

論理値... boolean

true もしくは false の値を格納する際に使用します。

MyApp.java
boolean flag = true;

型を変更する(キャストする)

  • double 型の値をint 型にする場合
MyApp.java
public class MyApp {
  public static void main(String[] args) {

    double d = 5242.88;
    int x = (int)d;
    System.out.println(x);

  }
}
% javac MyApp.java
% java MyApp
5242
  • int 型の値をdouble 型にする場合
MyApp.java
public class MyApp {
  public static void main(String[] args) {

    /* 
    以下の方法だと整数の状態で計算されてしまうため、結果 2.5 ではなく 2 が返ってきてしまうため注意。
    int i = 10;
    double y = i / 4;
    System.out.println(y);
    */

    // 正しく処理するためには以下のように記述する
    int i = 10;
    double y = (double)i / 4;
    System.out.println(y);

  }
}
% javac MyApp.java
% java MyApp
2.5

以上になります。

【参考サイト】
- Let'sプログラミング -基本のデータ型

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