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

リテラル(literal)とは、ソースコード内に直接記述された定数の値を指します。たとえば、100 や "Hello" などがその例です。

リテラルの種類一覧

リテラルの種類 補足
整数リテラル 123, 0b1010, 0x1F 10進数、2進数、16進数など対応
浮動小数点リテラル 3.14, 2.0e10, 1.0f f または d で型を指定可能
文字リテラル 'A', '0', '\n' シングルクォートで囲む
文字列リテラル "Java", "Hello" ダブルクォートで囲む
論理リテラル true, false ブール型
nullリテラル null 参照型変数に使う

整数リテラルの例

int dec = 10;       // 10進数
int bin = 0b1010;   // 2進数(Java 7以降)
int oct = 012;      // 8進数
int hex = 0x1F;     // 16進数

文字と文字列のリテラル

文字リテラルは1文字をシングルクォーテーション ' ' で囲みます。
殊文字はエスケープシーケンスを使います。

char c = 'A';
char newline = '\n';

文字列リテラルは " " で囲みます。

String message = "Hello, Java!";

浮動小数点点数リテラル

デフォルトでは double 型になります。float にしたい場合は f を付けます。

double pi = 3.14159;
float rate = 2.5f;

指数表記も可能:

double exp = 1.2e3;  // 1.2 × 10^3 = 1200.0

論理リテラル(Boolean)

boolean isJavaFun = true;
boolean isDifficult = false;

null リテラル

nullは、オブジェクト参照が「何も指していない」ことを示します:

String str = null;

まとめ

リテラルの種類 使用例 説明
整数 10, 0x1F int型、long型のリテラル
浮動小数点 3.14, 2.5f double型、float型のリテラル
文字 'A' char型のリテラル
文字列 "Java" String型のリテラル
論理値 true boolean型のリテラル
null null 参照型に使用される特別な値
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?