banner
NEWS LETTER

java basic

Scroll down

Java基础

概述

第一个Java程序

1
2
3
4
5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

HelloWorld是一个类,文件名必须与类名相同,为HelloWorld.java

打开终端,依次输入

1
javac HelloWorld.java
1
java HelloWorld

会看到终端中输出HelloWorld。

四个概念

  1. 类: 一个模板,描述一类 对象 的行为和状态
  2. 对象: 的一个实例,有状态和行为
  3. 方法: 就是行为,比如逻辑运算,数据修改……
  4. 实例变量: 决定 对象 的状态

example:

20210105-java-object-1.png (880×442) (runoob.com)

Dog 是一个 ,Dog1,Dog2,Dog3是Dog类里的三个 对象 ,eat(),run()等是 方法 ,品种、大小等是 实例变量

第二个Java程序

1
2
3
4
5
6
7
8
9
10
public class MyDog {
String name = "Snoopy";
int age = 3;

public static void main(String[] args) {
MyDog Dog1 = new MyDog();
System.out.println("Name = "+ Dog1.name);
System.out.println("Age = "+ Dog1.age);
}
}

这段代码首先定义了一个 MyDog,然后第二、三行定义了两个 实例变量 ,第五行开始主程序,第六行通过 方法 MyDog()定义了一个 对象 Dog1,第七、八行分别输出Dog1的名字和年龄。

Java内存分配

  • 栈:方法运行时使用的内存
  • 堆:存储对象或者数组,用new创建的
  • 方法区:存储可执行的class文件
  • 本地方法栈:JVM使用操作系统功能时使用
  • 寄存器:CPU使用

基本数据类型

byte

  1. 8位有符号的二进制整数
  2. 取值范围[-128 , 127]默认值为0

short

  1. 16位有符号的二进制整数
  2. 取值范围[-215 , 215 - 1] ,默认值为0

int

  1. 32位有符号的二进制整数
  2. 取值范围[-231 , 231 - 1],默认值为0
  3. 一般的整形变量默认为int类型

long

  1. 64位有符号的二进制整数
  2. 取值范围[-263 , 263 - 1],默认值为0L
  3. “L”理论上不分大小写,但“l”容易与“1”混淆

float

  1. 单精度32位、符合IEEE 754标准的浮点数
  2. 默认值0.0f
  3. 不能表示精确的值

double

  1. 双精度64位、符合IEEE 754标准的浮点数
  2. 默认值0.0d
  3. 浮点数类型默认为double类型
  4. 不能表示精确的值

boolean

  1. 表示1位的信息
  2. 只有两个取值truefalse
  3. 默认为 false

char

  1. 单一16位Unicode字符
  2. 取值范围[\u0000 , \uffff]

变量命名规则

使用有意义的名字,避免关键词

驼峰命名法

除第一个单词外,其余单词首字母大写

  1. 局部变量:小写字母开头
  2. 实例变量:小写字母开头
  3. 静态变量:小写字母开头,或全大写,单词间用下划线分割,比如MAX_SIZE
  4. 常量:全大写,单词间下划线分割
  5. 参数:小写字母开头
  6. 类名:大写字母开头

修饰符

访问控制修饰符

  1. default:默认,同一包内可见
  2. private:同一类可见,不能修饰类(外部类)
  3. public:所有类可见
  4. protected:同一包内的类和子类可见,不能修饰类(外部类)

非访问修饰符

  1. static:声明静态变量静态方法,不可声明局部变量
  2. final:修饰变量的值无法改变,且必须显式指定初始值
  3. abstract:不可实例化对象
  4. synchronized:声明的方法只能被一个线程访问,可用于四个访问修饰符
  5. transient:预处理类和变量的数据类型
  6. volatile:统一不同线程中,修饰的变量的值

运算符

算数运算符

1
int a = 15, b = 5;
运算符 example
+(加法) a + b = 20
-(减法) a - b = 10
*(乘法) a * b = 75
/(除法) a / b = 3
%(取余) a % b = 0
++(自增) a++ = 16 ; ++a = 16
–(自减) a– = 14 ; –a = 14

