java基础知识点总结代码实例
package myStudyProject;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.io.*;
public class Study1 {
public static class MyEnum
{
public static final int VAL1 = 0b00000000;
public static final int VAL2 = 0b00000001;
public static final int VAL3 = 0b11111111;
public static final int VAL4 = 0b00000010;
public static final int VAL5 = 0b00000100;
}
private static final int A = 1;//常量的定义
//程序的入口main函数
public static void main(String[] args) {
//1.基础类型
BasicType();
//2.常量
ConstVal();
//3.布尔表达式
BooleanExpress();
//4.算术表达式
MathExpress();
//5.比较运算符表达式
CmpExpress();
//6.位运算符表达式
BitExpress();
//7.运算符优先级
ExpressYouXianJi();
//8.语句
Statement();
//9.方法
Method();
//10.面向对象
ObjectOri();
//11.访问修饰符
VisitedDecorate();
//12.回调接口
CallBack();
//13.数组集合和字典
ArrayCollectionDict();
//14.泛型
Generic();
//15.反射
Reflect();
//16.多线程
MutilThread();
//17.序列化
SeriAnUnSeri();
//18.文件操作
FileOp();
//19.正则表达式
RegexOp();
}
//1.基础数据类型和变量(隐式类型(java10+)和动态类型(没有))
public static void BasicType() {
//1.char是unicode编码,拥有全世界语言字符的编码
char a = 'a';
System.out.println(a);
char b = '鹏';
System.out.println(b);
//2.布尔类型,只有true和false两个值
boolean c = false;
System.out.println(c);
c = true;
System.out.println(c);
//3.整型(没有无符号类型)
//3.1 字节类型(1个字节)
byte d = Byte.MAX_VALUE;
System.out.println(d);
//3.2 短整型(2个字节)
short e = Short.MAX_VALUE;
System.out.println(e);
//3.3 整型(4个字节)
int f = Integer.MAX_VALUE;
System.out.println(f);
//3.4 长整型(8个字节)
long g = Long.MAX_VALUE;
System.out.println(g);
//4.浮点型
//4.1 单精度类型(小数后加f)
float h1 = 1.234567890f;//小数点后7位精度
System.out.println(h1);
//4.2 双精度类型
double h2 = Double.MAX_VALUE;//1.12345678901234567890;
System.out.println(h2);//小数点后16位精度
double h3 = 1.35e3;//1.3乘以1000,科学计数法
System.out.println(h3);
//5.金融货币类型(精确值)
BigDecimal bd = new BigDecimal("1.23E4"); // 正确,通过字符串构造
//取double类型的值
System.out.println(bd.doubleValue());
//6.字符串类型
String str1 = "123";
System.out.println(str1);
//拿已有的字符串构造新字符串
String str2 = new String(str1);
System.out.println(str2);
System.out.println(str1 == str2);//对象不等
System.out.println(str1.equals(str2));//值相等
//7.Object类型
Object o1 = 1;//装箱
int o2 = (int)o1;//拆箱
Object o3 = "abc";
//System.out.println(o1 == o2);//对象不等,两类型不能直接比较
System.out.println(o1 == o3);//对象不等,同种类型能直接比较
System.out.println(o1.equals(o2));//值相等
}
//2.常量
public static void ConstVal()
{
//常量不能改变其值
//A = 2;
}
//3.布尔运算符
public static void BooleanExpress() {
boolean a = true;
boolean b = !a;
boolean c = a && b;
boolean d = a || b;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
//4.算术运算符
public static void MathExpress() {
int a = 1;
int b = 2;
int c = a + b;//加
int d = a - b;//减
int e = a * b;//乘
int f = a / b;//除
int g = a % b;//余数
int h = a++; //自增1,先赋值
int i = ++a;//自增1,后赋值
int j = b--;//自减1,先赋值
int k = --b; //自减1,后赋值
}
//5.比较运算符
public static void CmpExpress() {
int a = 1;
int b = 2;
int c = 1;
boolean ret1 = a < b;// (小于)
boolean ret2 = a > b;// (大于)
boolean ret3 = a <= b;// (小于等于)
boolean ret4 = a >= b;// (大于等于)
boolean ret5 = a == b;// (等于)
boolean ret6 = a != b;// (不等于)
boolean ret7 = a == c;// (等于)
boolean ret8 = a != c;// (不等于)
}
//6.位运算符
public static void BitExpress() {
int yuResult = MyEnum.VAL1 & MyEnum.VAL2;//位与,结果:MyEnum.VAL1
int huoResult = MyEnum.VAL1 | MyEnum.VAL2;//位或,结果:MyEnum.VAL2
int feiResult = ~MyEnum.VAL1;//求反,结果:MyEnum.VAL3
int yihuoResult = MyEnum.VAL1 ^ MyEnum.VAL2;//异或,两1变0,两0不变,1/0(0/1) 为1,结果:MyEnum.VAL2
int zuoyiResult = (int)MyEnum.VAL2 << 2; //左移2位,结果:MyEnum.VAL5
int youyiResult = (int)MyEnum.VAL5 >> 2; //右移2位,结果:MyEnum.VAL2
}
//7.运算符优先级
public static void ExpressYouXianJi() {
byte b1 = 0b00000001;
byte b2 = 0b01000000;
byte b3 = 0b01000000;
int i1 = 100;
int i2 = 2;
int ret = b1 << 4 | b2 ^ b3 & 2; //先移位,再求位(与或非,右结合)
System.out.println(ret);
int ret2 = b2 ^ b3 & 2;
System.out.println(ret2);
//表达式运算优先级: 移位运算 > 位运算 > 算术运算 > 比较运算 > 逻辑运算 > 运算和赋值 > 赋值
boolean ret3 = true;
boolean ret0 = ret3 |= (b1 << 4 | (b2 ^ (b3 & 2))) == (b2 ^ b3 & 2)+ i1 && false;
System.out.println(ret0);
int ret4 = b2 | (b3 +100);
System.out.println(ret4);
int ret5= b2 | b3 + 100;
System.out.println(ret5);
int ret6 = (b2 | b3) + 100;
System.out.println(ret6);
}
//8.语句
public static void Statement() {
//1.赋值语句
int a = 1;
//2.表达式语句
boolean b = 1 > 2;
//3.块语句
{
int c = 1;
String d = "hello";
}
//4.if语句
if (1 > 0)
{
}
//5.if else 语句
if (1 > 0)
{
}
else
{
}
//6.if elseif ..else 语句
int e = 90;
if (e >= 90)
{
}
else if (e >= 80)
{
}
else if (e >= 60)
{
}
else
{
}
//for语句
int[] f = { 1, 2, 3, 4, 5, 6 };
int i = 0;
for (i = 0; i < f.length; i++)
{
int tem = f[i];
}
//for迭代语句
for (int item : f)
{
int tem = item;
}
//while语句
i = 0;
while (i < f.length)
{
int tem = f[i++];
}
//do...while语句
i = 0;
do
{
int tem = f[i++];
} while (i < f.length);
//switch语句
String abc = "1";
switch (abc)
{
case "1":
abc += "1";
break;
case "2":
abc += "2";
break;
case "3":
abc += "3";
break;
default:
break;
}
//continue语句
for (i = 0; i < f.length; i++)
{
if (i % f.length == 1)
{
continue;//跳过
}
System.out.println(f[i]);
}
//break语句
for (i = 0; i < f.length; i++)
{
if (i > 3)
{
break;//退出循环
}
System.out.println(f[i]);
}
//goto语句(java没有,但是有标签,break和continue能使用)
i = 0;
Loop1:
while(true)
{ i++;
if (i == 2) {
break;
}
continue Loop1;//继续循环
}
System.out.println("loop1:"+String.valueOf(i));
i = 0;
Loop2:
while(i >= 0 && i <= 2)
{ i++;
//System.out.println("~~~"+String.valueOf(i));
if (i == 2) {
break Loop2;//break loop2就不会再次执行循环体了
}
}
System.out.println("loop2:"+String.valueOf(i));
//方法调用语句
System.out.println("Hello World!!!");
}
//9.方法
public static void Method(){
//StaticCommon静态类的静态方法
//Common普通类的成员方法
}
//10.面向对象
public static void ObjectOri() {
Person chinese = new Chinese("1", "刘一");
Person englishman = new Engishman("2","jackie chan");
chinese.SayHello();
chinese.doEat();
englishman.SayHello();
englishman.doEat();
}
//11.访问修饰符
public static void VisitedDecorate() {
new Visited().Call();
}
//12.回调接口
public static void CallBack() {
ExecuteCallBack(new MyCallBackClass());
}
public static void ExecuteCallBack(MyCallBackInterface cb) {
if (cb != null) {
cb.CallAction();
}
}
//13.数组集合和字典
public static void ArrayCollectionDict() {
//一维数组
int a[] = {1,2,3};
/*
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at myStudyProject.Study1.ArrayCollectionDict(Study1.java:437)
at myStudyProject.Study1.main(Study1.java:60)
*/
//a[3] = 4;//访问数组下标元素越界
a[0] = 1;
System.out.println(a[0]);
//二维数组
int b[][] = {{1,2,3,4,5},{6,7}};
//遍历二维数组
for(int i = 0; i < b.length;i++) {
int b1[] = b[i];
for(int j = 0; j< b1.length; j++) {
System.out.println(b1[j]);
}
}
//集合
List<Integer> intList = new ArrayList<Integer>();
//添加集合元素
intList.add(1);
List<Integer> intList2 = new ArrayList<Integer>();
intList2.add(2);
//添加另一个集合的所有元素
intList.addAll(intList2);
intList.remove(0);//删除下标元素
for(int j = 0; j < intList.size(); j++) {
System.out.println(intList.get(j));
}
//条件删除
intList.removeIf(new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t == 2;
}} );
for(int j = 0; j < intList.size(); j++) {
System.out.println(intList.get(j));
}
intList.clear();
//字典
Map<Integer,String> m1 = new HashMap<Integer,String>();
m1.put(1, "100");
//遍历键
for(int key:m1.keySet()) {
System.out.println(m1.get(key));
}
//遍历项
for(Map.Entry<Integer, String> e :m1.entrySet()) {
System.out.println(e.getKey()+":"+e.getValue());
}
//删除键和值,如果不存在不影响
m1.remove(1,"101");
//遍历键
for(int key:m1.keySet()) {
System.out.println(m1.get(key));
}
m1.remove(1);//删除键
}
//14.泛型
public static void Generic() {
MathOp<Integer> intMath = new MathOp<Integer>();
Integer ret1 = (int)intMath.Plus(1, 2);
MathOp<Float> floatMath = new MathOp<Float>();
Float ret2 = (float)floatMath.Plus(3.1f, 2.3f);
}
//15.反射
public static void Reflect() {
Class<ThatPerson> thatPersonClass = ThatPerson.class;
//测试getFields()函数
Field []studentFields = thatPersonClass.getFields();
System.out.println("通过getFields获取Student类所有公开属性");
for (Field field:studentFields) {
System.out.println("属性的类型为:"+field.getType()+"属性的名称为:"+field.getName());
}
System.out.println();//换行
//测试getDeclaredFields()函数
Field []studentDeclaredFields = thatPersonClass.getDeclaredFields();
System.out.println("通过getDeclaredFields获取Student类所有属性(包括私有,不包括继承)");
for (Field field :studentDeclaredFields) {
System.out.println("属性的类型为:"+field.getType()+"\t属性的名称为:"+field.getName());
}
System.out.println();//换行
//getField(String)函数
Field field = null;
try {
field = thatPersonClass.getField("age");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
System.out.println("通过getField(\"age\")获取公开属性age");
System.out.println("属性的类型为:"+field.getType()+"\t属性的名称为:"+field.getName());
System.out.println();//换行
//测试getDeclaredField(String)函数
Field DeclaredFiled = null;
try {
DeclaredFiled = thatPersonClass.getDeclaredField("name");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
System.out.println("通过getDeclaredField(\"name\")获取私有属性name");
System.out.println("属性的类型为:"+DeclaredFiled.getType()+"\t属性的名称为:"+DeclaredFiled.getName());
Method[] methods = thatPersonClass.getMethods();
System.out.println("通过getMethods()获取所有公开方法");
for (Method method : methods) {
System.out.println(method.getName());
Class[] plts = method.getParameterTypes();
System.out.println("参数数量为:"+plts.length);
for (Class p : plts) {
System.out.println("参数类型为:"+p.getTypeName());
}
}
System.out.println();//换行
//测试getDeclaredMethods()函数
Method[] DeclaredMethods = thatPersonClass.getDeclaredMethods();
System.out.println("通过getDeclaredMethods()获取所有方法(包括私有,不包括继承)");
for (Method method : DeclaredMethods) {
System.out.println(method.getName());
Class[] plts = method.getParameterTypes();
System.out.println("参数数量为:"+plts.length);
for (Class p : plts) {
System.out.println("参数类型为:"+p.getTypeName());
}
}
System.out.println();//换行
//测试getMethod(参数)函数
Method method = null;
try {
method = thatPersonClass.getMethod("setName", String.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
System.out.println("通过getMethod(\"getName\",String.class)获取getName方法");
System.out.println(method.getName());
Class[] plts = method.getParameterTypes();
System.out.println("参数数量为:"+plts.length);
for (Class p : plts) {
System.out.println("参数类型为:"+p.getTypeName());
}
System.out.println();//换行
//测试getDeclaredMethod(参数)函数
Method DeclaredMethod = null;
try {
DeclaredMethod = thatPersonClass.getDeclaredMethod("doingThing");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
System.out.println("通过getDeclaredMethod(\"schooling\")获取schooling方法");
System.out.println(DeclaredMethod.getName());
Class[] pls = DeclaredMethod.getParameterTypes();
System.out.println("参数数量为:"+pls.length);
for (Class p : pls) {
System.out.println("参数类型为:"+p.getTypeName());
}
Constructor[] constructors = thatPersonClass.getConstructors();
System.out.println("通过getConstructors()获取所有公开构造方法");
for (Constructor con: constructors) {
System.out.println("构造方法名称为:"+con.getName());
Class plts1[] = con.getParameterTypes();
System.out.println("参数数量为:"+plts1.length);
System.out.println("形参类型为:");
for (Class p: plts1) {
System.out.println(p);
}
}
System.out.println();//换行
//测试getDeclaredConstructors()函数
Constructor[] DeclaredConstructors = thatPersonClass.getDeclaredConstructors();
System.out.println("通过getDeclaredConstructors()获取所有构造方法(包括私有,包括继承)");
for (Constructor con : DeclaredConstructors) {
System.out.println("构造方法名称为:"+con.getName());
Class[] plts2 = con.getParameterTypes();
System.out.println("参数数量为:"+plts2.length);
System.out.println("形参类型为:");
for (Class p: plts2) {
System.out.println(p);
}
}
Constructor c = null;
try {
c = thatPersonClass.getConstructor(String.class, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
Object obj = null;
try {
obj = c.newInstance("小明",18);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(obj);
//等价于
ThatPerson s = new ThatPerson("小明", 10);
System.out.println(s);
//获取setName方法并调用
Method m1 = null;
try {
m1 = thatPersonClass.getDeclaredMethod("setName", String.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
try {
m1.invoke(obj,"小飞");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(obj);
//获取doingThing方法
Method m2 = null;
try {
m2 = thatPersonClass.getDeclaredMethod("doingThing");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
//如果doingThing为私有方法,则得取消权限访问控制,但实际为公有方法
//m2.setAccessible(true);
try {
m2.invoke(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//16.多线程
public static void MutilThread() {
MyRun run = new MyRun();
run.run();
MyThread th = new MyThread();
th.start();
}
//17.序列化和反序列化
public static void SeriAnUnSeri() {
ThatPerson tp = new ThatPerson("long",10);
File file = new File("d:\\thatPerson1.dat");
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tp);
oos.flush();
fos.close();
oos.close();
System.out.println("写文件成功!");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
ThatPerson tp2;
tp2 = (ThatPerson)ois.readObject();
System.out.println("name="+tp2.getName());
System.out.println("age="+tp2.age);
ois.close();
fis.close();
System.out.println("读文件成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//18.文件操作
public static void FileOp() {
String srcFile= "d:\\thatPerson1.dat";
String destFile = "d:\\thatPerson2.dat";
try {
copyFile(srcFile,destFile);
File file = new File(destFile);
if (file.exists()) {
System.out.println("文件拷贝成功!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//文件拷贝操作
public static void copyFile(String filePath,String filePath1)throws IOException {
FileInputStream fi=new FileInputStream(filePath);
FileOutputStream fo=new FileOutputStream(filePath1);
byte buffer[]=new byte[1024];
int ret = -1;
try {
do{
ret = fi.read(buffer);
if (ret > 0){
fo.write(buffer,0,ret);
}
}
while(ret <= 0);
}catch(IOException e) {
System.out.println(e);
}
finally{
fi.close();
fo.close();
}
}
//19.正则表达式
public static void RegexOp() {
String address = "jackyfang888@qq.com";
String regex="\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}"; //定义要匹配使用的E-mail使用的正则表达式
if(address.matches(regex)) { //判断字符串变量是否与正则表达式匹配
System.out.println(address+"是合法的邮箱!");
}else {
System.out.println(address+"不是合法的邮箱!");
}
}
}
//继承Thread类
class MyThread extends Thread{
@Override
public void run() {
System.out.println("MyThread run ...");
}
}
//实现Runnable接口
class MyRun implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("MyRun run ...");
}
}
//反射操作的类,也是序列化的类
class ThatPerson implements Serializable{
private String name;
public int age;
public ThatPerson(String name, int age) {
this.name = name;
this.age = age;
}
public ThatPerson(String name){
this.name = name;
}
public void doingThing(){
System.out.println("doingThing...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ThatPerson{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//泛型类
class MathOp<T extends Number>
{
//泛型方法
public double Plus(T a, T b) {
return a.doubleValue() + b.doubleValue();
}
public double Minus(T a, T b) {
return a.doubleValue() - b.doubleValue();
}
}
interface MyCallBackInterface{
public void CallAction();
}
class MyCallBackClass implements MyCallBackInterface{
@Override
public void CallAction() {
System.out.println("call back...");
}
}
//定义一个类
class Common
{
//静态方法,必须由静态类调用的方法
public static void Print(String content)
{
System.out.println(content);
}
//Print方法的重载
public static void Print(String content, boolean printLine)
{
if (printLine)
System.out.println(printLine + ":" + content);
else
System.out.println(printLine + ":"+content);
}
public void EmptyMethod()
{
System.out.println("EmptyMethod无参无返回值方法的调用");
}
public void Param2Method(int param1, String param2)
{
System.out.println("Param2Method:有参无返回值方法的调用");
}
public boolean Param2HasResultMethod(int param1, String param2)
{
System.out.println("Param2HasResultMethod:有参有返回值方法的调用");
return true;
}
}
//“人”的抽象类
abstract class Person implements Eat //人都要实现怎么吃的接口
{
public Person(String id, String fullName)
{
this.id = id;
this.fullName = fullName;
}
public String id;
public String fullName;
public abstract void doEat();//用什么吃饭(筷子,刀叉等)
//不同国家的人说“哈喽”用不一样的词汇
public abstract void SayHello();
}
//吃动作的接口
interface Eat
{
public abstract void doEat();
}
//中国人(密封类,不能再派生)
class Chinese extends Person
{
public Chinese(String id, String fullName) {
super(id, fullName);
System.out.println("这来了一个人,叫"+fullName+",是中国人!");
}
public void doEat()
{
System.out.println("中国人用筷子吃饭");
}
public void SayHello()
{
System.out.println("中国人说hello:你好!");
}
}
//英国人(密封类,不能再派生)
final class Engishman extends Person
{
public Engishman(String id, String fullName) {
super(id, fullName);
System.out.println("这来了一个人,叫"+fullName+",是英国人!");
}
public void doEat()
{
System.out.println("英国人用刀叉吃饭");
}
public void SayHello()
{
System.out.println("英国人说hello:How do you do!");
}
}
//这是不能实现的
// public class ThirdPerson extends Chinese
// {
//
// }
//访问修饰
class Visited
{
//私有内部类,被嵌套定义,能被直接外部类访问,外部类之外无法访问
private class Class_Private
{
//公有
public int a ;
//私有
private int b ;
//受保护
protected int c;
}
//内部保护类,被嵌套定义,能被直接外部类访问,外部类之外无法访问
protected class Class_Protected
{
public int a;
}
//公共的类,能被任何地方引用
class Class_Public
{
public int a;
}
//调用成员方法
public void Call()
{
//私有的内部类能实例化
Class_Private class_Private = new Class_Private();
class_Private.a = 1;
class_Private.b = 2;//外部可以访问私有成员
class_Private.c = 3;//外部可以访问受保护成员
//公有的类
Class_Public class_Public = new Class_Public();
class_Public.a = 1;
//受保护的类
Class_Protected class_Protected = new Class_Protected();
class_Protected.a = 1;
}
}
更多推荐




所有评论(0)