Note 14 - Common API s & Exceptions

1. Packaging Classes

1.1 Basic Type Packaging Class (Memory)

  • Role of basic types of wrapper classes

    The benefit of encapsulating basic data types as objects is that you can define more functional methods within the object to manipulate the data

    One of the common operations: for conversion between basic data types and strings

  • Packaging Class for Base Type

    Basic data typesPackaging Class
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    doubleDouble
    charCharacter
    booleanBoolean

1.2 Integer class (application)

  • Overview of Integer classes

    Wrap the value of the original type int in an object

  • Integer class construction method

    Method NameExplain
    public Integer(int value)Create Integer object from int value (obsolete)
    public Integer(String s)Create Integer objects from String values (obsolete)
    public static Integer valueOf(int i)Returns an Integer instance representing the specified int value
    public static Integer valueOf(String s)Returns an Integer object String that holds the specified value
  • Sample Code

    public class IntegerDemo {
        public static void main(String[] args) {
            //public Integer(int value): Create an Integer object based on an int value (obsolete)
            Integer i1 = new Integer(100);
            System.out.println(i1);
    
            //public Integer(String s): Create Integer objects based on String values (obsolete)
            Integer i2 = new Integer("100");
    //        Integer i2 = new Integer("abc"); //NumberFormatException
            System.out.println(i2);
            System.out.println("--------");
    
            //public static Integer valueOf(int i): Returns an Integer instance representing the specified int value
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //public static Integer valueOf(String s): Returns an Integer object String that holds the specified value
            Integer i4 = Integer.valueOf("100");
            System.out.println(i4);
        }
    }
    

1.3int and String type conversion (memory)

  • int to String

    • Conversion mode

      • Method 1: Add an empty string directly after the number
      • Mode 2: valueOf() via String class static method
    • Sample Code

      public class IntegerDemo {
          public static void main(String[] args) {
              //int --- String
              int number = 100;
              //Mode 1
              String s1 = number + "";
              System.out.println(s1);
              //Mode 2
              //public static String valueOf(int i)
              String s2 = String.valueOf(number);
              System.out.println(s2);
              System.out.println("--------");
          }
      }
      
  • String to int

    • Conversion mode

      • Mode 1: Convert a string number to Integer before calling the valueOf() method
      • Mode 2: Convert via Integer static method parseInt()
    • Sample Code

      public class IntegerDemo {
          public static void main(String[] args) {
              //String --- int
              String s = "100";
              //Mode 1: String --- Integer --- int
              Integer i = Integer.valueOf(s);
              //public int intValue()
              int x = i.intValue();
              System.out.println(x);
              //Mode 2
              //public static int parseInt(String s)
              int y = Integer.parseInt(s);
              System.out.println(y);
          }
      }
      

1.4 String Data Sorting Case (Application)

  • Case Requirements

    There is a string:'91 27 46 38 50', please write a program to achieve the final output:'27 38 46 50 91'

  • code implementation

    public class IntegerTest {
        public static void main(String[] args) {
            //Define a string
            String s = "91 27 46 38 50";
    
            //Store numeric data in a string in an array of type int
            String[] strArray = s.split(" ");
    //        for(int i=0; i<strArray.length; i++) {
    //            System.out.println(strArray[i]);
    //        }
    
            //Define an int array to store each element of the String[] array in the int array
            int[] arr = new int[strArray.length];
            for(int i=0; i<arr.length; i++) {
                arr[i] = Integer.parseInt(strArray[i]);
            }
    
            //Sort the int array
            Arrays.sort(arr);
    
            //The elements in the sorted int array are stitched together into a string, which is stitched using StringBuilder
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<arr.length; i++) {
                if(i == arr.length - 1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(" ");
                }
            }
            String result = sb.toString();
    
            //Output Results
            System.out.println(result);
        }
    }
    

1.5 Automatic unpacking and packing (understanding)

  • Automatic packing

    Convert basic data types to corresponding wrapper class types

  • Auto-unboxing

    Convert wrapper class type to corresponding base data type

  • Sample Code

    Integer i = 100;  // Automatic packing
    i += 200;         // i = i + 200;I + 200 auto-unboxing;i = i + 200;Is automatic packing
    

2. Time Date Class