PS. 前缀自增/减,先进行算术运算,后赋值运算。后缀自增/减先赋值运算后算数运算

1
2
3
4
5
6
7
8
9
10
11
12
public class Test {

public static void main(String[] args) {
int a = 15;
int b = 5;
System.out.println("a + b = " + (a + b) ); // 20
System.out.println("a - b = " + (a - b) ); // 10
System.out.println("a * b = " + (a * b) ); // 75
System.out.println("a / b = " + (a / b) ); // 3
System.out.println("a % b = " + (a % b) ); // 0
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class selfAddMinus{
public static void main(String[] args){
int a = 3; //定义一个变量;
int b = ++a; //前缀自增运算
int c = a++; //后缀自增运算
int d = --a; //前缀自减运算
int e = a--; //后缀自减运算
System.out.println(b); // 4
System.out.println(c); // 3
System.out.println(d); // 2
System.out.println(e); // 3
}
}

关系运算符

1
int a = 15, b = 5;
运算符 example
==(相等) (a == b) = false
!=(不相等) (a != b) = true
>(大于) (a > b) = true
<(小于) (a < b) = false
>=(大于等于) (a >= b) = true
<=(小于等于) (a <= b) = false
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {

public static void main(String[] args) {
int a = 15;
int b = 5;
System.out.println("a == b = " + (a == b) ); // false
System.out.println("a != b = " + (a != b) ); //true
System.out.println("a > b = " + (a > b) ); //true
System.out.println("a < b = " + (a < b) ); //false
System.out.println("b >= a = " + (b >= a) ); //false
System.out.println("b <= a = " + (b <= a) ); //true
}
}

位运算符

1
2
A = 0011 1100
B = 0000 1101
运算符 描述 example
& 相对应位都是1,则结果为1 (A&B) = 0000 1100
| 相对应位都是0,则结果为0 (A|B) = 0011 1101
^ 相对应位值相同,则结果为0 (A^B) = 0011 0001
~ 翻转操作数的每一位,即0变成1,1变成0 (~A) = - 1100 0011
<< 左操作数按位左移右操作数指定的位数 (A<<2) = 1111 0000
>> 左操作数按位右移右操作数指定的位数 (A>>2) = 1111
>>> 左操作数的值按右操作数指定的位数右移,移动得到的空位以零填充 (A>>>2) = 0000 1111
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Test {
  public static void main(String[] args) {
    int a = 60; /* 60 = 0011 1100 */ 
     int b = 13; /* 13 = 0000 1101 */
     int c = 0;
     c = a & b;       /* 12 = 0000 1100 */
     System.out.println("a & b = " + c );

     c = a | b;       /* 61 = 0011 1101 */
     System.out.println("a | b = " + c );

     c = a ^ b;       /* 49 = 0011 0001 */
     System.out.println("a ^ b = " + c );

     c = ~a;          /*-61 = 1100 0011 */
     System.out.println("~a = " + c );

     c = a << 2;     /* 240 = 1111 0000 */
     System.out.println("a << 2 = " + c );

     c = a >> 2;     /* 15 = 1111 */
     System.out.println("a >> 2  = " + c );
  
   c = a >>> 2;     /* 15 = 0000 1111 */
     System.out.println("a >>> 2 = " + c );
  }
}

逻辑运算符

1
boolean A = true, B = false
运算符 描述 example
&& 逻辑与,同真则真 (A && B) = false
|| 逻辑或,同假则假 (A || B ) = true
逻辑非,反转真假 (!A) = false ; (!B) = true
1
2
3
4
5
6
7
8
9
public class Test {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a && b)); //false
System.out.println("a || b = " + (a || b) ); //true
System.out.println("!(a && b) = " + !(a && b)); //true
}
}

赋值运算符

运算符 运算符
= <<=
+= >>=
-= &=
*= ^=
/= |=
(%)=

