java之基础语法(中)

java常量
声明时必须赋值,常量名在计算机领域要求全部大写

final int AGE = 18; 

变量作用域

{
int i = 6;
}
System.out.println(i); 此行错误,i变量作用域在{}内。

数据类型 byte 1字节   -128~127

short 2字节   -32768~32767

int 4字节      -2147483648~2147483647

long 8字节     -2^63~2^63-1

float 4字节      1.4e-45f~3.4e+38f

double 8字节    4.9e-324~1.8E+308

char 2字节

boolean 1字节    true或false

基本的数据类型 int long byte double boolean
整型
long
long m = 24;
int
int i = 1000;
short
short s = 5;
byte
byte i = 3;

byte cc = .3; 错误
byte num = 300;//-128 - 127

双精度
float
float f = 6.56;
double
double m = 6.56;
字符型
char
char c = 'a';
char a = 97;
int n = 'A';
1和0 二进制
布尔型 true 真 false 假
2 == 2 条件成立 结果真 true
2 == 3 条件不成立 结果假 false
boolean
boolean f = true; //false


long age = 18;
int age = 18;

byte age = 150;

java数据类型转换
自动转换 隐式转换

double d = 10;
(byte,short,char)--int--long--float—double。

强制类型转换
short s = 5;

byte a = s;
short s = 5;
byte a = (byte)s; //强制类型转换
String num = "abc";

运算符共分以下几种:

算术运算符

赋值运算符

比较运算符

逻辑运算符

位运算符

运算符:是一种特殊符号,用以表示数据的运算、赋值和比较。
表达式:使用运算符将运算数据连接起来的符合Java语法规则的式子。

int i = 3 * 6;

算术运算符 赋值运算
public class User {
public static void main(String[] args) {
// System.out.println("hello 3 * 3 = " + (3 * 3));

System.out.println(2 + 3);// 5
System.out.println(2 - 3);// -1
System.out.println(2 * 3);// 6
System.out.println(2 / 3);// 0
System.out.println((int) 0.6666);// 0
System.out.println(2.0 / 3);// 0.66666666
System.out.printf("%.2f\n", 2.0 / 3);// 0.67 四舍五入保留两位小数
System.out.println(6 / 3);// 2
System.out.println(6 / 4);// 1
System.out.println(6 % 4);// 2 求余数
// System.out.println(6/0); 有异常

String name = "李四";
System.out.println("欢迎:" + name);

//++ --
int a = 6;
a = a + 3;
a += 2;//有点像 a = a+2;
int y = a++;//自身+1 //y=11 a=12
int n = ++a;
System.out.println(a);
System.out.println(n);



}
}

public class OperaTest {
public static void main(String[] args) {
int a = 0;
++a;
a += 2;
int b = a--;// b=3 a=2
System.out.printf("a = %d\n", a--);// 2 a = 1
System.out.printf("b = %d\n", ++b);// 4
System.out.printf("a = %d,b = %d\n", a, b);
}
}


小拓展

class MathTest{
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
if (a % b == 0) {
//System.out.printf("%d ÷ %d = %d\n", a, b, a / b);//格式化输出
System.out.println(a + " ÷ " + b + " = " + a/b);
} else {
System.out.printf("%d ÷ %d = %d …… %d\n", a, b, a / b, a % b);
}
}
}

猜你喜欢

转载自www.cnblogs.com/jinjinqiao/p/12919055.html