2.1 Date class (application)

  • An overview of the Date class

    Date represents a specific time, accurate to milliseconds

  • Date class construction method

    Method NameExplain
    public Date()Assign a Date object and initialize it so that it represents the time it was allocated, accurate to milliseconds
    public Date(long date)Assign a Date object and initialize it to represent the number of milliseconds specified from standard base time
  • Sample Code

    public class DateDemo01 {
        public static void main(String[] args) {
            //public Date(): Assign a Date object and initialize it so that it represents the time it was allocated, accurate to milliseconds
            Date d1 = new Date();
            System.out.println(d1);
    
            //public Date(long date): Assign a Date object and initialize it to represent the number of milliseconds specified from standard base time
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

2.2Date Class Common Methods (Applications)

  • common method

    Method NameExplain
    public long getTime()Gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
    public void setTime(long time)Set the time, given the value in milliseconds
  • Sample Code

    public class DateDemo02 {
        public static void main(String[] args) {
            //Create Date object
            Date d = new Date();
    
            //public long getTime(): Gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
    //        System.out.println(d.getTime());
    //        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "year");
    
            //public void setTime(long time): Set the time, given a value of milliseconds
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

2.3SimpleDateFormat class (application)

  • An overview of the SimpleDateFormat class

    SimpleDateFormat is a specific class for formatting and parsing dates in a locale-sensitive manner.

    We focus on formatting and parsing dates

  • SimpleDateFormat class construction method

    Method NameExplain
    public SimpleDateFormat()Construct a SimpleDateFormat using default mode and date format
    public SimpleDateFormat(String pattern)Construct a SimpleDateFormat to use the given pattern and default date format
  • Common methods of the SimpleDateFormat class

    • Formatting (from Date to String)
      • public final String format(Date date): Format the date into a date/time string
    • Parse (from String to Date)
      • public Date parse(String source): parses text from the beginning of a given string to generate a date
  • Sample Code

    public class SimpleDateFormatDemo {
        public static void main(String[] args) throws ParseException {
            //Formatting: From Date to String
            Date d = new Date();
    //        SimpleDateFormat sdf = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //From String to Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

2.4 Tool Case (Application)

  • Case Requirements

    Defines a DateUtils tool class that contains two methods: converting a date to a string in a specified format;Parses the string to a date in the specified format, and then defines a test class (DateDemo), the method of the test date tool class

  • code implementation

    • Tool class
    public class DateUtils {
        private DateUtils() {}
    
        /*
            Converts the date to a string in the specified format
            Return value type: String
            Parameters: Date date, String format
         */
        public static String dateToString(Date date, String format) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            String s = sdf.format(date);
            return s;
        }
    
    
        /*
            Resolves a string to a date in the specified format
            Return value type: Date
            Parameters: String s, String format
         */
        public static Date stringToDate(String s, String format) throws ParseException {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date d = sdf.parse(s);
            return d;
        }
    
    }
    
    • Test Class
    public class DateDemo {
        public static void main(String[] args) throws ParseException {
            //Create Date object
            Date d = new Date();
    
            String s1 = DateUtils.dateToString(d, "yyyy year MM month dd day HH:mm:ss");
            System.out.println(s1);
    
            String s2 = DateUtils.dateToString(d, "yyyy year MM month dd day");
            System.out.println(s2);
    
            String s3 = DateUtils.dateToString(d, "HH:mm:ss");
            System.out.println(s3);
            System.out.println("--------");
    
            String s = "2048-08-09 12:12:12";
            Date dd = DateUtils.stringToDate(s, "yyyy-MM-dd HH:mm:ss");
            System.out.println(dd);
        }
    }
    

2.5 Calendar class (application)

  • An overview of Calendar classes

    Calendar provides methods for converting specific moments to a set of calendar fields and for manipulating calendar fields

    Calendar provides a class method, getInstance, to obtain generally useful objects of this type.

    This method returns a Calendar object.

    Its calendar field has been initialized with the current date and time: Calendar rightNow = Calendar.getInstance();

  • Common Calendar Class Methods

    Method NameExplain
    public int get(int field)Returns the value of a given calendar field
    public abstract void add(int field, int amount)Adds or subtracts a specified amount of time from a given calendar field according to calendar rules
    public final void set(int year,int month,int date)Set the year, month and day of the current calendar
  • Sample Code

    public class CalendarDemo {
        public static void main(String[] args) {
            //Get Calendar Class Object
            Calendar c = Calendar.getInstance();
    
            //public int get(int field): Returns the value of a given calendar field
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH) + 1;
            int date = c.get(Calendar.DATE);
            System.out.println(year + "year" + month + "month" + date + "day");
    
            //public abstract void add(int field, int amount): Adds or subtracts a specified amount of time from a given calendar field according to calendar rules
            //Demand 1:3 years ago today
    //        c.add(Calendar.YEAR,-3);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + year + month + month + date + day);
    
            //Demand 2:10 days ago
    //        c.add(Calendar.YEAR,10);
    //        c.add(Calendar.DATE,-10);
    //        year = c.get(Calendar.YEAR);
    //        month = c.get(Calendar.MONTH) + 1;
    //        date = c.get(Calendar.DATE);
    //        System.out.println(year + year + month + month + date + day);
    
            //public final void set(int year,int month,int date): sets the month and year day of the current calendar
            c.set(2050,10,10);
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH) + 1;
            date = c.get(Calendar.DATE);
            System.out.println(year + "year" + month + "month" + date + "day");
    
        }
    }
    

February Day 2.6 Case (Application)

  • Case Requirements

    Get the number of days in February of any year

  • code implementation

    public class CalendarTest {
        public static void main(String[] args) {
            //Keyboard Enter Any Year
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter a year:");
            int year = sc.nextInt();
    
            //Set year, month, day of calendar object
            Calendar c = Calendar.getInstance();
            c.set(year, 2, 1);
    
            //March 1 goes forward one day, the last day of February
            c.add(Calendar.DATE, -1);
    
            //Get the output for this day
            int date = c.get(Calendar.DATE);
            System.out.println(year + "In February of the year" + date + "day");
        }
    }
    

3. Exceptions

3.1 Anomalies (Memory)

  • Overview of anomalies

    An exception is a malfunction in the program

  • Abnormal Architecture

3.2JVM default way of handling exceptions (understand)

  • If something goes wrong with the program and we don't do anything, the JVM will do it by default in two steps:

  • Information such as the name of the exception, the cause of the error and the location of the exception is output to the console

  • Program Stop Execution

3.3try-catch handling exceptions (application)

  • Define Format

    try {
    	Code with possible exceptions;
    } catch(Exception Class Name Variable Name) {
    	Handling code for exceptions;
    }
    
  • Execute process

    • The program starts with code inside the try
    • If an exception occurs, it jumps to the corresponding catch to execute
    • After execution, the program can continue
  • Sample Code

    public class ExceptionDemo01 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("End");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]);
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) {
    //            System.out.println("The array index you accessed does not exist, please go back and modify it to the correct index");
                e.printStackTrace();
            }
        }
    }
    