PS. 右侧变量算数运算或位运算结束后赋值给左侧变量,右侧变量值不变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c ); // 30
c += a ;
System.out.println("c += a  = " + c ); // 40
c -= a ;
System.out.println("c -= a = " + c ); // 30
c *= a ;
System.out.println("c *= a = " + c ); // 300
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c ); // 1
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a  = " + c ); // 5
c <<= 2 ;
System.out.println("c <<= 2 = " + c ); // 20
c >>= 2 ;
System.out.println("c >>= 2 = " + c ); // 5
c >>= 2 ;
System.out.println("c >>= 2 = " + c ); // 1
c &= a ;
System.out.println("c &= a = " + c ); // 0
c ^= a ;
System.out.println("c ^= a = " + c ); // 10
c |= a ;
System.out.println("c |= a = " + c ); // 10
}
}

条件运算符(?:)

variable x = (expression) ? value /if true/ : value /if false/

1
2
3
4
5
6
7
8
9
10
11
12
public class Test {
public static void main(String[] args){
int a , b;
a = 10;
// 如果 a 等于 1 成立,则设置 b 为 20,否则为 30
b = (a == 1) ? 20 : 30;
System.out.println( "Value of b is : " + b ); // 30

b = (a == 10) ? 20 : 30;
System.out.println( "Value of b is : " + b ); // 20
}
}

instanceof运算符

检查该对象是否是一个特定类型(类类型或接口类型)

( Object reference variable ) instanceof (class/interface type)

1
2
3
4
5
6
7
8
9
10
11
12
class Vehicle {}

public class Car extends Vehicle {
public static void main(String[] args){
String name = "James";
boolean result = name instanceof String;
System.out.println(result); //true
Vehicle a = new Car();
result = a instanceof Car;
System.out.println(result); //true
}
}

语法结构

