In the previous chapters we often used System.out.println(), so what is it?
println() is a method (Method), and System is a system class (Class), and out is a standard output object (Object). The usage of this sentence is to call the method println() in the standard output object out in the system class System.
A Java method is a collection of statements that together perform a function.
A method is an ordered combination of steps to solve a type of problem
Methods contained in classes or objects
Methods are created in the program and referenced elsewhere
Generally, defining a method includes the following syntax:
Modifier return value type method name (parameter type parameter name) {
...
Method body...
return return value;
}
A method contains a method header and a method body. Here are all the parts of a method:
Modifiers: Modifiers, which are optional, tell the compiler how to call the method. Defines the access type for this method.
Return value type: Methods may return values. returnValueType is the data type of the method return value. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword void .
Method name: is the actual name of the method. The method name and parameter list together form the method signature.
Parameter type: The parameter is like a placeholder. When the method is called, values are passed to the parameters. This value is called an actual parameter or variable. The parameter list refers to the parameter type, order and number of parameters of the method. Parameters are optional and methods can contain no parameters.
Method body: The method body contains specific statements that define the function of the method.
like:
publicstaticintage(intbirthday){...}
There can be multiple parameters:
staticfloatinterest(floatprincipal,intyear){...}
Note: In some other languages methods refer to procedures and functions. A method that returns a non-void return value is called a function; a method that returns a void return value is called a procedure.
The method below contains 2 parameters num1 and num2 and it returns the maximum value of these two parameters.
/**Returns the larger value of the two integer variable data*/
publicstaticintmax(intnum1,intnum2){
intresult;
if(num1>num2){
result=num1;
}else{
result=num2;
}
returnresult;
}
Java supports two ways of calling methods, depending on whether the method returns a value.
When a program calls a method, control of the program is transferred to the called method. Control is returned to the program when the return statement of the called method is executed or the method body closing bracket is reached.
When a method returns a value, the method call is usually treated as a value. For example:
intlarger=max(30,40);
If the method return value is void, the method call must be a statement. For example, the method println returns void. The following call is a statement:
System.out.println("WelcometoJava!");
The following example demonstrates how to define a method and how to call it:
publicclassTestMax{
/**Main method*/
publicstaticvoidmain(String[]args){
inti=5;
intj=2;
intk=max(i,j);
System.out.println("Themaximumbetween"+i+
"and"+j+"is"+k);
}
/**Returns the larger value of the two integer variables*/
publicstaticintmax(intnum1,intnum2){
intresult;
if(num1>num2){
result=num1;
}else{
result=num2;
}
returnresult;
}
}
The compilation and running results of the above example are as follows:
Themaximumbetween5and2is5
This program contains main method and max method. The Main method is called by the JVM. Other than that, the main method is no different from other methods.
The head of the main method remains unchanged, as shown in the example, with the modifiers public and static, returns a void type value, the method name is main, and takes a String[] type parameter. String[] indicates that the parameter is a string array.
This section explains how to declare and call a void method.
The following example declares a method named printGrade and calls it to print the given grade.
publicclassTestVoidMethod{
publicstaticvoidmain(String[]args){
printGrade(78.5);
}
publicstaticvoidprintGrade(doublescore){
if(score>=90.0){
System.out.println('A');
}
elseif(score>=80.0){
System.out.println('B');
}
elseif(score>=70.0){
System.out.println('C');
}
elseif(score>=60.0){
System.out.println('D');
}
else{
System.out.println('F');
}
}
}
The compilation and running results of the above example are as follows:
C
The printGrade method here is a void type method and it does not return a value.
A call to a void method must be a statement. Therefore, it is called as a statement on the third line of the main method. Just like any statement that ends with a semicolon.
When calling a method, you need to provide parameters, and you must provide them in the order specified in the parameter list.
For example, the following method prints a message n times in a row:
publicstaticvoidnPrintln(Stringmessage,intn){
for(inti=0;i<n;i++)
System.out.println(message);
}
The following example demonstrates the effect of passing by value.
This program creates a method that exchanges two variables.
publicclassTestPassByValue{
publicstaticvoidmain(String[]args){
intnum1=1;
intnum2=2;
System.out.println("Beforeswapmethod,num1is"+
num1+"andnum2is"+num2);
//Call the swap method swap(num1,num2);
System.out.println("Afterswapmethod,num1is"+
num1+"andnum2is"+num2);
}
/**Method to exchange two variables*/
publicstaticvoidswap(intn1,intn2){
System.out.println("tInsidetheswapmethod");
System.out.println("ttBeforeswappingn1is"+n1
+"n2is"+n2);
//Exchange the values of n1 and n2 inttemp=n1;
n1=n2;
n2=temp;
System.out.println("ttAfterswappingn1is"+n1
+"n2is"+n2);
}
}
The compilation and running results of the above example are as follows:
Beforeswapmethod,num1is1andnum2is2
Insidetheswapmethod
Beforeswappingn1is1n2is2
Afterswappingn1is2n2is1
Afterswapmethod,num1is1andnum2is2
Call the swap method passing two parameters. Interestingly, the values of the actual parameters do not change after the method is called.
The max method used above only applies to int type data. But what if you want to get the maximum value of two floating point types of data?
The solution is to create another method with the same name but different parameters, as shown in the following code:
publicstaticdoublemax(doublenum1,doublenum2){
if(num1>num2){
returnnum1;
}else{
returnnum2;
}
}
If you pass an int parameter when calling the max method, the max method of the int parameter will be called;
If a double parameter is passed, the max method body of the double type will be called. This is called method overloading;
That is, two methods of a class have the same name, but different parameter lists.
The Java compiler determines which method should be called based on the method signature.
Method overloading can make the program clearer and easier to read. Methods that perform closely related tasks should use the same name.
Overloaded methods must have different parameter lists. You can't overload methods based solely on modifiers or return types.
The scope of a variable is the portion of the program that the variable can be referenced from.
Variables defined within a method are called local variables.
The scope of a local variable starts from its declaration and ends at the end of the block that contains it.
Local variables must be declared before they can be used.
The parameter scope of a method covers the entire method. The parameter is actually a local variable.
The variables declared in the initialization part of the for loop have scope throughout the loop.
But the scope of application of the variable declared in the loop body is from its declaration to the end of the loop body. It contains variable declarations as shown below:
You can declare a local variable with the same name multiple times within a method, in different non-nested blocks, but you cannot declare a local variable twice within a nested block.
Sometimes you want to pass messages to a program while it is running. This is accomplished by passing command line arguments to the main() function.
Command line parameters are the information immediately following the program name when executing the program.
The following program prints all command line arguments:
publicclassCommandLine{
publicstaticvoidmain(Stringargs[]){
for(inti=0;i<args.length;i++){
System.out.println("args ["+i+"]:"+args[i]);
}
}
}
Run the program as shown below:
javaCommandLinethisisacommandline200-100
The running results are as follows:
args[0]:this
args[1]:is
args[2]:a
args[3]:command
args[4]:line
args[5]:200
args[6]:-100
When an object is created, constructors are used to initialize the object. The constructor has the same name as the class it belongs to, but the constructor has no return value.
Constructors are typically used to assign initial values to instance variables of a class, or to perform other necessary steps to create a complete object.
Regardless of whether you customize the constructor or not, all classes have constructors because Java automatically provides a default constructor that initializes all members to 0.
Once you define your own constructor, the default constructor becomes invalid.
Here is an example using constructor methods:
//A simple constructor static classMyClass{
intx;
//The following is the constructor MyClass(){
x=10;
}
}
You can initialize an object by calling the constructor like this:
publicclassConsDemo{
publicstaticvoidmain(Stringargs[]){
MyClasst1=newMyClass();
MyClasst2=newMyClass();
System.out.println(t1.x+""+t2.x);
}
}
Most of the time a constructor with parameters is needed.
Here is an example using constructor methods:
//A simple constructor classMyClass{
intx;
//The following is the constructor MyClass(inti){
x=i;
}
}
You can initialize an object by calling the constructor like this:
publicclassConsDemo{
publicstaticvoidmain(Stringargs[]){
MyClasst1=newMyClass(10);
MyClasst2=newMyClass(20);
System.out.println(t1.x+""+t2.x);
}
}
The running results are as follows:
1020
Starting with JDK 1.5, Java supports passing variable parameters of the same type to a method.
The declaration of the variadic parameters of the method looks like this:
typeName...parameterName
In a method declaration, add an ellipsis (...) after specifying the parameter type.
Only one variable parameter can be specified in a method, and it must be the last parameter of the method. Any ordinary parameters must be declared before it.
publicclassVarargsDemo{
publicstaticvoidmain(Stringargs[]){
//Call the variable parameter method printMax(34,3,3,2,56.5);
printMax(newdouble[]{1,2,3});
}
publicstaticvoidprintMax(double...numbers){
if(numbers.length==0){
System.out.println("Noargumentpassed");
return;
}
doubleresult=numbers[0];
for(inti=1;i<numbers.length;i++)
if(numbers[i]>result){
result=numbers[i];
}
System.out.println("Themaxvalueis"+result);
}
}
The compilation and running results of the above example are as follows:
Themaxvalueis56.5
Themaxvalueis3.0
Java allows the definition of such a method, which is called before the object is destructed (recycled) by the garbage collector. This method is called finalize(), which is used to clear the recycled object.
For example, you can use finalize() to ensure that a file opened by an object is closed.
In the finalize() method, you must specify the operations to be performed when the object is destroyed.
The general format of finalize() is:
protectedvoidfinalize()
{
//Terminal code here}
The keyword protected is a qualifier that ensures that the finalize() method will not be called by code outside the class.
Of course, Java's memory recycling can be automatically completed by the JVM. If you use it manually, you can use the method above.
publicclassFinalizationDemo{
publicstaticvoidmain(String[]args){
Cakec1=newCake(1);
Cakec2=newCake(2);
Cakec3=newCake(3);
c2=c3=null;
System.gc();//Calling Java garbage collector}
}
classCakeextendsObject{
privateintid;
publicCake(intid){
this.id=id;
System.out.println("CakeObject"+id+"iscreated");
}
protectedvoidfinalize()throwsjava.lang.Throwable{
super.finalize();
System.out.println("CakeObject"+id+"isdisposed");
}
}
Running the above code, the output results are as follows:
C:1>javaFinalizationDemo
CakeObject1iscreated
CakeObject2iscreated
CakeObject3iscreated
CakeObject3isdisposed
CakeObject2isdisposed