基础语法
基础语法
基本数据类型
- 内置数据类型
| 类型 | 字节数 | 最小值 | 最大值 | 是否有符号位 |
|---|---|---|---|---|
| boolean | 1bit | None | None | 否 |
| byte | 1 | -2^7 = Byte.MIN_VALUE | 2^7-1 = Byte.MAX_VALUE | 有 |
| char | 2 | ‘\u0000’=0=Character.MIN_VALUE | ‘\uFFFF’=2^15*2-1=65535=Character.MAX_VALUE | 否 |
| short | 2 | -2^15=Short.MIN_VALUE (-32768) | 2^15-1=Short.MAX_VALUE (32767) | 是 |
| int | 4 | -2^31=Integer.MIN_VALUE (-21亿) | 2^31-1=Integer.MAX_VALUE (21亿) | 是 |
| long | 8 | -2^63=Long.MIN_VALUE (-922千亿) | 2^63-1=Long.MAX_VALUE(922千亿) | 是 |
| float | 4 | 1.4E-45f=Float.MIN_VALUE | 3.4028235E38=Float.MAX_VALUE | 是 |
| double | 8 | 4.9E-324=Double.MIN_VALUE | 1.7976931348623157E308==Double.MAX_VALUE | 是 |
| 类型 | 字节数 | 默认值 | 包装类 | 备注 |
|---|---|---|---|---|
| boolean | 1 或4 | false | Boolean | boolean类型无法和其他类型直接转换,单个boolean占4字节,boolean数组里的boolean占1字节 |
| byte | 1 | 0 | Byte | IO流中经常使用 |
| char | 2 | ‘\u0000’ | Character | |
| short | 2 | 0 | Short | 历史遗留类型,不再被使用 |
| int | 4 | 0 | Integer | |
| long | 8 | 0 | Long | 在int无法存储的情况下使用 |
| float | 4 | 0.0f | Float | 在对内存要求高对精度要求不高时使用 |
| double | 8 | 0.0d | Double |
-
注意点
- float:(占4字节)可以精确到6位有效数字,可能精确到7位有效数字,赋值时需要在值后面添加F或f
- double:(占8字节)可以精确到15位有效数字,可能精确到16位有效数字,是浮点数的默认数据类型
- 浮点类型不能用于比较,因为精度丢失,都不能用于表示精确的值,如货币
-
浮点类型比比较,对于浮点数,我们无法使用
==或者包装类型的equals()来精确比较。-
// 对f1执行11次加0.1的操作 float f1 = 0.0f; for (int i = 0; i < 11; i++) { f1 += 0.1f; } // f2是0.1*11的结果 float f2 = 0.1f * 11; System.out.println(f1 == f2); // 结果为false // output : f1 = 1.1000001, f2 = 1.1, 可以看到,在浮点数的运算过程中,确实出现了精度问题。 -
解决方法
- 规定误差范围,尽管无法做到精确比较,但是我们可以确定一个误差范围,当小于这个误差范围的时候就认为这两个浮点数相等。例如:
final float THRESHOLD = 0.000001; // 设置最大误差不超过0.000001 float f1 = 0.0f; for (int i = 0; i < 11; i++) { f1 += 0.1f; } float f2 = 0.1f * 11; if (Math.abs(f1 - f2) < THRESHOLD) { System.out.println("f1 equals f2"); }- 使用BigDecimal,
BigDecimal是一个不可变的、能够表示大的十进制整数的对象。注意使用BigDecimal时,要使用参数为String的构造方法,而不要使用参数为double的构造方法,防止产生精度丢失。使用BigDecimal进行运算,使用它的compareTo()方法比较即可。
private void compareByBigDecimal() { BigDecimal f1 = new BigDecimal("0.0"); BigDecimal pointOne = new BigDecimal("0.1"); for (int i = 0; i < 11; i++) { f1 = f1.add(pointOne); } BigDecimal f2 = new BigDecimal("0.1"); BigDecimal eleven = new BigDecimal("11"); f2 = f2.multiply(eleven); System.out.println("f1 = " + f1); System.out.println("f2 = " + f2); if (f1.compareTo(f2) == 0) { System.out.println("f1 and f2 are equal using BigDecimal"); } else { System.out.println("f1 and f2 are not equal using BigDecimal"); } }
-
-
引用数据类型:对象、数组都是引用数据类型
-
Java常量、进制
final double PI = 3.1415927;
byte a = 68;
char a = 'A'
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
int a = 0b00000001; // 前缀 0 表示 8 进制,而前缀 0x 代表 16 进制, 0b 表示二进制
变量类型
Java语言支持的变量类型有:
- 类变量:独立于方法之外的变量,用 static 修饰。
- 实例变量:独立于方法之外的变量,不过没有 static 修饰。
- 局部变量:类的方法中的变量。
public class Variable{
static int allClicks=0; // 类变量
String str="hello world"; // 实例变量
public void method(){
int i =0; // 局部变量
}
}
-
局部变量
-
局部变量声明在方法、构造方法或者语句块中;
-
局部变量在方法、构造方法、或者语句块被执行的时候创建,当它们执行完成后,变量将会被销毁;
-
访问修饰符不能用于局部变量;
-
局部变量只在声明它的方法、构造方法或者语句块中可见;
-
局部变量是在栈上分配的。
-
局部变量没有默认值,所以局部变量被声明后,必须经过初始化,才可以使用。
-
public void pupAge(){ int age = 0; // yes age = age + 7; System.out.println("小狗的年龄是: " + age); } public void pupAge(){ int age; // wrong age = age + 7; System.out.println("小狗的年龄是 : " + age); }
-
-
实例变量
-
public class Employee{ // 这个实例变量对子类可见 public String name; // 私有变量,仅在该类可见 private double salary; }
-
-
类变量(静态变量)
-
public class Employee { //salary是静态的私有变量 private static double salary; // DEPARTMENT是一个常量 public static final String DEPARTMENT = "开发人员"; public static void main(String[] args){ salary = 10000; System.out.println(DEPARTMENT+"平均工资:"+salary); } }
修饰符
- default (即默认,什么也不写): 在同一包内可见,不使用任何修饰符。使用对象:类、接口、变量、方法。
- private : 在同一类内可见。使用对象:变量、方法。 注意:不能修饰类(外部类)和 接口
- public : 对所有类可见。使用对象:类、接口、变量、方法
- protected : 对同一包内的类和所有子类可见。使用对象:变量、方法。 注意:不能修饰类(外部类)和 接口。
-
| 修饰符 | 当前类 | 同一包内 | 子孙类(同一包) | 子孙类(不同包) | 其他包 |
|---|---|---|---|---|---|
public |
Y | Y | Y | Y | Y |
protected |
Y | Y | Y | Y/N(说明) | N |
default |
Y | Y | Y | N | N |
private |
Y | N | N | N | N |
访问控制和继承
请注意以下方法继承(不了解继承概念的读者可以跳过这里,或者点击 Java继承和多态 预览)的规则:
- 父类中声明为public的方法在子类中也必须为public。
- 父类中声明为protected的方法在子类中要么声明为protected,要么声明为public。不能声明为private。
- 父类中默认修饰符声明的方法,能够在子类中声明为private。
- 父类中声明为private的方法,不能够被继承。
Static
-
static关键字的作用:方便在没有创建对象的情况下来进行调用(方法/变量)
-
静态变量:
static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。
-
静态方法:
static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。
-
使用说明
- 使用static关键字修饰一个属性:声明为static的变量实质上就是全局变量
- 使用static关键字修饰一个方法:在一个类中定义一个方法为static,那就是说,无需本类的对象即可调用此方法(类调用)
- 使用static关键字修饰一个类(内部类)
- 声明为static的方法有以下几条限制:
它们仅能调用其他的static 方法,反过来是可以的。
它们只能访问static数据。
它们不能以任何方式引用this或super。
不允许用来修饰局部变量
abstract
抽象类不能用来实例化对象,声明抽象类的唯一目的是为了将来对该类进行扩充。一个类不能同时被 abstract 和 final 修饰。如果一个类包含抽象方法,那么该类一定要声明为抽象类,否则将出现编译错误。抽象类可以包含抽象方法和非抽象方法。
abstract class Caravan{
private double price;
private String model;
private String year;
public abstract void goFast(); //抽象方法
public abstract void changeColor();
}
输入输出
public class Test1 {
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
System.out.println("请输入名字:");
String next = sca.next();
System.out.println("请输入年龄:");
int i = sca.nextInt();
if (i > 18) {
System.out.println(next + ",恭喜,骑共享汽车");
}else {
System.out.println(next + ",未满18岁,不能骑车");
}
}
}
// 格式化输出
double d = 345.678;
String s = "hello!";
int i = 1234;
//"%"表示进行格式化输出,"%"之后的内容为格式的定义。
System.out.printf("%f",d);//"f"表示格式化输出浮点数。
System.out.printf("%9.2f",d);//"9.2"中的9表示输出的长度,2表示小数点后的位数。
System.out.printf("%+9.2f",d);//"+"表示输出的数带正负号。
System.out.printf("%-9.4f",d);//"-"表示输出的数左对齐(默认为右对齐)。
System.out.printf("%+-9.3f",d);//"+-"表示输出的数带正负号且左对齐。
System.out.printf("%d",i);//"d"表示输出十进制整数。
System.out.printf("%o",i);//"o"表示输出八进制整数。
System.out.printf("%x",i);//"d"表示输出十六进制整数。
System.out.printf("%#x",i);//"d"表示输出带有十六进制标志的整数。
System.out.printf("%s",s);//"d"表示输出字符串。
System.out.printf("输出一个浮点数:%f,一个整数:%d,一个字符串:%s",d,i,s);//可以输出多个变量,注意顺序。
System.out.printf("字符串: %2$s, %1$d的十六进制数:%1$#x", i, s); // "X$"表示第几个变量
Switch ENUM
//switch表达式后面的数据类型只能是byte,short,char,int四种整形类型,枚举类型和java.lang.String类型(从java 7才允许),不能是boolean类型。
//在网上看到好多文章,说switch还支持byte,short,char,int 的包装类,首先可以肯定说switch不支持这些包装类,但是如下的代码又是正确的:
public static void main(String[] args) {
switch (new Integer(45)) {
case 40:
System.out.println("40");
break;
case 45:
System.out.println("45");//将会打印这句
break;
default:
System.out.println("?");
break;
}
}
//原因在于自动拆箱
// 使用方法一
public enum Color {
RED, GREEN, BLANK, YELLOW
}
// 使用方法二
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
// 成员变量
private String name;
private int index;
// 构造方法
private Color(String name, int index) {
this.name = name;
this.index = index;
}
// 普通方法
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
// 其他使用方法 https://blog.csdn.net/mingyuli/article/details/113487078
包装类和Math和Random
public class Test{
public static void main(String[] args){
Integer x = 5; // 装箱 Integer.valueof(x)
x = x + 10; // 拆箱 x.intvalue()
System.out.println(x);
}
}
| 序号 | 方法与描述 |
|---|---|
| 1 | xxxValue() 将 Number 对象转换为xxx数据类型的值并返回。 |
| 2 | compareTo() 将number对象与参数比较。 |
| 3 | equals() 判断number对象是否与参数相等。 |
| 4 | valueOf() 返回一个 Number 对象指定的内置数据类型 |
| 5 | toString() 以字符串形式返回值。 |
| 6 | parseInt() 将字符串解析为int类型。 |
| 7 | abs() 返回参数的绝对值。 |
| 8 | ceil() 返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。 |
| 9 | floor() 返回小于等于(<=)给定参数的最大整数 。 |
| 10 | rint() 返回与参数最接近的整数。返回类型为double。 |
| 11 | round() 它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。 |
| 12 | min() 返回两个参数中的最小值。 |
| 13 | max() 返回两个参数中的最大值。 |
| 14 | exp() 返回自然数底数e的参数次方。 |
| 15 | log() 返回参数的自然数底数的对数值。 |
| 16 | pow() 返回第一个参数的第二个参数次方。 |
| 17 | sqrt() 求参数的算术平方根。 |
| 18 | sin() 求指定double类型参数的正弦值。 |
| 19 | cos() 求指定double类型参数的余弦值。 |
| 20 | tan() 求指定double类型参数的正切值。 |
| 21 | asin() 求指定double类型参数的反正弦值。 |
| 22 | acos() 求指定double类型参数的反余弦值。 |
| 23 | atan() 求指定double类型参数的反正切值。 |
| 24 | atan2() 将笛卡尔坐标转换为极坐标,并返回极坐标的角度值。 |
| 25 | toDegrees() 将参数转化为角度。 |
| 26 | toRadians() 将角度转换为弧度。 |
| 27 | random() 返回一个随机数。 |
public class Test {
public static void main(String[] args) {
Random rand = new Random();
System.out.println("rand.nextBoolean():" + rand.nextBoolean());
// 生成0.0-1.0之间的伪随机double数
System.out.println("rand.nextDouble():" + rand.nextDouble());
// 生成0.0-1.0之间的伪随机float数
System.out.println("rand.nextFloat():" + rand.nextFloat());
// 生成一个处于int整数取值范围的伪随机数
System.out.println("rand.nextInt():" + rand.nextInt());
// 生成0-20之间的伪随机整数
System.out.println("rand.nextInt(20):" + rand.nextInt(20)); // nextInt提供两种方法
// 生成一个处于long整数取值范围的伪随机数
System.out.println("rand.nextLong():" + rand.nextLong());
}
}
| SN(序号) | 方法描述 |
|---|---|
| 1 | char charAt(int index) 返回指定索引处的 char 值。 |
| 2 | int compareTo(Object o) 把这个字符串和另一个对象比较。 |
| 3 | int compareTo(String anotherString) 按字典顺序比较两个字符串。 |
| 4 | int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。 |
| 5 | String concat(String str) 将指定字符串连接到此字符串的结尾。 |
| 6 | boolean contentEquals(StringBuffer sb) 当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。 |
| 7 | [static String copyValueOf(char] data) 返回指定数组中表示该字符序列的 String。 |
| 8 | [static String copyValueOf(char] data, int offset, int count) 返回指定数组中表示该字符序列的 String。 |
| 9 | boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。 |
| 10 | boolean equals(Object anObject) 将此字符串与指定的对象比较。 |
| 11 | boolean equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。 |
| 12 | [byte] getBytes() 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
| 13 | [byte] getBytes(String charsetName) 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
| 14 | [void getChars(int srcBegin, int srcEnd, char] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。 |
| 15 | int hashCode() 返回此字符串的哈希码。 |
| 16 | int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。 |
| 17 | int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 |
| 18 | int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。 |
| 19 | int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 |
| 20 | String intern() 返回字符串对象的规范化表示形式。 |
| 21 | int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。 |
| 22 | int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 |
| 23 | int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。 |
| 24 | int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 |
| 25 | int length() 返回此字符串的长度。 |
| 26 | boolean matches(String regex) 告知此字符串是否匹配给定的正则表达式。 |
| 27 | boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。 |
| 28 | boolean regionMatches(int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。 |
| 29 | String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 |
| 30 | String replaceAll(String regex, String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 |
| 31 | String replaceFirst(String regex, String replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 |
| 32 | [String] split(String regex) 根据给定正则表达式的匹配拆分此字符串。 |
| 33 | [String] split(String regex, int limit) 根据匹配给定的正则表达式来拆分此字符串。 |
| 34 | boolean startsWith(String prefix) 测试此字符串是否以指定的前缀开始。 |
| 35 | boolean startsWith(String prefix, int toffset) 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 |
| 36 | CharSequence subSequence(int beginIndex, int endIndex) 返回一个新的字符序列,它是此序列的一个子序列。 |
| 37 | String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。 |
| 38 | String substring(int beginIndex, int endIndex) 返回一个新字符串,它是此字符串的一个子字符串。 |
| 39 | [char] toCharArray() 将此字符串转换为一个新的字符数组。 |
| 40 | String toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。 |
| 41 | String toLowerCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。 |
| 42 | String toString() 返回此对象本身(它已经是一个字符串!)。 |
| 43 | String toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。 |
| 44 | String toUpperCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。 |
| 45 | String trim() 返回字符串的副本,忽略前导空白和尾部空白。 |
| 46 | static String valueOf(primitive data type x) 返回给定data type类型x参数的字符串表示形式。 |
| 47 | contains(CharSequence chars) 判断是否包含指定的字符系列。 |
| 48 | isEmpty() 判断字符串是否为空。 |
String, String Builder, String Buffer
public class RunoobTest{
public static void main(String args[]){
StringBuilder sb = new StringBuilder(10);
sb.append("Runoob..");
System.out.println(sb);
sb.append("!");
System.out.println(sb);
sb.insert(8, "Java");
System.out.println(sb);
sb.delete(5,8);
System.out.println(sb);
}
}
public class Test{
public static void main(String args[]){
StringBuffer sBuffer = new StringBuffer("hello");
sBuffer.append("www");
sBuffer.append(".runoob");
sBuffer.append(".com"); // hellowww.runoob.com
sBuffer.reverse(); // moc.boonur.wwwolleh
System.out.println(sBuffer);
}
}
Date & Calendar
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
// 解析传入的字符串
Scanner scanner = new Scanner();
String inputString = scanner.nextString();
Date t = ft.parse(inputString);
System.out.println("当前时间为: " + dNow.toString()); // Mon May 04 10:16:34 CDT 2018
System.out.println("当前时间为: " + ft.format(dNow)); // 2018-09-06 10:16:34
}
}
// Calendar类的功能要比Date类强大很多,而且在实现方式上也比Date类要复杂一些
Calendar c1 = Calendar.getInstance();//默认是当前日期
c1.set(2009, 6, 12); // 指定时间的Calendar对象,还有许多set方法
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.DATE,10);
c1.add(Calendar.DATE, 10);
// 获得年份
int year = c1.get(Calendar.YEAR);
// 获得月份
int month = c1.get(Calendar.MONTH) + 1;
// 获得日期
int date = c1.get(Calendar.DATE);
// 获得小时
int hour = c1.get(Calendar.HOUR_OF_DAY);
// 获得分钟
int minute = c1.get(Calendar.MINUTE);
// 获得秒
int second = c1.get(Calendar.SECOND);
// 获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期1、3代表星期二,以此类推)
int day = c1.get(Calendar.DAY_OF_WEEK);

浙公网安备 33010602011771号