Java 基础知识——基础语法

Java基础语法

一、基本概念

  1. JDK,JRE,JVM 之间的关系
    JVMJava 虚拟机。解释器将 Java 代码.java文件编译成 Java 字节码.class文件(中间代码)。
    JREJava 运行时环境。在JVM的基础上配上 Java 核心类库。
    JDKJava 开发工具包。在 JRE 的基础上配上一些编译、调试工具、基础类库等,提供了大量的应用程序编程接口(API)。

在这里插入图片描述

  1. Java 代码编译和运行过程
    编写源程序代码 .java → 经过编译生成 Java 字节码 .class → 转换成各个平台自己的机器语言运行在不同平台
  2. Java版本
    Java SE:Java 标准版,Java 技术的核心和基础,主要用于开发桌面应用程序。
    Java ME:Java 微型版,可以为在移动设备和嵌入式设备上运行的应用程序提供灵活的环境。
    Java EE:Java企业版,提供了企业级应用开发的完整解决方案。
二、Java 基础语法
  1. 注释

    单行注释: //
    块注释:/* */
    文档注释:/ ** */

  2. 常量和变量

    ○ 标识符命名规则

    由字母、数字、下划线、$ 符组成,开头不能为数字;区分大小写;不可使用关键字。

    常量

    java中,用final定义常量,一经赋值不可改变。定义格式如下

    final datat_type var_name= value;
    

    常量定义举例:

    final double PI = 3.1415936;
    final boolean FlAG = true;
    

    变量

    Java 数据类型分为基本数据类型引用数据类型

    基本数据类型包括:

    整形:byte、short、int、long
    浮点型:float、double
    字符型:char
    布尔型:boolean

    引用数据类型包括:

    类(class)、接口(interface)、数组、枚举(enum)、注解(Annotation)

    类型字节数范围举例
    byte1 字节-128 ~ 127(-27 ~ 27-1)byte a = 123
    short2 字节-32768 ~ 32767(-215 ~ 215-1)short b = 12345
    int4 字节-2147483648 ~ +2147483647(-231 ~ 231-1)int c = 123456789
    long8 字节-263 ~ 263-1long d = 123456723423432L
    float4 字节3.4e-38 ~ 3.4e+38float e = 1.2F
    double8 字节1.7e-38 ~ 1.7e+38double f = 1.2, g = 1.2D
    boolean1true / falseboolean f = false
    char20 ~ 216-1char c = ‘A’

    注:java 默认浮点型为 double 型,若是定义 float 型应标明 float a = 1.2f,或者强制类型转换(float)1.2f

  3. Java 中数据类型转换

    分为自动转换强制转换

    ○ 自动类型转换:数据宽度小→数据宽度大。如下图:虚线代表的转换可能会丢失精度
    在这里插入图片描述

    ○ 强制类型转换:数据宽度大→数据宽度小。 强制类型转换可能会使数据溢出或丢失精度

    int i = 10;
    byte j = (byte) i;
    
  4. Java 的输入与输出

    ○ 输入

    法一: Scanner a = new Scanner(System.in);

    System.out.println("请输入a与b的值:");
    Scanner a = new Scanner(System.in);
    Scanner b = new Scanner(System.in);
    String str1 = a.next();
    String str2 = b.nextLine();
    System.out.println("a 的值为"+ str1);
    System.out.println("b 的值为"+ str2);
    

    next()nextLine() 均可读入字符串,但前者不可读入空格,后者可以 ,控制台输出如下:

    请输入a与b的值:
    hello world
    hello world
    a 的值为hello
    b 的值为hello world

    法二:BufferedReader 输入规模较大时使用,注意需要抛出异常

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    int x = br.read();
    System.out.println(str);
    System.out.println(x);
    

    read()readLine()控制台输出如下:

    hello world
    a
    hello world
    97

    ○ 输出

    法一:

    System.out.print("a 的值为"+ str1); 				// 1. 不带回车输出
    System.out.println("a 的值为"+ str1); 				// 2. 带回车输出
    System.out.printf("%.2f %04d\n",3.1414926,12); 		// 3. 格式化输出 3.12  0012
    

    法二:BufferedWriter输入规模较大时使用,注意需要抛出异常

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    bw.write("Hello World\n");
    bw.flush();  										// 一定手动刷新缓冲区
    

    ○ 补充
    Integer.parseInt()splt()

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] strs = br.readLine().split(" ");    		// 按空格切片操作
    int a = Integer.parseInt(strs[0]);                 	// 将输入的字符串转化成整数
    int b = Integer.parseInt(strs[1]);
    System.out.println(a+"和"+b);
    
三、 判断语句
  1. if-else
    C++ python一样
    Scanner sc = new Scanner(System.in);
    int year = sc.nextInt();
    if (year % 100 == 0) {
         if (year % 400 == 0)
             System.out.printf("%d是闰年\n", year);
         else
             System.out.printf("%d不是闰年\n", year);
    } else {
        if (year % 4 == 0)
             System.out.printf("%d是闰年\n", year);
        else
             System.out.printf("%d不是闰年\n", year);
    }
    
  2. switch-case
    switch (day) {
       case 1:
           name = "Monday";
           break;
            ...
       case 7:
           name = "Sunday";
           break;
       default:
           name = "not valid";
    }
    
