Java速通1:基础知识

479 阅读2分钟

基础知识

1.从java7开始,可以给数字添加下划线 增强可读性

int v1 = 1_0000_0000;
int v2 = 0xFF_EC_DE_5E;
int v3 = 0b11001100_11110000_10101010;
double v4 = 1.23_34_43;
以下方法是错误的:
// 不能在小数点前后使用
double r1 = 1._23;
double r2 = 1_.23;

//不能在数字前后使用
int v1 = _123;
int v2 = 123_;

2.>> 与 >>>

>>:有符号右移(最左用符号位补齐)
>>>:无符号右移动(最左用0补齐)

-128       = 1111111110000000 
-128 >>  2 = 1111111111100000 
-128 >>> 2 = 0011111111100000

3.数据类型

byte: 8bit    [-128, 127]      默认:0                  
short: 16bit  [-32768, 32767] 默认:0
int: 32bit     [-2^31, 2^31-1] 默认:0
long: 64bit    [-2^63, 2^63-1] 默认:0L
float: 32bit   [1.40E-45F, 3.4028235E38F]       默认:0.0F
double: 64bit  [4.9E-324, 1.7976931348623157E] 默认:0.0
boolean: true false  默认:false
char: 16bit的Unicode字符 默认:'\u0000'
// Math类的常用方法
Math.abs(-100);     // 求绝对值 100
Math.max(22, 100);  // 求最大值 100
Math.min(22, 100);  // 求最小值 22
Math.floor(3.5);    // 向下取整 3.0
Math.ceil(3.5);     // 向上取整 4.0
Math.round(3.5);    // 四舍五入 4
Math.pow(4, 2);     // 4的2次方 16.0
Math.sqrt(16);      // 16的平方根 4.0

4.可变参数

public int sum(int... numbers){
    int result = 0;
    for(int num : numbers){
        result += num;
    }
    return result;
}

sum(10, 20, 30);

举例:
System.out.printf("My name is %s, age is %d", name, age);

源码:
public PrintStream printf(String format, Object... args){
    return format(format, args);
}

5.方法参数与返回值

  1. 引用类型作为参数 传递的是地址
  2. 引用类型作为返回值 返回的是地址
public int[] test(){
    int[] t = {11, 22};
    return t;
}

int[] n = test();
test() 方法执行完,{11, 22}在堆内存中的内容不会被GC,因为被n引用了。

6.方法的签名:方法名 + 参数类型

7.方法重载:方法名相同,方法签名不同

8.栈帧(Frame):

  1. 栈帧随着方法的调用而创建,随着方法结束而销毁,存储了方法的局部变量信息。
  2. 栈溢出:Stack Overflow

1-1.png

问:方法存储在哪里?

内存划分:

  1. PC寄存器(Program Counter Register):存储java虚拟机正在执行的字节码指令地址
  2. java虚拟机栈(java Virtual Machine Stack):存储栈帧
  3. 堆(Heap):存储GC所管理的各种对象
  4. 方法区(Method Area):存储每个类的结构信息(比如字段名称和类型,方法的返回值与签名,构造方法和普通方法的字节码等)
  5. 本地方法栈(Native Method Stack):用来支持native方法的调用(比如C语言编写的方法)
  6. 简单对象内存

1-2.png 7. 复杂对象内存

1-3.png 8. 对象数组内存

1-4.png