Java程序示例:一个没有参数和返回类型的方法

WBOY
WBOY 转载
2023-09-17 11:13:02 577浏览

Java程序示例:一个没有参数和返回类型的方法

首先,让我们熟悉一下语法、示例,然后最后再进行实现。

Java中的方法非常重要,因为它允许重复使用相同的代码,减少代码中需要编写的语句数量。

有三个主要部分的方法,以使其可执行。

  • 方法的声明。

  • 方法的定义。

  • 调用该方法。

方法调用是最后一步,而其他两个步骤可以互换。唯一需要记住的是,在调用方法之前必须先声明它。

Syntax

To create a method without any parameter and return type, the following syntax is considered.

Class class_name{
   function _name() {
      Statement 1;
      Statement 2;
      .
      .
      Statement n;
      //an optional return 
      return;
   }
   Main function() {
      // invoking the above function
      function_name();
   }
}

在一个类中创建一个空参数列表的方法。方法内部写入语句,可能会在最后加上一个空的返回语句。然后在主方法中调用这个方法。

Example

下面的程序是为了展示如何创建一个既没有参数也没有返回类型的方法。

A class named Wish is created within which, a method named wish() with return type void is created denoting it does not return any value, also it does not consist of any parameter. A statement is written within the wish() method and is displayed by invoking this method in the main method.

// Java Program to demonstrate a method without Parameters and Return Type
public class Wish {
	// Declaration and Definition of the method
	public static void wish(){
		System.out.println("Good Morning! Have a nice day");
	}
	public static void main(String args[]){
		// Calling the method without any parameters
		wish ();
	}
}

输出

Good Morning! Have a nice day

Example

下面的程序是为了展示如何创建一个既没有参数也没有返回类型的方法。

A class named Wish is created within which, a method named wish() with return type void is created denoting it does not return any value, also it does not consist of any parameter. The statements written inside the wish() method are displayed by invoking the method in the main method.

// Java Program to demonstrate a method without Parameters and Return Type
public class Wish {
	// Declaration and Definition of the method
	public static void wish(){
		System.out.println("Congratulations! Have a great professional life");
			//It is optional to use a return statement here.
			return;
	}
	public static void main(String args[]){
		// Calling the method without any parameters
		wish();
	}
}

输出

Congratulations! Have a great professional life

结论

本文阐述了如何在Java中定义一个没有参数和返回值的方法。我们从语法开始,进一步看到了一个示例和两个Java程序,以便清楚地了解这个主题。

以上就是Java程序示例:一个没有参数和返回类型的方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除