3.4 Throwable member method (application)

  • common method

    Method NameExplain
    public String getMessage()Returns the detailed message string for this throwable
    public String toString()Return this throwable short description
    public void printStackTrace()Output exception error information to console
  • Sample Code

    public class ExceptionDemo02 {
        public static void main(String[] args) {
            System.out.println("start");
            method();
            System.out.println("End");
        }
    
        public static void method() {
            try {
                int[] arr = {1, 2, 3};
                System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
    //            e.printStackTrace();
    
                //public String getMessage(): Returns the detailed message string for this throwable
    //            System.out.println(e.getMessage());
                //Index 3 out of bounds for length 3
    
                //public String toString(): Returns this short description that can be thrown
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace(): Output exception error information to console
                e.printStackTrace();
    //            java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    //            at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
    //            at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
    
            }
        }
    }
    

3.5 Difference between compile-time and run-time exceptions (memory)

  • Compile-time exceptions

    • Are Exception classes and their subclasses
    • Processing must be displayed or the program will fail to compile
  • Runtime Exceptions

    • Are both RuntimeException classes and their subclasses
    • No display handling is required or can be handled as an exception during compilation

3.6 throws handling exceptions (application)

  • Define Format

    public void Method() throws Exception Class Name {
        
    }
    
  • Sample Code

    public class ExceptionDemo {
        public static void main(String[] args) {
            System.out.println("start");
    //        method();
            try {
                method2();
            }catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("End");
        }
    
        //Compile-time exceptions
        public static void method2() throws ParseException {
            String s = "2048-08-09";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse(s);
            System.out.println(d);
        }
    
        //Runtime Exceptions
        public static void method() throws ArrayIndexOutOfBoundsException {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
        }
    }
    
  • Matters needing attention

    • This throws format follows the parentheses of the method
    • Compile-time exceptions must be handled, either try...catch...or throws. If throws are used, who calls whom to handle them in the future
    • Runtime exceptions can be left untreated and we need to come back to modify the code after a problem occurs

Differences between 3.7 throws and throws (memory)

3.8 Custom Exceptions (Apply)

  • Custom exception class

    public class ScoreException extends Exception {
    
        public ScoreException() {}
    
        public ScoreException(String message) {
            super(message);
        }
    
    }
    
  • Teachers

    public class Teacher {
        public void checkScore(int score) throws ScoreException {
            if(score<0 || score>100) {
    //            throw new ScoreException();
                throw new ScoreException("You gave the wrong score, it should be 0-100 Between");
            } else {
                System.out.println("Normal results");
            }
        }
    }
    
  • Test Class

    public class Demo {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter a score:");
    
            int score = sc.nextInt();
    
            Teacher t = new Teacher();
            try {
                t.checkScore(score);
            } catch (ScoreException e) {
                e.printStackTrace();
            }
        }
    }
    

Tags: Java api Exception

Posted by JimmyD on Mon, 28 Jun 2021 04:14:47 +0930