Common API & Exceptions

1. Packaging

1.1 Basic Types of Packaging (Memory)

  • The Role of Basic Types of Packaging Classes

    The advantage of encapsulating basic data types as objects is that more functional methods can be defined in the objects to manipulate the data.

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

  • Packaging classes corresponding to basic types

    Basic data types Packaging
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    char Character
    boolean Boolean

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 name Explain
    public Integer(int value) Create Integer objects based on int values (obsolete)
    public Integer(String s) Create Integer objects based on 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 Integer objects based on int values (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 value Of (int i): Returns an Integer instance representing the specified int value
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //Public static Integer value Of (String): 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)

  • Converting int to String

    • Conversion mode

      • Way 1: Add an empty string directly after the number
      • Mode 2: valueOf() through the static method of String class
    • 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

      • Way 1: First convert the string number to Integer, and then call the valueOf() method
      • Mode 2: Conversion through 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 the program to achieve the final output result: "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 strings 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 and 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 int arrays
            Arrays.sort(arr);
    
            //The elements in the sorted int array are spliced together to form a string. String Builder is used for splicing.
            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 Unpacking (Understanding)

  • Automatic packing

    Converting basic data types to corresponding packaging class types

  • Auto-unboxing

    Converting packaging class types to corresponding basic data types

  • Sample code

    Integer i = 100;  // Automatic packing
    i += 200;         // i = i + 200; I + 200 automatic unpacking; i = i + 200; automatic packing
    

2. Time and Date Class

2.1 Date class (application)

  • Overview of the Date class

    Date represents a specific time, accurate to milliseconds

  • Date Class Construction Method

    Method name Explain
    public Date() Assign a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
    public Date(long date) Assign a Date object and initialize it to represent the number of milliseconds specified from the standard reference 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 is 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 the standard baseline time
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

2.2Date Class Common Methods (Application)

  • common method

    Method name Explain
    public long getTime() What you get is 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 of milliseconds
  • Sample code

    public class DateDemo02 {
        public static void main(String[] args) {
            //Create a 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 time, given a value of milliseconds
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

2.3 SimpleDateFormat class (application)

  • Summary of SimpleDateFormat Classes

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

    We focus on date formatting and parsing.

  • SimpleDateFormat Class Construction Method

    Method name Explain
    public SimpleDateFormat() Construct a SimpleDateFormat using default mode and date format
    public SimpleDateFormat(String pattern) Construct a SimpleDateFormat using the given pattern and default date format
  • Common methods of SimpleDateFormat classes

    • Formatting (from Date to String)
      • public final String format(Date date): Format the date into a date/time string
    • Parsing (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 instrumental cases (application)

  • Case requirements

    Define a Date Utils class, which contains two methods: converting the date to a string in a specified format; parsing the string to a date in a specified format, and then defining a Date Demo to test the method of the Date Utils class.

  • code implementation

    • Tool class
    public class DateUtils {
        private DateUtils() {}
    
        /*
            Converts the date to a specified format string
            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;
        }
    
    
        /*
            Resolve 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 a 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)

  • Overview of Calendar Classes

    Calendar provides some methods for conversion between a particular instant and a set of calendar fields, and for manipulating calendar fields

    Calendar provides a class method getInstance for obtaining 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 right now = Calendar. getInstance ();

  • Common methods of Calendar class

    Method name Explain
    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 given calendar field from a specified amount of time according to calendar rules
    public final void set(int year,int month,int date) Set the month and day of the current calendar
  • Sample code

    public class CalendarDemo {
        public static void main(String[] args) {
            //Get Calendar Class Objects
            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 after 10 years
    //        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 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");
    
        }
    }
    

2.6 February Day Case (Application)

  • Case requirements

    How many days are there in February of any year?

  • code implementation

    public class CalendarTest {
        public static void main(String[] args) {
            //Keyboard entry for any year
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the year:");
            int year = sc.nextInt();
    
            //Setting the year, month and day of the calendar object
            Calendar c = Calendar.getInstance();
            c.set(year, 2, 1);
    
            //March 1st is 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 2000, there were" + date + "day");
        }
    }
    

3. Abnormality

3.1 Abnormality (Memory)

  • An overview of anomalies

    An exception is an abnormal situation in a program.

  • Abnormal Architecture

    [External Link Picture Transfer Failure (img-mK0k8XNy-1565866637065) (img 01.png)]

3.2 JVM default way to handle exceptions (understand)

  • If there is a problem with the program, we do not do any processing, and eventually the JVM will do the default processing. The processing method has the following two steps:

  • The name of the exception, the cause of the error and the location of the exception are output to the console.

  • Program stop execution

3.3try-catch approach to exception handling (application)

  • Definition format

    try {
    	Code that may have exceptions;
    } catch (variable name of exception class name){
    	Exception handling code;
    }
    
  • Execution process

    • The program starts with the code in try
    • If an exception occurs, it jumps to the corresponding catch to execute.
    • After execution, the program can continue to execute.
  • 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 visited does not exist, please go back and modify it to the correct index");
                e.printStackTrace();
            }
        }
    }
    

3.4 Throwable Membership Method (Application)

  • common method

    Method name Explain
    public String getMessage() Returns the detailed message string for this throwable
    public String toString() Returns this throwable brief 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 to String (): Returns this throwable short description
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace(): Output exceptional error information to the 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 Differences between compile-time exceptions and run-time exceptions (memory)

  • Compile-time exception

    • All Exception classes and their subclasses
    • Processing must be displayed, otherwise the program will fail and cannot be compiled.
  • Runtime exception

    • All RuntimeException classes and their subclasses
    • No display processing is required, and it can also be handled as an exception at compilation time.

3.6 throws to handle exceptions (application)

  • Definition 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 exception
        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 exception
        public static void method() throws ArrayIndexOutOfBoundsException {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
        }
    }
    
  • Matters needing attention

    • The throws format follows the parentheses of the method
    • Compile-time exceptions must be handled. There are two solutions: try... catch... Or throws, if throws are used, who calls whom to handle them in the future
    • Runtime exceptions can be left untreated. When problems arise, we need to come back and modify the code.

3.7 Differences between throws and throws (Memory)

[External Link Picture Transfer Failure (img-RcCRvqhW-1565866637065) (img 02.png)]

3.8 Custom Exceptions (Applications)

  • 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 a wrong score. The score should be 0.-100 Between");
            } else {
                System.out.println("Normal performance");
            }
        }
    }
    
  • 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();
            }
        }
    }
    

    if(score<0 || score>100) {
    // throw new ScoreException();
    throw new ScoreException("You gave the wrong score, the score should be between 0 and 100");
    } else {
    System.out.println("Normal Achievement");
    }
    }
    }

  • 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();
            }
        }
    }
    

Keywords: Java jvm

Added by big_c147 on Thu, 15 Aug 2019 17:22:36 +0300