


How to define a method in Java. Declaration syntax and parameter passing of method
May 20, 2025 pm 08:18 PMThe basic structure of defining methods in Java includes access modifiers, return types, method names, and parameter lists. There are two ways to pass parameter: 1. Value pass, which is suitable for basic data types, and modifications within the method do not affect the original value; 2. Reference pass, which is suitable for reference types, and modifications within the method will affect the original object.
In Java, defining methods is a basic skill, which not only involves the declarative syntax of methods, but also includes understanding how parameters are passed and how these parameters are processed in methods. Today, I will take you into delving into the method definition and parameter passing in Java, combining some practical code examples and my personal experience to help you better grasp these concepts.
Method definitions in Java seem simple, but they actually contain many subtleties. Let's start with the most basic syntax:
public static void main(String[] args) { // Method body}
This is a typical definition of main method, which shows the basic structure of the method: access modifier (public), return type (void), method name (main), parameter list (String[] args), and method body (code within {}). This structure is the basic template for all Java methods.
When defining a method, you need to consider the following points:
- Access modifier : Determines the visibility of the method, such as public, private, protected, or default (no modifier).
- Return type : Specifies the type of value returned after the method is executed. It can be a primitive type (such as int, boolean) or a reference type (such as String, custom class). If there is no return value, use void.
- Method name : Follow CamelCase, it must be meaningful and easy to understand.
- Parameter list : can be empty or contain multiple parameters, each parameter consisting of type and name, separated by commas.
Now, let's dive into parameter passing in depth. In Java, there are two ways to pass parameter: value pass and reference pass.
Value passing is suitable for basic data types (such as int, double, boolean, etc.). When you pass a value of a primitive type, you are actually passing a copy of the value, so the modification of the parameters inside the method will not affect the original value.
public class ValuePassingExample { public static void modifyValue(int number) { number = number * 2; System.out.println("Inside method: " number); } public static void main(String[] args) { int originalValue = 10; System.out.println("Before method call: " originalValue); modifyValue(originalValue); System.out.println("After method call: " originalValue); } }
Run this code and you will find that originalValue
does not change before and after the method call, because it is passed through the value.
Reference pass is suitable for reference types (such as arrays, objects, etc.). When you pass a reference type, the reference to the object is passed, so the modification of parameters inside the method will affect the original object.
public class ReferencePassingExample { public static void modifyArray(int[] array) { array[0] = array[0] * 2; System.out.println("Inside method: " array[0]); } public static void main(String[] args) { int[] originalArray = {10}; System.out.println("Before method call: " originalArray[0]); modifyArray(originalArray); System.out.println("After method call: " originalArray[0]); } }
In this example, the first element of the array changes before and after the method call, because the array is passed by reference.
In actual programming, it is crucial to understand how parameters are passed. For example, reference passing can be more efficient when dealing with large objects, but also requires careful handling, as improper modifications can lead to unexpected side effects.
In addition, there are some details and best practices to be aware of:
- Method overloading : Java allows multiple methods of the same name to be defined in a class, as long as their parameter list is different. This is a powerful feature that provides different implementations based on different parameter types or numbers.
- Variable parameters : Using the
...
syntax, you can define a method to accept any number of parameters of the same type. For example,public void printNumbers(int... numbers)
. - Default parameter value : Java does not support the default value of method parameters, but similar effects can be achieved through method overloading.
In my development experience, I found that clear method naming and annotation are key to keeping code readable and maintainable. At the same time, rational use of method overloading and variable parameters can make your API design more flexible and user-friendly.
In short, method definition and parameter passing in Java seem simple, but it contains many details that require in-depth understanding. Through practice and continuous learning, you will be able to use these features more effectively and write more efficient and easier to maintain code.
The above is the detailed content of How to define a method in Java. Declaration syntax and parameter passing of method. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Ethereum is a decentralized application platform based on smart contracts, and its native token ETH can be obtained in a variety of ways. 1. Register an account through centralized platforms such as Binance and Ouyiok, complete KYC certification and purchase ETH with stablecoins; 2. Connect to digital storage through decentralized platforms, and directly exchange ETH with stablecoins or other tokens; 3. Participate in network pledge, and you can choose independent pledge (requires 32 ETH), liquid pledge services or one-click pledge on the centralized platform to obtain rewards; 4. Earn ETH by providing services to Web3 projects, completing tasks or obtaining airdrops. It is recommended that beginners start from mainstream centralized platforms, gradually transition to decentralized methods, and always attach importance to asset security and independent research, to

The most suitable tools for querying stablecoin markets in 2025 are: 1. Binance, with authoritative data and rich trading pairs, and integrated TradingView charts suitable for technical analysis; 2. Ouyi, with clear interface and strong functional integration, and supports one-stop operation of Web3 accounts and DeFi; 3. CoinMarketCap, with many currencies, and the stablecoin sector can view market value rankings and deans; 4. CoinGecko, with comprehensive data dimensions, provides trust scores and community activity indicators, and has a neutral position; 5. Huobi (HTX), with stable market conditions and friendly operations, suitable for mainstream asset inquiries; 6. Gate.io, with the fastest collection of new coins and niche currencies, and is the first choice for projects to explore potential; 7. Tra

The real use of battle royale in the dual currency system has not yet happened. Conclusion In August 2023, the MakerDAO ecological lending protocol Spark gave an annualized return of $DAI8%. Then Sun Chi entered in batches, investing a total of 230,000 $stETH, accounting for more than 15% of Spark's deposits, forcing MakerDAO to make an emergency proposal to lower the interest rate to 5%. MakerDAO's original intention was to "subsidize" the usage rate of $DAI, almost becoming Justin Sun's Solo Yield. July 2025, Ethe

What is Treehouse(TREE)? How does Treehouse (TREE) work? Treehouse Products tETHDOR - Decentralized Quotation Rate GoNuts Points System Treehouse Highlights TREE Tokens and Token Economics Overview of the Third Quarter of 2025 Roadmap Development Team, Investors and Partners Treehouse Founding Team Investment Fund Partner Summary As DeFi continues to expand, the demand for fixed income products is growing, and its role is similar to the role of bonds in traditional financial markets. However, building on blockchain

Table of Contents Crypto Market Panoramic Nugget Popular Token VINEVine (114.79%, Circular Market Value of US$144 million) ZORAZora (16.46%, Circular Market Value of US$290 million) NAVXNAVIProtocol (10.36%, Circular Market Value of US$35.7624 million) Alpha interprets the NFT sales on Ethereum chain in the past seven days, and CryptoPunks ranked first in the decentralized prover network Succinct launched the Succinct Foundation, which may be the token TGE

A verbal battle about the value of "creator tokens" swept across the crypto social circle. Base and Solana's two major public chain helmsmans had a rare head-on confrontation, and a fierce debate around ZORA and Pump.fun instantly ignited the discussion craze on CryptoTwitter. Where did this gunpowder-filled confrontation come from? Let's find out. Controversy broke out: The fuse of Sterling Crispin's attack on Zora was DelComplex researcher Sterling Crispin publicly bombarded Zora on social platforms. Zora is a social protocol on the Base chain, focusing on tokenizing user homepage and content

Directory What is Zircuit How to operate Zircuit Main features of Zircuit Hybrid architecture AI security EVM compatibility security Native bridge Zircuit points Zircuit staking What is Zircuit Token (ZRC) Zircuit (ZRC) Coin Price Prediction How to buy ZRC Coin? Conclusion In recent years, the niche market of the Layer2 blockchain platform that provides services to the Ethereum (ETH) Layer1 network has flourished, mainly due to network congestion, high handling fees and poor scalability. Many of these platforms use up-volume technology, multiple transaction batches processed off-chain

The failure to register a Binance account is mainly caused by regional IP blockade, network abnormalities, KYC authentication failure, account duplication, device compatibility issues and system maintenance. 1. Use unrestricted regional nodes to ensure network stability; 2. Submit clear and complete certificate information and match nationality; 3. Register with unbound email address; 4. Clean the browser cache or replace the device; 5. Avoid maintenance periods and pay attention to the official announcement; 6. After registration, you can immediately enable 2FA, address whitelist and anti-phishing code, which can complete registration within 10 minutes and improve security by more than 90%, and finally build a compliance and security closed loop.
