【JavaSE】常用基础类库

本文深入讲解Java编程关键技能,包括程序入口main函数、使用Scanner获取输入、System类应用、Runtime类介绍、Objects类新增功能、Math类数学运算、BigDecimal类高精度计算、Date和Calendar类日期操作、以及Properties类的属性文件读写。文章涵盖Java基础到进阶的知识点,适合初学者及有一定经验的开发者阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Java程序入口main函数

public static void main(String[] args) {}
  • 参数列表为字符串数组,根据调用规则,谁调用谁传参,因为main()方法由JVM调用,因此args形参由JVM负责赋值,空格作为参数分割符,若参数本身包含空格,则一个将该参数用双引号括起来。

2.使用Scanner获取键盘输入

语法:Scanner scan=new Scanner(System.in);//声明Scanner类

  • System in 代表标准输入,就是键盘输入

Scanner提供获取输入的方法有:

public boolean hasNextXxx();//Xxx为想要获取的数据类型
public String next();
public Xxx nextXxx();
public String nextLine();//将此扫描仪推进到当前行并返回跳过的输入。

更改分割符:

public Scanner useDelimiter(String pattern);//不再使用空格作为分割符
 Scanner scanner=new Scanner(System.in);
        System.out.println("请输入年龄");
        //判断下一个输入是否int值
//        if(scanner.hasNextInt()){
        //接收int数据类型
//            System.out.println(scanner.nextInt());
//        }else{
//            System.out.println("输入的不是数字");
//        }

//通过while循环,直到接收到int数据为止
        while(true){
            if(scanner.hasNextInt()){
                System.out.println(scanner.nextInt());
                break;
            }else{
                System.out.println("输入的不是数字");
                //获取下一行(丢弃不符合要求的数据)
                scanner.next();
            }
        }
        scanner.close();
    }
