第二节 Java基本语言元素

关键字与标识符

关键字

访问控制

private protected public

类,方法和变量修饰符

abstract class extends final implements interface native new
static strictfp synchronized volatile

程序控制

break continue return do while if else for instanceof switch

异常处理

try catche throw throws

包相关

import package

基本类型

boolean byte char double float int long short null true false

变量引用

super this void

保留字

goto const

标识符

标识符规则
  1. 标识符由字母,数字,下划线和$组成
  2. 不能以数字开头
  3. 严格区分大小写
  4. 长度任意
命名规范
包名 类名和接口 变量名和函数名 常量名
多个单词组成,全部小写,例如 com.baidu 多个单词组成,每个单词首字母大写,例如 HelloWorld 多个字母组成,第一个单词小写,其他单词首字母大写,例如 getMax() 多个单词组成,全部大写,用下划线连接,例如 INT_LEFT

变量与数据类型

变量

//变量的声明和赋值
public static void main(String[] args) {
    //创建变量
    int value;
    //创建多个变量
    int val1,val2,val3;


    //为变量赋值
        //先声明后赋值
    String str;
    str="hello world!";
        //声明赋值一步到位
    String string = "hello world!";
    /**
     * 局部变量在使用之前需要赋值,否则无法编译。
     * System.out.println(value);//出错,因为value没有赋值。
     *
     * 默认情况下,实例变量和类变量的初始值取决于其数据类型
     * 数值变量:0
     * 字符变量 '\0'
     * 布尔变量:false
     * 对象:null
     */
}

常量

/**
* 常量
*  主要用于对象共享值
*/
final int LEFT=1;
final int RIGHT=2;
final int UP=3;
final int DOWN=4;

int direction=LEFT;
//上述语句更容易让人理解direction指向左边。

注释

//单行注释

/*
多行注释
*/

/**
* 文档注释
*/ 

数据类型

/**
* 数据类型
*  java一共有八种基本数据类型
*  java有一个特殊类型void
*  java有两种引用类型:类或者接口,数组
*/

数据类型

每种数据类型都有相对应的字面量
其中char类型所对应的字面量除了正常字符之外,还包括转义字符
/**
* 转义字符
* 除了正常的字符外,还有一些非打印字符或者不能通过键盘输入的字符,比如换行
*/
System.out.print("hello");
System.out.print("\n");//打印换行
System.out.print("\t");//打印制表符即tab键的含义
System.out.print("world!");

转义字符

运算符

算术运算符

算术运算符

比较运算符

比较运算符

逻辑运算符

逻辑运算符

位运算符

位运算符

赋值运算符

赋值运算符

运算符优先级

    运算符优先级
        递增递减运算->算术运算符->比较运算->逻辑运算->赋值运算

数组

    //声明数组
    int[] arr;

    //创建数组
    int[] arr = new arr[2];
    arr[0]=1;
    arr[1]=2;

    //创建数组2
    int[] arr={1,2,3,4};

数组的遍历

public class TextArray{
    public static void main(String[] args){
        int[] arr = {0,6,3,,8,2,1,7};
        for(int i = 0;i<arr.length;i++){
            System.out.println("arr["+i+"] = "+arr[i]);
        }
        //foreach
        for(int j : arr){
            System.out.println(j);
        }
    }
}

数组的排序

冒泡排序法
选择排序法

数组获取最大最小值

public class TextArray{
    public static void main(String[] args){
        int[] arr = {0,6,3,,8,2,1,7};
        //求最大值
        int max=arr[0];
        for(int i=1;i<arr.length;i++){
            if(arr[i]>max){
                max=arr[i];
            }
        }
        System.out.println("最大值="+max);
        //求最小值
        int min = arr[0];
        for(int i=1;i<arr.length;i++){
            if(arr[i]<min){
                min=arr[i];
            }
        }
        System.out.println("最小值="+min);
    }
}

猜你喜欢

转载自blog.csdn.net/lay_ko/article/details/79693263