JAVA基础知识总结(二)
常量与数值
定义方式
常量的特点
- 编译时值已确定,运行过程中始终不变
- 类和接口中都可以定义常量
- 全局变量定义用
public static final int MAX_VALUE = 512;
- 只在本类中使用的常定义为 private
- 常量命用大写
常用的数据类型
基本数据类型 | 占字节,位数 | |
---|---|---|
整型 | int | 4,32 |
整型 | long | 8,64 |
整型 | byte | 1,8 |
整型 | short | 2,16 |
浮点型 | float | 4,32 |
浮点型 | double | 8,64 |
布尔型 | ture,false | 1,8 |
字符型 | ‘a’ | 2,16 (unicode) |
字符串型 | “hello” |
变量与数据类型
变量的定义格式
int num =5;
这句话表示在内存中,开辟一块大小为四个字节的区域(具体位置由计算机掌握),并把5对应的二进制码赋值给该区域
int a=3;
int b;
b=a;
开辟两个独立的内存区域,将a中的值复制给b,a的值不变。
标识符
变量与常量的名字称为标识符。
方法名的命名规范:动宾结构,第二个单词开头大写,如getName。
类名的命名规范:名词,每个单词头大写。
int,for,extends,class等为关键字,给变量,方法,类起名字不能用。
原始数据类型与引用数据类型
原始数据类型
共八种,全部小写
short int long float double char byte boolean
引用数据类型
如String,开头大写
包装类
int ->Integer
char->Character
其他原始数据类型直接将首字母大写
double类型精度问题
double类型的小数部分使用1/2,1/4,1/8……,1/2^n的方法近似表示,当计算机的存储区域有限时,小数部分不能无限近似,因此会产生精度问题,出现误差。
处理精度损失可以使用BigDecimal类。
条件语句
if
int a=1,b=2,c=3,d=4;
if(a<b&&c>d)//逻辑与优先级低,先比大小
{c=0;d=0;}
else
c=d=1;
System.out.println("s"+a+b+c+d);//1211
?:表达式
String 变量名=判断语句?“正确时返回值”:“错误时返回值”;
必须为String。
String outcome=a>b?"1":"0";
System.out.println(outcome);
switch语句
switch后面值加括号,case整体加大括号
case 后面不加括号,跟冒号,加处理语句,记得写break
switch (a)
{
case 1:
System.out.println("1");break;
case 2:
System.out.println("2");break;
}
循环语句
do while
执行do,若while满足,继续。
int a = 1, b = 2, c = 3, d = 4;
do
{
d--;
System.out.println(d+"\r\n");
}
while(d>1);//3 2 1
while
while后满足,执行
int a = 1, b = 2, c = 3, d = 4;
while(d>1)
{
d--;
System.out.println(d+"\r\n");//3 2 1
}
for循环
赋循环变量,判断条件,满足执行第三个。
for (int i=0;i<d;i++)
{
System.out.println(i+"\r\n");
}
continue 与 break
continue跳出本次循环,执行下一判断,
break跳出循环。
方法
把方法放进类里,设置为public,即可给别人使用。
把方法放进类里,设置为静态的,类似于C 中的全局变量。
方法的定义=访问权限+static+返回值类型+方法名(入口参数)
public class Main
{
public static void main(String[] args)
{
int a=3;
int b =square(a);
System.out.println(b);
}
public static int square(int a)
{
return a*a;
}
}
方法重载
方法名相同,参数的个数,类型,类型的顺序不同,称为重载。
重载与返回值类型无关。
public class Main
{
public static void main(String[] args)
{
System.out.println(square(3));//9
System.out.println(square(0.3));//0.09
}
public static int square(int a)
{
return a*a;
}
public static double square(double a)
{
return a*a;
}
}
递归
public class Main
{
public static void main(String[] args)
{
System.out.println(repeat(5));//120
}
private static int repeat(int a)
{
if (a<2) //判断什么时候结束
return a;
return a*repeat(a-1);//自己调用自己
}
}