JavaSE

发布时间 2023-07-03 22:38:07作者: NewBee_2023

Java 基本数据类型

Java 提供了八种基本类型,包括六种数字,一种字符,一种布尔:

public class Test {
    public static void main(String[] args) {
        int i = 8;
        System.out.println(i); // 8
        System.out.println(i/3); // 2 (int -> int)
        Float f = 22.02f;
        System.out.println(f); // 22.02
        Double d = 13.14;
        System.out.println(d); // 13.14
        Boolean b = false;
        System.out.println(b); // false
        char c = 't';
        System.out.println(c); // t
    }
}

数组

public class Test {
    public static void main(String[] args) {
        String[] books = {"三国演义", "西游记", "红楼梦", "水浒传"};
        System.out.println("第2本书是:"+books[1]);
        // 第2本书是:西游记
    }
}

异常处理

throw 用于抛出异常, throws 用于声明方法可能抛出异常

public class Test {
    public static void main(String[] args) throws Exception {
        testErr();
    }

    static void testErr() throws Exception {
        try {
            String[] books = {"三国演义", "西游记", "红楼梦", "水浒传"};
            System.out.println("第5本书是:" + books[5]);
        } catch (Exception e) {
            System.out.println(e);
            // java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4
            throw new Exception("不存在这本书");
        }
    }
}

ArrayList、HashMap

ArrayList

public class Test {
    public static void main(String[] args) throws Exception {
        ArrayList<String> books = new ArrayList<String>();
        books.add("三国演义");
        books.add("西游记");
        books.add("红楼梦");
        for(String book: books) {
            System.out.println(book);
        }
    }
}

HashMap

public class Test {
    public static void main(String[] args) throws Exception {
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "西游记");
        map.put(2,"红楼梦");
        System.out.println(map); // {1=西游记, 2=红楼梦}
    }
}