四、循环语句
  1. while / do while / for

    C++ python一样

    while (i < 5) {
    System.out.println(i);
    i ++ ;
    }
    
    do {
        System.out.println(i);
        i ++ ;
    } while (i < 5);
    
    for (int i = 0; i < 5; i ++ ) {  // 普通循环
        System.out.println(i);
    }
    
    int[] a = {0, 1, 2, 3, 4};
    for (int x: a) {  // forEach循环
        System.out.println(x);
    }
    
五、转移语句
  1. break 跳出本层循环
    ○ 在 switch 语句中用于终止 case 语句
    ○ 在循环语句中用于跳出循环结构
    ○ 与标签语句配合,从内层循环或内层程序块中退出
  2. continue 跳出本次循环
    ○ 跳出满足某条件的单次循环。
  3. return 语句
六、数组
  1. 数组创建

    若未初始化, int 缺省的默认值 为0,boolean 缺省默认值为 false。

    // 1. 数组创建
    int[] array;      					 // 定义声明数组无需说明长度
    array = new int[10];				 // 分配空间,构建时需要定长度
    int[] a = new int[5];				 // 定义并分配空间,长度一但定义不可改变								 	
    int n = 10;
    float[] b = new float[n];		
    
  2. 数组初始化

    ○ 静态初始:定义并赋值

    int[] a = {1, 2, 3 ,4 , 5};
    int[] a = new int[]{1, 2, 3 ,4 , 5};   // 无需写个数,自己按{}个数计算
    char[] c = {'a','b','c'};
    

    ○ 动态初始化:定义与赋值分开

    int[] a = new int[5];
    for (int i = 0; i < 5; i++){
        a[i]=i;
    }
    for (int i = 0; i < 5; i++){
        System.out.println(a[i]);
    }	 	
    
  3. 数组拷贝

    ○ 使用循环语句进行赋值
    ○ 使用 clone() 方法
    ○ 使用 System.arrraycopy() 方法

    【若直接采用 int a = b,赋值的是引用,一方改变另一方会影响】

    char[] c = {'a','b','c'};
    char[] d = c;  						// 赋值的是引用
    System.out.println(c.hashCode());	//输出地址的哈希值:460141958
    System.out.println(d.hashCode());	//输出地址的哈希值:460141958
    
    // 1. 循环语句
    int[] a = {1, 2, 3, 4, 5};
    int[] b = new int[a.length];
    for (int i = 0; i < a.length; i++){
       b [i] = a [i];
    }
    
    //2. clone() 方法
    int[] a = {1, 2, 3, 4, 5};
    int[] b = a.clone();
    
    //3. System.arrraycopy() 方法
    // System.arraycopy(from,index,to,index,count);
    int[] a = {1, 2, 3, 4, 5};
    int[] b = new int[a.length-1];
    System.arraycopy(a,1,b,0,4);
    // b = {2, 3, 4, 5};
    
  4. 二维数组

    // 1. 定义
    int[][] a = new int[5][];       // 至少要指定行数
    // 2. 初始化
    int[][] b = {{1, 2}, {3, 4}, {5, 6}};   // 系统自行判定长度
    // 3. 遍历
    for (int[] x:b) {
       for (int c:x) {
            System.out.println(c);
       }
    }
    // 或者
    for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 2; j++) {
           System.out.println(b[i][j]);
       }
    }
    // 或者
    System.out.println(Arrays.deepToString(b));
    
  5. 补充常用API

    ○ length: 属性,返回数组长度
    ○ Array.sort() :数组排序
    ○ Arrays.fill( int[ ] a,int val ) :填充数组
    ○ Arrays.toString() :将数组转化为字符串
    ○ Arrays.deepToString() :将多维数组转化为字符串

七、字符串类
  1. String 是用 final 修饰的,java 中凡是被 final 修饰的类都不能被继承,也不能被修改,因此String 是只读变量,一经赋值不可改变。
    String 类底层是由 char 数组进行数据存储。

    String a = "Hello World";
    String b = "My name is";
    String x = b; 						 // 存储到了相同地址
    String c = b + "lijiaojiao";  		 // String可以通过加号拼接
    String d = "My age is " + 18;  		 // int会被隐式转化成字符串"18"
    String str = String.format("My age is %d", 18);  // 格式化字符串,类似于C++中的sprintf
    String money_str = "123.45";
    double money = Double.parseDouble(money_str); 	 // String转double
    

    只读变量,不能修改,例如:

    String a = "Hello ";
    a += "World";  // 会构造一个新的字符串
    

    访问String中的字符:

    String str = "Hello World";
    for (int i = 0; i < str.length(); i ++ ) {
        System.out.print(str.charAt(i));  // 只能读取,不能写入
    }
    
  2. String 类常用 API

    length():返回长度。
    split(String regex):分割字符串
    indexOf(char c)、indexOf(String str):查找,找不到返回-1
    equals():判断两个字符串是否相等,注意不能直接用==
    compareTo():判断两个字符串的字典序大小,负数表示小于,0表示相等,正数表示大于
    startsWith():判断是否以某个前缀开头
    endsWith():判断是否以某个后缀结尾
    trim():去掉首位的空白字符
    toLowerCase():全部用小写字符
    toUpperCase():全部用大写字符
    replace(char oldChar, char newChar):替换字符
    replace(String oldRegex, String newRegex):替换字符串
    substring(int beginIndex, int endIndex):返回[beginIndex, endIndex)中的子串

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值