java零碎知识(更新中)
-
类型转换
强制类型转换<手动>(高->低)
自动类型转换<自动>(低->高)
不能对boolean类型进行转换
转换时注意内存溢出或精度问题
低----------------------------------------->高
byte,short,char->int->long->float->double
运算中,不同类型的数据先转化为同一类型,然后进行计算。
int money=10_0000_0000;//下划线不影响输出
int year=20;
int total=money*year;
System.out.println(total);//int类型溢出了导致输出乱码
long total2=money*year;
System.out.println(total2);//仍然会输出乱码,因为year默认为int,转化之前已经存在问题
//解决方案
long total3=money*((long)year);//正确输出
-
变量、常量、作用域
- 变量
public class Variable{
static double salary=2500;//类变量
String str="hello world";//实例变量:从属于对象。不初始化将变为该类型默认值。
//boolean默认值是false
//除了基本数据类型其余默认值为null
String name;
int age;
public void method(){
int i=0;//局部变量:必须声明和初始化值
Variable target=new Varible();
System.out.println(target.age());
//实例变量例子
System.out.println(salary);
//类变量例子
}
}
- 常量
常量是一种特殊的变量,他的值被设定后,在程序运行中不允许被改变
常量名一般使用大写字符
final 常量名=值;
final double PI=3.14;
static final double APPLE=24;//修饰符不区分先后顺序
-
字符串连接符
int a=10;
int b=20;
sout(""+a+b);/1020//这是因为最左侧有字符串,则整个结果都以字符串形式输出
sout(a+b+"");/30//""在右侧则还是先运算
sout(a+b+""+a+b)/301020
sout(a+b+""+a+b+""+a+b+...)/3010201020...
-
三元运算符
x?y:z//如果x为true,则结果为y,否则为z
int score=50;
String type=score<60?"不及格":"及格";
sout(type);/不及格
-
For-Each循环(增强for循环)
for-each 循环(也叫增强 for 循环)是 Java 中简化数组 / 集合遍历的语法糖,核心作用是无需手动控制索引,直接遍历容器中的每一个元素,代码更简洁、可读性更高,且能避免索引越界等问题。
for (元素数据类型 变量名 : 数组/集合对象) {
// 循环体:对变量名(当前遍历的元素)进行操作
}
public class ForEachDemo {
public static void main(String[] args) {
// 定义一个字符串数组
String[] fruits = {"苹果", "香蕉", "橙子", "葡萄"};
// for-each 遍历数组
System.out.println("遍历水果数组:");
for (String fruit : fruits) { // fruit 代表当前遍历到的元素
System.out.println(fruit);
}
// 对比普通 for 循环(需要手动控制索引)
System.out.println("\n普通 for 循环遍历:");
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
}
我本将心向明月,奈何明月照沟渠

浙公网安备 33010602011771号