//代替BufferedReader读取文件(从文件中获取输入)
        try (Scanner scanner = new Scanner(Paths.get("D:","TL-BITE","Test","write.txt"))) {
            scanner.useDelimiter("\n");
            while (scanner.hasNext()) {
                System.out.println(scanner.next());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

3.System类

System类代表当前Java程序的运行平台,程序不能创建System类的对象
1.“标准”错误输出流

static PrintStream err

2.“标准”输入流。

static InputStream in 

3.“标准”输出流

static PrintStream out 

4.获取指定环境变量的值

public static String getenv(String name) ;

5.确定当前的系统属性

public static Properties getProperties();

6.运行垃圾回收器

public static void gc();
//系统属性
        Properties properties = System.getProperties();
 常用的系统属性
        user.home
        user.dir
        java.home
        path.separator
        file.separator

4.Runtime类

Runtime类代表Java程序运行时环境,每个Java程序都有与之对应的Runtime实例,应用程序通过该类对象与其运行时环境相连。应用程序不能创建自己的Runtime实例,但可以通过getRuntime()方法获取与之相关连的Runtime对象。

public class RuntimeTest {
    public static void main(String[] args) {
        Runtime rt=Runtime.getRuntime();
        System.out.println("处理器数量"+rt.availableProcessors());
        System.out.println("空闲内存"+rt.freeMemory());
        System.out.println("可用最大内存数"+rt.maxMemory());
    }
}

5.JDK1.7新增Objects类

Objects工具类提供了一些工具方法来操作对象,这些工具方法大多是“空指针”安全的。当你不确定一个引用变量是否为null,就调用了Object类中的toString()方法,那么就有可能引发空指针异常,但是使用Objects提供的toString()方法不会引发异常,只会在空指针是返回null值。

public class ObjectsTest {
    static ObjectsTest obj;
    public static void main(String[] args) {
        System.out.println(Objects.hashCode(obj));
        System.out.println(Objects.toString(obj));
      
      //要求obj不能为null,如果为null,就会引发异常。
       System.out.println(Objects.requireNonNull(obj,"obj的参数不能是null"));
    }

6.Math类

Java中的Math类提供了像三角函数,对数运算,指数运算等复杂数学运算。Math类是一个工具类,其构造器是private的,因此无法创建Math类的实例,其中所有的方法都是静态的类方法,因此可以直接通过类名Math调用。除此之外,Math类还提供了两个常量PI和E即数学上的圆周率与e
1.三角函数类工具方法

public static void main(String[] args) {
        System.out.println("将弧度转化为角度:Math.toDegrees(1.57)\t"+Math.toDegrees(1.57));
        System.out.println("将角度转化为弧度:Math.toRadians(90)\t" + Math.toRadians(90));
        System.out.println("计算反余弦:Math.acos(1.2)\t"+Math.acos(1.2));
        System.out.println("计算反正弦:Math.asin(0.8)\t"+Math.asin(0.8));
        System.out.println("计算计算双曲正弦:Math.cosh(1.2)\t"+Math.cosh(1.2));
        System.out.println("计算计算双曲正切:Math.cosh(1.2)\t"+Math.tanh(2.1));
    }

2.取整运算

	    //向下取整
        System.out.println("Math.floor(-1.2)\t"+Math.floor(-1.2));
      
       //向上取整
        System.out.println("Math.ceil(-1.2)\t"+Math.ceil(-1.2));
      
       //四舍五入取整
        System.out.println(Math.round(2.5));

3.乘方、开方、指数运算

  		//计算平方根
        System.out.println("Math.sqrt(1.2)"+Math.sqrt(1.2));
        //计算立方根
        System.out.println("Math.cbrt(3)"+Math.cbrt(3));
        //返回(x1+x2)的平方根
        System.out.println("Math.hypot(2,3)"+Math.hypot(2,3));
        //计算底数为10的自然对数
        System.out.println("Math.log10(100)"+Math.log10(100));

4.符号运算

		 //计算绝对值
        System.out.println("Math.abs(-4.5)"+Math.abs(-4.5));
        //符号赋值,返回第二个带有浮点符号的第一个浮点参数
        System.out.println("Math.copySign(1.2,-1.0)"+Math.copySign(1.2,-1.0));
        //符号函数
        System.out.println("Math.signum(120)"+Math.signum(120));

5.大小运算

		//找出最大值
        System.out.println(Math.max(1.2,3.4));
        //计算最小值
        System.out.println(Math.min(1.2,1.3));
        //返回第一个参数和第二个参数之间与第一个参数相邻的浮点数
        System.out.println(Math.nextAfter(1.2,3));
        //返回比浮点数略大的浮点数
        System.out.println(Math.nextUp(12.2));
        //返回一个伪随机数,该值大于等于0.0且小于1.0
        System.out.println(Math.random());

7.BigDecimal类

float、double两种基本浮点类型容易引起精度丢失,尤其在进行算术运算时。
为了能精确表示,计算浮点数,Java提供了BigDecimal类,建议使用public BigDecimal(String value)的构造器,创建浮点对象。
BigDecimal类提供了add(),substract(),divide(),pow()等方法对精确浮点数进行常规算术运算。

public static void main(String[] args) {
        BigDecimal f1=new BigDecimal("0.05");
        BigDecimal f2=new BigDecimal("0.01");
        BigDecimal f3=new BigDecimal("99.793");
        System.out.println("0.05+0.01="+f1.add(f2));
       // System.out.println("0.05+0.01="+(0.05+0.01));//0.05+0.01=0.060000000000000005
        System.out.println("0.05-0.01="+f1.subtract(f2));
        System.out.println("0.05*0.01="+f1.multiply(f2));
        System.out.println("0.05/0.01="+f1.divide(f2));
    }

8.date类

date构造器:

public date();//生成一个代表当前日期的date对象
public date(long time);//根据指定的整数生成一个date对象

这个long型整数是指创建的date对象和1970年1月1日00:00:01之间的时间差,以毫秒作计时单位

public void setTime(long time);//设置该date对象的时间

8.calendar类

calendar是一个抽象类,不能直接实例化,程序只能创建calendar类的子类,如GregorianCalendar类,是我们平常用的公历。也可以提供静态方法getInstance(),获取calendar的对象。

   Calendar calendar = Calendar.getInstance();
    //从calendar对象中取出Date对象
        Date date = calendar.getTime();
        //通过Date对象获得对应的Calendar对象
        //Calendar没有相应的构造函数接收Date对象
        //所有通过setTime方法接收
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date);

Calender类提供大量访问、修改日期的方法:
1.根据日历规则,为给定日历字段加上或减去指定时间量

public void add(int field,int amount)

2.使用默认时区和区域设置获取日历。

public static Calendar getInstance()  

3.设置日历字段中的值 YEAR , MONTH和 DAY_OF_MONTH
void set(int year, int month, int date)
4.将指定(签名)金额添加到指定的日历字段,而不更改较大的字段

void roll(int field, int amount) 

Properties属性文件操作

在java中有一种属性文件(资源文件)的定义:.properties文件,在这种文件里面其内容的保存形式为"key = value",Properties(.properties(属性文件)–>Properties(属性类))是Hashtable的子类,因此可以用get put方法
*.properties文件中: 注释是“#” 属性文件中内容不换行 行结尾不以任何符号结尾,换行即可

在进行属性操作时利用Properties类提供的方法完成

  1. 设置属性 : public synchronized Object setProperty(String key, String value)
  2. 取得属性 : public String getProperty(String key),如果没有指定的key则返回null
  3. 取得属性 : public String getProperty(String key, String defaultValue),如果没有指定的key则返回默认值

在Properties类中提供有IO支持的方法:

  1. 保存属性: public void store(OutputStream out, String comments) throws IOException
  2. 读取属性: public synchronized void load(InputStream inStream) throws IOException
public static void main(String[] args) {
        //因为Properties继承了Hashtable,因此可以用get put方法
        //*.properties  ->属性文件
        //Properties    ->属性类
        //读取文件:load ->Properties InputStream
        //写入文件:store ->Properties OutputStream
        Properties properties=new Properties();

        //读取属性
        try {
            //1.通过文件流读取属性
            properties.load(new FileInputStream("D:\\TL-BITE\\JAVA\\java_examples\\collection_practice\\src\\com\\sweet\\properties\\hello.properties"));
           //
            InputStream inputStream= PropertiesTest.class.getClassLoader()
                    .getResourceAsStream("com/sweet/properties/hello.properties");//文件名须包含包名
            properties.load(inputStream);
            System.out.println(properties.get("c++"));
            System.out.println("java");
            //当某个属性可能没有时,利用getProperty方法,为属性(key)赋值
            System.out.println(properties.getProperty("php","nice"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        properties.put("go", "better");
        properties.setProperty("python", "hard");

        //将写的key存入
        try {
            properties.store(new FileOutputStream("D:\\TL-BITE\\JAVA\\java_examples\\collection_practice\\src\\com\\sweet\\properties\\hello-1.properties"),"写入");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Collections工具类

Collections是一个集合操作的工具类,包含有集合反转、排序等操作。

public static void main(String[] args) {
        List<String> data = new ArrayList<>();
        for(int i=65;i<=123;i++){
data.add(String.valueOf((char)i));
        }
        System.out.println(data);
        System.out.println("原始数据"+data);
        System.out.println("反转:");
        Collections.reverse(data);
        //二分查找
        //index=-(插入点的下标)-1
       int index= Collections.binarySearch(data, "A");
        System.out.println("查看A下标"+index);
        //乱序
        Collections.shuffle(data);
        //将非同步集合变为同步集合
        //将集合变为不可修改的集合
        Map<String, String> map = new HashMap<>();
        System.out.println(map.put("q","退出"));
       map= Collections.unmodifiableMap(map);

       System.out.println(map.put("q","退出"));
        //将集合变为不可修改的集合后再对集合进行修改则会报错
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值