快捷按键
- psvm: public static void main(String[] args) { }
- sout: System.out.println();
Java基础语法
注释
- 单行注释://
- 多行注释/* xxxxxxxxxxxxxxxx */
- 文档注释:/** xxxxxxxxxxxx */
标识符
关键字
标识符
- 首字母以字母大小写(a-z,A-Z),美元$或者下划线开始。
- 首字母以后可以是字母,美元,数字,下划线等任何字符组合。
- 不能使用关键字作为类名和方法名。
- 标识符是分大小写的。
数据类型
- 基本类型(primitive type)
- 引用类型(reference type)
类型转换:
低------------------------------------------------------------->高
byte–>short -->char–>int–>long–>float–>double
强制类型转换:由高到低
自动类型转换:由低到高
- 转换的时候可能存在内存溢出或者出现精度问题
(int)23.7 : 23
(int)-45.89f : -45
##操作比较大的数,注意溢出问题。
JDK7特性:数字之间可以使用下划线分割,不会输出。
int money = 1_000_000_000;
int years = 20;
int total = money * years;
System.out.println(total);
total 得出来的值是一个负数,溢出问题
int total3 = money * ((long)years);
total3输出的结果对。
逻辑运算符
自增自减运算符
public class Demo04 {
public static void main(String[] args) {
int a = 3;
int b = a++; // a++ : a = a + 1; 执行完代码后,给B赋值3;然后再自增 (+1),执行完该语句后,a才为4
int c = ++a ;//执行代码前,先自增,再给c赋值。
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
输出结果为:5 3 5
幂运算
2^3 : 222
double pow = Math.pow(2,3);
System.out.println(pow);
逻辑运算符
public class Demo05 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a && b)); // 逻辑与运算,两个变量都为真,结果才为真
System.out.println("a || b:"+(a || b)); // 逻辑或运算,两个变量有一个为真,结果为真
System.out.println("!(a && b):"+!(a && b)); // 逻辑非运算,如果是真,则变为假,如果是假,则变为真。
}
}
a && b:false
a || b:true
!(a && b):true
位运算
A = 0011 1100;
B = 0000 1101;
每位做比较: A的1位和B的1位比较,A的2位和B的2位比较……
A & B : 且 两个都是1才为1,否则为0. 0000 1100
A | B : 或 有一个为1则为1,否则为0。 0011 1101
A ^ B : 亦或 两个相同为0,不相同为1. 0011 0001
~B : 取反 取相反的值 1111 0010
如何最快的计算 2 * 8
2 * 8 = 2 * 2 * 2 * 2
<< :左移 *2 ; >>:右移 / 2
二进制
0000 0000 :0
0000 0001: 1
0000 0010:2
0000 0011:3
0000 0100:4
0000 1000:8
0001 0000:16
System.out.println(2<<3);
进制
拓展和条件运算符
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+= b; //a = a+b
System.out.println(a);
System.out.println("-----------------------------------------------------------");
//字符串连接符
System.out.println(a+b);
System.out.println(""+a+b);
System.out.println(a+b+""); //
System.out.println("-------------------------------------------------------------");
//三元运算符
//x ? y : z 如果x的值为true,则x的值为y,反之为z
int score = 99;
String type =score<60 ? “不及格”:“及格”;
System.out.println(type);
}
视频地址:https://www.bilibili.com/read/cv5702420/