Java语法和C/C++很是类似,比如
- 注释
- 变量名以及它的定义和初始化
- 大部分关键字
- 控制流(if,else,for,while,do while,…)
- etc.
变量的定义
首先我们先看一下Java的原始数据类型:
type | description |
---|---|
boolean | true or false |
char | 16 bit character, coded using Unicode 1.1.5 |
byte | 8 bit signed integer, using 2’s complement |
short | 16 bit signed integer, using 2’s complement |
int | 32 bit signed integer, using 2’s complement |
long | 64 bit signed integer, using 2’s complement |
float | floating point real number, 32 bit IEEE 754-1985 |
double | floating point real number, 64 bit IEEE 754-1985 |
变量的定义包括三个部分:修饰符(比如public),类型,变量列表,
其中修饰符是可选的。
Example:
public int a, b, c; // "public" is a modifier
数组
在Java中的数组和C语言中的数组的声明语句不太一样。如果我们要声明一个整数数组,我们可以写成
int [] a
,这里a
就是这个数组的引用。
为了创建数组,我们还需要new一下:
int []a=new int [3]
Example: Table initialisation and index exceptions (compiled and run)
public class Main {
public static void main(String argv[]) {
int i; int[] itab1 = {10, 20, 30};
// Table initialisation.
for ( i = 0 ; i <itab1.length ; i++ )
System.out.println(itab1[i]);
// Create an "IndexOutOfBoundsException" here.
for ( i = 0 ; i <=itab1.length ; i++ )
System.out.println(itab1[i]);
System.out.println("We got away from the Exception!");
}
}
在这个例子中,我们可以发现,Java的数组有自带length
方法,而且它的索引(index)也是和C语言一样,从0到length-1,所以上面的第二个循环就数组越界,抛出了异常。
Control flow
Flow controls which have an identical syntax to that of “C” are:
- if-else
- switch-case
- while
- do-while
- for
- break, continue, return
但是,这里Java有一点和C语言不太相同,就是labelled break语法:
Example
public class Labelled_break {
public static void main(String[]args) {
brkpnt:for(int i=0;i<10;i++) {
for(int j=0;j<10;j++) {
if(j==3) break brkpnt;
System.out.println(i+" "+j);
}
}
}
}
Programming style
- Indentation.
- Class names (ThisIsAClassName).
- Constant names (THIS_IS_A_CONSTANT).
- Class variable/field names (thisIsAClassMemberVariable).
- Method names (thisIsAMethodName).
- Function parameter names (thisIsAFunctionParameter).
- Local variable names (this_is_a_local_variable). This does not seem to be used by Sun, but is highly recommended to increase program readability.
- Comments (class and method definitions, documentation comments).