Java Learning note Methods for 5--classes

Source: Internet
Author: User
Tags integer division throw exception

This article address: http://www.cnblogs.com/archimedes/p/java-study-note5.html, reprint please indicate source address.

1, the method of the control process

There are three main types of process Control structures in Java:

Sequential structure

Select structure

If statement (two-way selection structure), switch statement (multi-channel selection structure)

Loop structure

For statement, while statement, Do-while statement

Run a program:

Enter a year to determine if it is a leap years. (Leap Year: divisible by 4 but not divisible by 100, or divisible by 400)
 Public classTest { Public Static voidMain (string[] args)throwsIOException {intYear ; Booleanisleapyear; System.out.println ("Enter the Year:"); BufferedReader in=NewBufferedReader (NewInputStreamReader (system.in)); year=(NewInteger (In.readline ())). Intvalue (); Isleapyear= ((year%4==0 && year%100! = 0) | | (year%400 = = 0)); if(isleapyear) {System.out.print (year); System.out.println ("is a leap year"); } Else{System.out.print (year); System.out.println ("Isn't a leap year"); }    }}

Because Java-related loop control is similar to C language, do not repeat

2. Introduction to Exception Handling

Basic concepts of Exceptions:

Also known as the exception, is a special run Error object, is a part of the object-oriented specification, is an object of the exception class, there are many exception classes declared in Java, each exception class represents a run error, the class contains the information of the run error

Ways to handle Errors:

Whenever a recognized run-time error occurs during a Java program run, i.e. the error has an exception class corresponding to it, the system produces an object of that exception class, which produces an exception

Exception handling:

Advantages of the Java exception handling mechanism:
    • Separating error-handling code from regular code

    • Grouping by error type and difference

    • Capturing and handling of unpredictable errors

    • Overcoming the problem of limited error information in traditional methods

    • Propagate errors to the call stack

Exception events that occur during program operation can be divided into two categories depending on the severity of the error.

Error

Fatal, the user program cannot process

The error class is the parent class of all the wrong classes

Abnormal

Non-lethal, can be programmed to capture and process

The exception class is the parent class of all exception classes

Hierarchy of exception and error classes:

Some common exceptions that are predefined by Java:

ArithmeticException: Divisor in integer division is 0

NullPointerException: The object accessed has not yet been instantiated

Negativearraysizeexception: The number of elements is negative when creating an array

ArrayIndexOutOfBoundsException: Array subscript out of bounds when accessing array elements

Arraystoreexception: The program tries to access the wrong type of data to the array

FileNotFoundException: Attempting to access a file that does not exist

IOException: Usual I/O error

Handling of Exceptions:

For check-type exceptions, Java forcing programs must be processed. There are two ways to handle this: declaring a throw exception

Instead of handling the exception within the current method, it throws an exception into the calling method to catch the exception, uses the try{} catch () {} block, catches the exception that occurred, and handles the corresponding

Declaration throws an exception

If the programmer does not want to handle the exception within the current method, you can use the throws clause declaration to throw the exception into the calling method

If all of the methods have chosen to throw this exception, the JVM will catch it, output the associated error message, and terminate the program's run. During an exception being thrown, any method can capture it and handle it accordingly.

As an example:

 Public void throws java.io.FileNotFoundException {      //code  }publicVoid  throws  java.io.FileNotFoundException {     // do something This    . Openthisfile ("Customer.txt");      // Do something  }

If a FileNotFoundException exception is thrown in Openthisfile, GetCustomerInfo will stop execution and pass this exception to its caller

Catching exceptions

Syntax format:
Try {    catch  (exceptiontype name) {    finally  {    statement (s)}

Description

Try statement followed by a code block that could produce an exception

Catch statement followed by an exception-handling statement, typically using two methods

GetMessage (), which returns a string that describes the exception that occurred.

Printstacktrace (), gives the sequence of calls to the method, until the location where the exception occurs

The finally statement, whether or not the try code fragment produces an exception, will be executed after the finally program code snippet. Usually frees resources other than memory here

Precautions

In the class hierarchy tree, the generic exception type is placed in the back, and the special is placed in front

As an example:

ImportJava.io.*;  Public classExceptiontester { Public Static voidMain (String args[]) {System.out.println ("Enter The first number:"); intNumber1 =Keyboard.getinteger (); System.out.println ("Enter The second number:"); intNumber2 =Keyboard.getinteger (); System.out.print (Number1+ "/" + number2 + "="); intresult = NUMBER1/number2;      SYSTEM.OUT.PRINTLN (result); } }

Among them, the declaration of the keyboard class is as follows:

ImportJava.io.*;  Public classkeyboard{StaticBufferedReader InputStream =NewBufferedReader (NewInputStreamReader (system.in));  Public Static intGetinteger () {Try {             return(Integer.valueof (Inputstream.readline (). Trim ()). Intvalue ()); } Catch(Exception e) {e.printstacktrace (); return0; }     }      Public StaticString getString () {Try {             return(Inputstream.readline ()); } Catch(IOException e) {return"0"; }       }}
Operation Result:

Enter the first number:

140

Enter the second number:

Abc

Java.lang.NumberFormatException:abc

At Java.lang.Integer.parseInt (integer.java:426)

At Java.lang.Integer.valueOf (integer.java:532)

At Keyboard.getinteger (keyboard.java:10)

At Exceptiontester.main (exceptiontester.java:7)

140/0=exception in thread "main" java.lang.ArithmeticException:/By zero

At Exceptiontester.main (exceptiontester.java:10)

3. Overloading of methods (overloading)

Multiple methods with the same name in a class, the parameters of which must be different, and Java can identify overloaded methods by different parameter lists: or different number of arguments, or different types of parameters

The return value can be the same or different; the value of overloading is that it allows access to multiple methods by using a method name

As an example:

classmethodoverloading { Public voidReceiveinti) {System.out.println ("Receive one int parameter."); System.out.println ("I=" +i); }         Public voidReceiveDoubled) {System.out.println ("Receive one double parameter."); System.out.println ("D=" +d); }         Public voidreceive (String s) {System.out.println ("Receive one String parameter."); System.out.println ("S=" +s); }        Public voidReceiveintIintj) {System.out.println ("Receive both int parameters."); System.out.println ("I=" + i + "j=" +j); }         Public voidReceiveintIDoubled) {System.out.println ("Receive one int parameter and one double parameter."); System.out.println ("I=" + i + "d=" +d); }    } Public classTest { Public Static voidMain (String args[]) {methodoverloading m=Newmethodoverloading (); M.receive (2); M.receive (5.6); M.receive (3,4); M.receive (7,8.2); M.receive ("Is it fun?"); }}
Operation Result:

Receive one int parameter.

i=2

Receive one double parameter.

d=5.6

Receive both int parameters.

I=3 j=4

Receive one int parameter and one double parameter.

I=7 d=8.2

Receive one String parameter.

S=is it fun?

Resources:

"Java Programming"--Tsinghua University

Java Learning note Methods for 5--classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.