search
HomeJavajavaTutorialDoes java have functions?

Does java have functions?

Nov 18, 2019 pm 01:51 PM
javafunction

Does java have functions?

#Does java have functions?

Java has functions. A function is an independent block of code defined in a class to implement a certain function. In Java, functions are also called methods.

The main function of the function is to improve the reusability of the code.

Functions are all run in stack memory; the running function is on the top of the stack.

Function format:

Modifier Return value type Function name ( [ Parameter type 1 parameter name 1, parameter type 2 parameter name 2.... ] ) {

// [] Ins the options, that is, the parameter is not necessary

execution statement ...

# Return return value; // The type of return value must be consistent with the return value type.

}

Explanation:

  • Modifier: It can be an access modifier or a function modifier (abstract, final , static, synchronized), or a combination of the two.

  • Return value type: The data type used to limit the return value of the function.

  • Parameter type: used to limit the data type passed when calling the function.

  • Parameter name: It is a variable used to receive the data passed when calling the method.

  • return: Used to receive methods and return values ​​of the specified type from the function.

  • Return value: This value will be returned to the caller of the function.

Example:

public class method {
    /*
     * 程序入口,主函数 .
     * 
     * @ 方法 <==> 函数,指的是同一个东西.
     */
    public static void main(String[] args) {
	// 通过函数名调用
	method01();
 
	method02(9, 3);
	System.out.println("5+6=" + add(5, 6));
    }
 
    /*
     * @ 函数的格式为:
     * 
     * @ 访问修饰符 返回值类型 函数名(参数类型1 参数名1,参数类型2 参数名2....){
     * 
     * @ 执行语句
     * 
     * @ return 返回值;//返回值的类型必须与返回值类型一致
     * 
     * @ }
     */
    /*
     * @ 声明一个静态函数method01() 无参数无返回值
     */
    static void method01() {
	System.out.println("这是method01方法,可以通过method01();调用.");
	// 这个return可以省略.每个函数都是以return结束,返回到函数调用处
	return;
    }
 
    /*
     * 有参数无返回值
     */
    static void method02(int num1, int num2) {
	method01();
	System.out.println("这是method02方法,第一个参数是" + num1 + "第二个参数是" + num2);
    }
 
    /*
     * 有返回值的返回值类型要和要返回的数据类型一致
     * 
     * @ 例如:计算两个整数的和,结果仍然是整型,返回值类型为int.返回值类型可以说基本数据类型,也可是自定义的数据类型
     */
    static int add(int num1, int num2) {
	int sum = 0; // 声明一个整形变量并初始化为0
	sum = num1 + num2;// 将num1和num2的和赋值给sum
	return sum;// 将sum的值返回到调用处
    }
 
}

Run result:

Does java have functions?

The above is the detailed content of Does java have functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Application Performance Monitoring (APM) ToolsJava Application Performance Monitoring (APM) ToolsJul 24, 2025 am 03:37 AM

Common JavaAPM tools include NewRelic, DatadogAPM, AppDynamics, SkyWalking, Pinpoint and Prometheus Grafana Micrometer combinations; whether APM is required depends on system lag, complex microservice calls, performance details and optimization requirements; APM should consider deployment methods, learning costs, performance impact, cost and integration capabilities; when using them, you should pay attention to reasonable configuration, sampling rate, alarm rules, and analyze the root cause in combination with code.

Building Reactive Java Applications with RxJavaBuilding Reactive Java Applications with RxJavaJul 24, 2025 am 03:35 AM

1.RxJava is a responsive framework based on observer pattern and functional programming, suitable for handling asynchronous and non-blocking tasks. 2. Core types include Observable, Flowable, Single, etc., which are used to represent different forms of data flow. 3. Data conversion and combination are performed through operators such as map, filter, and flatMap to simplify complex logic. 4. Use Schedulers.io(), Schedulers.computation(), AndroidSchedulers.mainThread() and other schedulers to control thread switching. 5. Specify the data flow start thread through subscribeOn, obse

Implementing a Thread-Safe Singleton in JavaImplementing a Thread-Safe Singleton in JavaJul 24, 2025 am 03:35 AM

When using double check lock to implement lazy loading singletons, the volatile keyword is required to ensure thread visibility and prevent instruction re-arrangement; 2. It is recommended to use static internal classes (BillPugh scheme) to implement thread-safe lazy loading singletons, because the JVM ensures thread safety and no synchronization overhead; 3. If you do not need lazy loading, you can use static constants to implement simple and efficient singletons; 4. When serialization is involved, enumeration method should be used, because it can naturally prevent multiple instance problems caused by reflection and serialization; in summary, general scenarios prefer static internal classes, and serialized scenarios to select enumerations. Both have the advantages of thread safety, high performance and concise code.

Comparing Java, Kotlin, and Scala for Backend DevelopmentComparing Java, Kotlin, and Scala for Backend DevelopmentJul 24, 2025 am 03:33 AM

Kotlinoffersthebestbalanceofbrevityandreadability,Javaisverbosebutpredictable,andScalaisexpressivebutcomplex.2.Scalaexcelsinfunctionalprogrammingwithfullsupportforimmutabilityandadvancedconstructs,KotlinprovidespracticalfunctionalfeatureswithinanOOPf

Managing Dependencies in a Large-Scale Java ProjectManaging Dependencies in a Large-Scale Java ProjectJul 24, 2025 am 03:27 AM

UseMavenorGradleconsistentlywithcentralizedversionmanagementandBOMsforcompatibility.2.Inspectandexcludetransitivedependenciestopreventconflictsandvulnerabilities.3.EnforceversionconsistencyusingtoolslikeMavenEnforcerPluginandautomateupdateswithDepend

Mastering Java 8 Streams and LambdasMastering Java 8 Streams and LambdasJul 24, 2025 am 03:26 AM

The two core features of Java8 are Lambda expressions and StreamsAPI, which make the code more concise and support functional programming. 1. Lambda expressions are used to simplify the implementation of functional interfaces. The syntax is (parameters)->expression or (parameters)->{statements;}, for example (a,b)->a.getAge()-b.getAge() instead of anonymous internal classes; references such as System.out::println can further simplify the code. 2.StreamsAPI provides a declarative data processing pipeline, the basic process is: create Strea

Java Security Tokenization and EncryptionJava Security Tokenization and EncryptionJul 24, 2025 am 03:24 AM

SecurityToken is used in Java applications for authentication and authorization, encapsulating user information through Tokenization to achieve stateless authentication. 1. Use the jjwt library to generate JWT, select the HS256 or RS256 signature algorithm and set the expiration time; 2. Token is used for authentication, Encryption is used for data protection, sensitive data should be encrypted using AES or RSA, and passwords should be stored with hash salt; 3. Security precautions include avoiding none signatures, setting the expiration time of tokens, using HTTPS and HttpOnlyCookies to store tokens; 4. In actual development, it is recommended to combine SpringSecurity and

The role of `var` for Local-Variable Type Inference in JavaThe role of `var` for Local-Variable Type Inference in JavaJul 24, 2025 am 03:23 AM

var was introduced in Java 10 for local variable type inference, to determine the type during compilation, and maintain static type safety; 2. It can only be used for local variables in methods with initialized expressions, and cannot be used for fields, parameters or return types; 3. Non-initialization, null initialization and lambda expression initialization are prohibited; 4. It is recommended to use them when the type is obvious to improve simplicity and avoid scenarios that reduce readability. For example, types should be explicitly declared when complex methods are called.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.