| 型 | バイト数 | 範囲 |
| int | 4 | -2G〜2G(Gは109) |
| short | 2 | -32k〜32k |
| long | 8 | 10進19桁 |
| byte | 1 | -128〜127 |
| float | 4 | 最大1038、有効6桁 |
| double | 8 | 最大308桁、有効15桁 |
| char | 2 | unicodeの1文字 |
| () [] | 括弧 |
| ++ -- ~ ! (型) | 増加、減少、ビット反転、キャスト |
| * / % | 乗算、除算、余り |
| + - | 加算、減算 |
| >> << >>> | 右シフト、左シフト、0フィルの右シフト |
| >、 >=、 < 、<= | 比較 |
| == 、!= | 同値、 |
| &、、^ | | 論理積、排他論理和、論理和 |
| && 、|| | 短絡論理演算 |
| ?: | 三項演算 |
| =、+=、 -=、 *-、 /=、 | 代入、演算付代入 |
変数 = 式;
public class exp {
//式、整数、少数の例題
public static void main(String[] args) {
//整数型と少数型の変数を定義
int i;
float x;
//定数の計算
System.out.println("整数割り算 3/5 =" + 3/5);
System.out.println("少数割り算 3.0/5.0 = " + 3.0/5.0);
System.out.println("混合割り算 3/5.0 = " + 3/5.0);
//整数変数の計算
i = 3;
i = i + 3;
System.out.println("代入 i =" + i);
//少数変数の計算
x = 3.0f;
x = x * i;
System.out.println("代入 x =" + x);
}
}
exp.java:15: 精度が落ちている可能性 検出値 : double 期待値 : float x=3.0;
整数割り算 3/5 =0 少数割り算 3.0/5.0 =0.6 混合割り算 3/5.0 =0.6 代入 i =6 代入 x =18.0
double[] acc = new double [100];また、
double acc[] = new double [100];とも宣言できます。
double[][] accd = new double [2][100];初期化は次のように設定します。
double[][] abcd=new double {{10,11,12},{20,21,22}};
ここで、double[i]は、i 列の配列を参照します。したがって、次のように、行毎に異なる列数の配列も指定できます。int [][] odds=new int[NMAX][]; //行のサイズを定める for(n=0;n<NMAX;n++) odds[n]=new int[n+1]; //各列のサイズを定めるなお、文字列の記録には、通常 String クラス(後述)を利用します。
static void fill()(基本型[], 配列名,値); //配列に値を詰める static void sort (基本型[], 配列名); //配列をソートする
条件?値1:値2 :条件によりtrueなら値1、falseなら値2となる「式」です。
if (条件式) 文1 else 文2 ;条件式はboolean型の値を返す必要があります。
switch (式)
case 値1: 文1;
case 値2: 文2;
while(条件式) 文;
do 文 while(条件式);
for(初期設定;条件式 ;繰り返し式 )
continue; //次の繰り返し
break://繰り返し修了
int age=18; String name="mimi" + age;
int l1=name.length();文字列の同値は、eqauls()メソッドで確認できます。これはbooleanの値を返します。次は文字列 command と "hello" を比較します。
例 String command ="abc" ;
command.equals("hello")
同じ文字列領域を共有しているか否かは == で判断できますが、+ 等で演算した文字列は == では判断できません。String s1="abc";boolean b1= (s1 == "abc"); //b1=true; boolean b2= (s1="ab"+"c"); //b2=false
型名 メソッドの名前(引数の並び){ 文 }で定義できます。メソッドを呼び出すことで、そのメソッドの引数に値を渡して、実行することができます。メソッドに static を付加すると、コンパイルされた時点で実行できるメソッドになります。main() は static (コンパイル時に清々される)メソッドにする必要があります。
public class app1{
//add() 関数の定義
static int add(int op1,int op2)
{
return op1+op2;
}
public static void main( String[] args)
{
//calc c2=new calc();
System.out.println(add(2,3));//関数の呼び出し
}
}
class arybound
{
//配列のエラー処理の例
public static void main()
{
int i=0;
try{
int array[]=new int [100];
i=100;
array[i]=10;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("**array index error: "+i);
e.printStackTrace();
}
}
}
class throwEx{
public static void main(String[] arg)
{
try{ work();}
catch(ArrayIndexOutOfBoundsException (e){
//work()関数での異常処理
System.out.println("**array index error**");
e.printStackTrace();
}
}
static void work() throw ArithmeticException{
int array[]=new int [100];
int i=100; array[i]=10;
}