判断结构

  1. if条件判断

    1
    2
    3
    4
    5
    6
    7
    if (/*condition*/) {
    /*do1*/
    }else if (/*condition*/) {
    /*do2*/
    }else {
    /*do3*/
    }
  2. switch选择判断

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    switch (/*expression*/) {
    case value1:
    /*do1*/
    break;
    case value2:
    /*do2*/
    break;
    ……
    default:
    /*don*/
    break;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    switch (/*expression*/) {
    case value1 -> {
    /*do1*/
    }
    case value2 -> {
    /*do2*/
    }
    ......
    default -> {
    /*don*/
    }
    }

循环结构

  1. for循环

    1
    2
    3
    for (int i = 1; i <= 10; i++) {
    /*do*/
    }
  2. while循环

    1
    2
    3
    while (/*condition*/) {
    /*do*/
    } //先判断后执行
  3. do…while循环

    1
    2
    3
    do {
    /*do*/
    } while (/*condition*/) //先执行后判断
  4. 跳转控制语句

    • continue:跳出当次循环,执行下次循环
    • break:退出整个循环

数组

数组初始化

  1. 静态初始化

    数据类型[] 数组名 = new 数据类型[] {元素1,元素2,元素3...};

    1
    2
    int[] array1 = new int[] {1, 2, 3};
    int[] array2 = {1, 2, 3};
  2. 动态初始化

    数据类型[] 数组名 = new 数据类型[数组长度];

    1
    int[] arr = new int[3];

    数组默认初始化值:

    • 整数类型:0
    • 小数类型:0.0
    • 字符类型:‘/u0000’ 空格
    • 布尔类型:false
    • 引用数据类型:null

数组的地址与元素访问

  1. 数组的地址

    1
    2
    int[] arr = {1, 2, 3};
    System.out.println(arr); // [I@6d03e736

    “I”是数组类型,“6d03e736”是数组在内存中的位置

  2. 元素访问

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    int[] arr = {1, 2, 3};

    System.out.println(arr[0]); // 1
    System.out.println(arr[1]); // 2
    System.out.println(arr[2]); // 3

    //获取
    int num = arr[0];
    System.out.println(num); // 1

    //存储
    arr[0] = 10;
    System.out.println(arr[0]); // 10

数组的内存图

  1. 各自指向不同空间

    1
    2
    int[] arr1 = new int[2];
    int[] arr2 = new int[2];

    此时arr1和arr2通过new在堆内存中占用两个内存空间。arr1和arr2相互独立。

  2. 指向同一空间

    1
    2
    int[] arr1 = new int[2];
    int[] arr2 = arr1;

    这段代码中,arr1通过new在堆内存中占据空间。但是arr2并没有使用new方法,而是指向了arr1的空间,共用同一个内存空间。arr1的值改变,arr2的值也会改变。

方法

方法的定义

  1. 简单方法定义

    1
    2
    3
    4
    5
    public static void 方法名() {
    /*方法体*/
    }

    方法名(); //调用
  2. 带参数的方法定义

    1
    2
    3
    4
    5
    public static void 方法名(参数数据类型 参数, ...) {
    /*方法体*/
    }

    方法名(参数数据类型 参数, ...); //调用
  3. 带返回值得到方法定义

    1
    2
    3
    4
    public static 返回值类型 方法名 (参数数据类型 参数, ...) {
    /*方法体*/
    return 返回值;
    }

方法的重载

同一个类中,方法名相同,参数(个数,类型,顺序)不同。一般将同类操作的方法定义为同一方法名。

注意点

方法调用时存储在栈内存,内部的参数,也在栈内存。调用结束后,内存全部释放。因此:

  1. 传递基本数据类型时,传递的是真实的数据,形参的改变,不影响实际参数的值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public class Test1 {
    public static void main(String[] args) {
    int num = 100;
    sout(num); // 100

    change1(num);
    sout(num); // 100

    num = change2(num);
    sout(num); // 200
    }

    public static void change1(int num) {
    num = 200;
    }

    public static int change2(int num) {
    num = 200;
    return num;
    }
    }
  2. 传递引用数据类型时,传递的是地址值,形参的改变,影响实际参数的值

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class Test2 {
    public static void main(String[] args) {
    int[] arr = {1, 2, 3};
    sout(arr[1]); // 100

    change1(arr[1]);
    sout(arr[1]); // 200
    }

    public static void change1(int[] arr) {
    arr[1] = 200;
    }
    }

标准的JavaBean类

要求

  1. 类名要见名知意
  2. 成员变量使用private修饰
  3. 提供至少两个构造方法
    • 无参构造方法
    • 带全部参数的构造方法
  4. 成员方法
    • 提供每一个成员变量对应的setXxx() / getXxx()
    • 其他行为

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package myPackage001;

public class User {
//成员变量
private String username;
private String password;
private int age;

//无参构造方法
public User() {}

//带全部参数的构造方法
public User(String username, String password, int age) {
this.username = username;
this.password = password;
this.age = age;
}

//每个变量的getXxx()和setXxx()
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

字符串

构造

  • 直接赋值

    1
    2
    String s1 = "abc"
    System.out.println(s1); //abc
  • new方法构造

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    //空参构造
    String s2 = new String();
    System.out.println(s2); //""

    //传递字符串
    String s3 = new String("abc");
    System.out.println(s3); //"abc"

    //传递字符数组
    char[] chs = {'a', 'b', 'c', 'd'};
    String s4 = new String(chs);
    System.out.println(s4); //"abcd"

    //传递字节数组
    byte[] bytes = {97, 98, 99, 100};
    Strings s5 = new String(bytes);
    System.out.println(s5); //"abcd"

比较

  • ==

    基本数据类型比较的是值,引用数据类型比较的是地址值

    1
    2
    3
    4
    5
    6
    7
    8
    String s1 = new String("abc");
    String s2 = new String("abc");
    String s3 = "abc";
    String s4 = "abc";

    System.out.println(s1 == s2); //false
    System.out.println(s1 == s3); //false
    System.out.println(s3 == s4); //true
  • 方法

    1. boolean equals() 完全一样为true

      1
      2
      3
      4
      5
      6
      String s1 = "abc";
      String s2 = "abc";
      String s3 = "ABC";

      System.out.println(s1.equals(s2)); //true
      System.out.println(s1.equals(s3)); //false
    2. boolean equalsIgnoreCase() 忽略大小写

      1
      2
      3
      4
      5
      6
      String s1 = "abc";
      String s2 = "abc";
      String s3 = "ABC";

      System.out.println(s1.equalsIgnoreCase(s2)); //true
      System.out.println(s1.equalsIgnoreCase(s3)); //true

遍历

  • 方法
    1. char charAt(int index) 根据索引返回字符
    2. int length() 返回字符串的长度

拼接

1
2
3
4
5
String a = "a";
String b = "b";
String c = a + b;

System.out.println(c); //"ab"

逆序

1
2
3
4
5
6
7
public static String reverser(String s) {
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result += s.charAt(i);
}
return result;
}

截取

1
2
3
4
5
6
7
String a = "0123456789";

String b = a.substring(0, 3);
System.out.println(b); //"012"

String c = a.substring(7);
System.out.println(c); //"789"

替换

1
2
3
String a = "123"
String b = a.replace("2", "1");
System.out.println(b); //"113"

StringBuilder

构造方法

  • public StringBuilder():创建空白可变字符串对象
  • public StringBuilder(String str):根据字符串str内容,创建可变字符串对象

常用方法

  • public StringBuilder append(任意数据类型):容器末尾添加数据,返回对象本身
  • public StringBuilder reverse():反转容器中的内容
  • public int length():返回长度
  • public String toString():把StringBuilder转化为String
  • public String insert(index, String[]):索引位置插入字符
  • public String delete(index1, index2):删除 索引1索引2 之间的字符(不包含两端)

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class RunoobTest{
public static void main(String args[]){
StringBuilder sb = new StringBuilder(10);
sb.append("Runoob..");
System.out.println(sb); //Runoob..

sb.append("!");
System.out.println(sb); //Runoob..!

sb.insert(8, "Java");
System.out.println(sb); //Runoob..Java!

sb.delete(5,8);
System.out.println(sb); //RunoobJava!
}
}

StringBuffer

与StringBuilder99%相似,区别在于:

  1. StringBuilder 的方法不是线程安全的(不能同步访问)
  2. StringBuilder 相较于 StringBuffer 有速度优势
  3. 一般使用StringBuilder
其他文章
cover
排序
  • 24/06/27
  • 09:39
  • 数据结构
目录导航 置顶
  1. 1. Java基础
    1. 1.1. 概述
      1. 1.1.1. 第一个Java程序
      2. 1.1.2. 四个概念
      3. 1.1.3. 第二个Java程序
      4. 1.1.4. Java内存分配
    2. 1.2. 基本数据类型
      1. 1.2.1. byte
      2. 1.2.2. short
      3. 1.2.3. int
      4. 1.2.4. long
      5. 1.2.5. float
      6. 1.2.6. double
      7. 1.2.7. boolean
      8. 1.2.8. char
    3. 1.3. 变量命名规则
      1. 1.3.1. 驼峰命名法
    4. 1.4. 修饰符
      1. 1.4.1. 访问控制修饰符
      2. 1.4.2. 非访问修饰符
    5. 1.5. 运算符
      1. 1.5.1. 算数运算符
      2. 1.5.2. 关系运算符
      3. 1.5.3. 位运算符
      4. 1.5.4. 逻辑运算符
      5. 1.5.5. 赋值运算符
      6. 1.5.6. 条件运算符(?:)
      7. 1.5.7. instanceof运算符
    6. 1.6. 语法结构
      1. 1.6.1. 判断结构
      2. 1.6.2. 循环结构
    7. 1.7. 数组
      1. 1.7.1. 数组初始化
      2. 1.7.2. 数组的地址与元素访问
      3. 1.7.3. 数组的内存图
    8. 1.8. 方法
      1. 1.8.1. 方法的定义
      2. 1.8.2. 方法的重载
      3. 1.8.3. 注意点
    9. 1.9. 标准的JavaBean类
      1. 1.9.1. 要求
      2. 1.9.2. Example
    10. 1.10. 字符串
      1. 1.10.1. 构造
      2. 1.10.2. 比较
      3. 1.10.3. 遍历
      4. 1.10.4. 拼接
      5. 1.10.5. 逆序
      6. 1.10.6. 截取
      7. 1.10.7. 替换
    11. 1.11. StringBuilder
      1. 1.11.1. 构造方法
      2. 1.11.2. 常用方法
      3. 1.11.3. example
    12. 1.12. StringBuffer
请输入关键词进行搜索