Java基本语法

Java语法和C/C++很是类似,比如

  • 注释
  • 变量名以及它的定义和初始化
  • 大部分关键字
  • 控制流(if,else,for,while,do while,…)
  • etc.

变量的定义

首先我们先看一下Java的原始数据类型:

typedescription
booleantrue or false
char16 bit character, coded using Unicode 1.1.5
byte8 bit signed integer, using 2’s complement
short16 bit signed integer, using 2’s complement
int32 bit signed integer, using 2’s complement
long64 bit signed integer, using 2’s complement
floatfloating point real number, 32 bit IEEE 754-1985
doublefloating 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语法:

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).
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值