从零开始学Java (三)基础语法

1. 基本数据类型

  • 整数类型:byte,short,int,long

  • 浮点数类型:float,double

  • 字符类型:char

  • 布尔类型:boolean

  

  java最小单位是bit,一个byte占用8个字节,详情如下:

 整型

 对于整型类型,Java只定义了带符号的整型,因此,最高位的bit表示符号位(0表示正数,1表示负数)。各种整型能表示的最大范围如下:

  • byte:-128 ~ 127
  • short: -32768 ~ 32767
  • int: -2147483648 ~ 2147483647
  • long: -9223372036854775808 ~ 9223372036854775807

 浮点型

  • float3.4x1038
  • double:1.79x10308

 布尔类型

  原则上是1bit,但是jvm没有规定,一般是4字节整数

 字符串

  定义字符串:

1 String str = ""; // 空字符串,包含0个字符
2 String str1 = "A"; // 包含一个字符

  对字符串进行操作:

1 public class Main {
2     public static void main(String[] args) {
3         String str1 = "Hello";
4         String str2 = "world";
5         String s = str1 + " " + str2 + "!";
6         System.out.println(s);
7     }
8 }

  java13新特性:多行字符串

 1 public class Main {
 2     public static void main(String[] args) {
 3         String s = """
 4                    SELECT * FROM
 5                      users
 6                    WHERE id > 100
 7                    ORDER BY name DESC
 8                    """;
 9         System.out.println(s);
10     }
11 }

 常量

  一般用final修饰

1   final double PI = 3.14;

 var关键字

  这两者是一样的,编译器会将前者解释为后者

1 var s = new StringBuilder();
2 StringBuilder sb = new StringBuilder();

 数组

  整型数组:最后的length的长度都是5.

1 int[] score = new int[5];
2 int[] score = new int[] { 68, 79, 91, 85, 62 };
3 int[] score = { 68, 79, 91, 85, 62 };
4 System.out.println(score.length);

  字符串数组

1 String[] names = {
2     "ABC", "XYZ", "zoo"
3 };
原文地址:https://www.cnblogs.com/gaoshaonian/p/11688167.html