Java study notes 5-class methods, java study notes 5 --
URL: http://www.cnblogs.com/archimedes/p/java-study-note5.html.
1. Method Control Process
There are three main process control structures in Java:
Sequential Structure
Select Structure
If statement (two-way selection structure) and switch statement (Multiple-Way Selection structure)
Loop Structure
For statement, while statement, do-while statement
Run a program:
Enter a year to determine whether it is a leap year. (Leap year: Can be divisible by 4, but cannot be divisible by 100, or can be divisible by 400)
public class test { public static void main(String[ ] args) throws IOException { int year; boolean IsLeapYear; System.out.println("Enter the year:"); BufferedReader in =new BufferedReader(new InputStreamReader(System.in)); year=(new Integer(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( "is not a leap year"); } }}
Java-related loop control is similar to the C language.
2. Exception Handling Overview
Basic concepts of exceptions:
An exception is a special running error object. It is part of the object-oriented specification and an object of the exception class. Many exception classes are declared in Java, each exception class represents a running error, which contains the running error information.
How to handle errors:
When an identifiable running error occurs during the Java program running, that is, an exception class corresponds to the error class, the system generates an object for the exception class, an exception occurs.
Exception Handling:
Advantages of Java Exception Handling Mechanism:
Separate Error Handling Code from common code
Group by error type and Difference
Capture and handle unpredictable errors
Overcome the problem of limited error information in traditional methods
Spread the error to the call stack
Exception events that occur during the program running can be divided into two types based on the severity of errors.
Error
Fatal, user programs cannot handle
The Error class is the parent class of all Error classes.
Exception
Non-lethal, programmed for capturing and Processing
The Exception class is the parent class of all Exception classes.
Hierarchy of exception and error classes:
Some common exceptions predefined by Java:
ArithmeticException: the division of integers is 0.
NullPointerException: The accessed object has not been instantiated.
NegativeArraySizeException: When an array is created, the number of elements is negative.
ArrayIndexOutOfBoundsException: when accessing an array element, the array subscript is out of bounds.
ArrayStoreException: The program attempts to access error data in the array.
FileNotFoundException: attempts to access a non-existing file
IOException: Common I/O errors
Exception Handling:
For checked exceptions, Java forces the program to handle them. There are two solutions: declaring and throwing an exception
Instead of handling exceptions in the current method, the exception is thrown to the call method to catch the exception. Use try {} catch () {} block to catch the exception, and handle the problem accordingly.
Declaration throws an exception
If the programmer does not want to handle exceptions in the current method, he can use the throws clause to declare that the exception will be thrown into the calling method.
If all methods have chosen to throw this exception, the JVM will capture it, output relevant error information, and terminate the program running. When an exception is thrown, any method can capture it and handle it accordingly.
For example:
public void openThisFile(String fileName) throws java.io.FileNotFoundException { //code for method }public void getCustomerInfo() throws java.io.FileNotFoundException { // do something this.openThisFile("customer.txt"); // do something }
If a FileNotfoundException exception is thrown in openThisFile, getCustomerInfo stops the execution and sends the exception to its caller.
Capture exceptions
Syntax format:
try { statement(s)} catch (exceptiontype name) { statement(s)} finally { statement(s)}
Description
Try statement, followed by code blocks that may generate exceptions
A catch statement followed by an exception handling statement. Two methods are usually used.
GetMessage () returns a string to describe the exception.
PrintStackTrace (), giving the call sequence of the method until the exception is generated.
The finally statement, whether or not exceptions occur in the try code segment, will be executed in the finally program code segment. Resources other than memory are usually released here
Notes
In the hierarchy tree of classes, the general exception types are placed behind, and the special ones are placed at the front.
For example:
import java.io.*; public class ExceptionTester { public static void main(String args[]) { System.out.println("Enter the first number:"); int number1 = Keyboard.getInteger(); System.out.println("Enter the second number:"); int number2 = Keyboard.getInteger(); System.out.print(number1 + " / " + number2 + "="); int result = number1 / number2; System.out.println(result); } }
The Keyboard class declaration is as follows:
import java.io.*; public class Keyboard{ static BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in)); public static int getInteger() { try { return (Integer.valueOf(inputStream.readLine().trim()).intValue()); } catch (Exception e) { e.printStackTrace(); return 0; } } public static String getString() { try { return (inputStream.readLine()); } catch (IOException e) { return "0"; } }}
Running 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. Method overload)
Multiple methods with the same name in a class. The parameters of these methods must be different. Java can identify the overloaded methods through different parameter lists: the number of parameters is different, or the parameter types are different.
The returned values can be the same or different. The value of overload is that it allows multiple methods to be accessed by using one method name.
For example:
class MethodOverloading { public void receive(int i){ System.out.println("Receive one int parameter. "); System.out.println("i="+i); } public void receive(double d){ System.out.println("Receive one double parameter. "); System.out.println("d="+d); } public void receive(String s){ System.out.println("Receive one String parameter. "); System.out.println("s="+s); } public void receive(int i,int j){ System.out.println("Receive two int parameters. "); System.out.println("i=" + i + " j=" + j); } public void receive(int i,double d){ System.out.println("Receive one int parameter and one double parameter. "); System.out.println("i=" + i + " d=" + d); } }public class test { public static void main(String args[]){ MethodOverloading m = new MethodOverloading(); m.receive(2); m.receive(5.6); m.receive(3,4); m.receive(7,8.2); m.receive("Is it fun?"); }}
Running result:
Receive one int parameter.
I = 2
Receive one double parameter.
D = 5.6
Receive two 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?
References:
Java programming-Tsinghua University