Java Methods

JK JK 2038 
Created at
Updated at  
7,151 0 0

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.


Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:

public class Main {
  static void myMethod() {
    // code to be executed
  }
}

Example Explained

  • myMethod() is the name of the method
  • static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
  • void means that this method does not have a return value. You will learn more about return values later in this chapter

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
  }
}

// Outputs "I just got executed!"

A method can also be called multiple times:

public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }

  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

// I just got executed!
// I just got executed!
// I just got executed!

Parameters and Arguments

Information can be passed to methods as parameter. Parameters act as variables inside the method.

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }

  public static void main(String[] args) {
    myMethod("Liam");
    myMethod("Jenny");
    myMethod("Anja");
  }
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

Multiple Parameters

You can have as many parameters as you like:

public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

  public static void main(String[] args) {
    myMethod("Liam", 5);
    myMethod("Jenny", 8);
    myMethod("Anja", 31);
  }
}

// Liam is 5
// Jenny is 8
// Anja is 31

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:

public class Main {
  static int myMethod(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(3));
  }
}
// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(5, 3));
  }
}
// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read and maintain):

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    int z = myMethod(5, 3);
    System.out.println(z);
  }
}
// Outputs 8 (5 + 3)

A Method with If...Else

It is common to use if...else statements inside methods:

public class Main {

  // Create a checkAge() method with an integer variable called age
  static void checkAge(int age) {

    // If age is less than 18, print "access denied"
    if (age < 18) {
      System.out.println("Access denied - You are not old enough!");

    // If age is greater than, or equal to, 18, print "access granted"
    } else {
      System.out.println("Access granted - You are old enough!");
    }

  }

  public static void main(String[] args) {
    checkAge(20); // Call the checkAge method and pass along an age of 20
  }
}

// Outputs "Access granted - You are old enough!"

Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of different type:

static int plusMethodInt(int x, int y) {
  return x + y;
}

static double plusMethodDouble(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethodInt(8, 5);
  double myNum2 = plusMethodDouble(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

static int plusMethod(int x, int y) {
  return x + y;
}

static double plusMethod(double x, double y) {
  return x + y;
}

public static void main(String[] args) {
  int myNum1 = plusMethod(8, 5);
  double myNum2 = plusMethod(4.3, 6.26);
  System.out.println("int: " + myNum1);
  System.out.println("double: " + myNum2);
}

 

Tags Java Java Methods Java Parameters Method Overloading Facebook X
Comments 0
Similar posts
  1. Java Scope
    7,181
  2. Java Recursion
    7,245
  3. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,012
  4. Java Classes and Objects
    7,177
  5. Java Switch Statements
    7,489
  6. Java Short Hand If...Else (Ternary Operator)
    7,660
  7. Java If ... Else
    7,489
  8. Java Packages
    7,235
  9. Java Inheritance (Subclass and Superclass)
    7,234
  10. Java Math
    7,513
  11. Java Variables
    7,556
  12. Java Comments
    8,177
  13. Java Polymorphism
    7,114
  14. The Print() Method
    7,216
  15. Java Syntax
    7,536
  16. Java Getting Started
    7,485
  17. Java Inner Classes
    7,137
  18. What is Java?
    7,144
  19. Machine Learning Types and Programming Languages
    7,317
  20. Java Tutorials associated with AP Computer Science A
    7,748
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,240
  22. Java Servlet Example
    7,175
  23. Difference between Java and Javascript
    7,719
  24. Challenge: One Code Problem Per Day
    1,242
  1. How do I replace content that based on the HTML UI Template
    7,211
  2. Dataset of California Foodbanks
    7,227
  3. Java Abstract Classes and Methods
    7,846
  4. Java Arrays
    8,937
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    553
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    501
  3. Michael Jackson's Billie Jean
    346
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    241
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    262
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    285
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    302
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    337
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,008
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    486
  11. The Evolution and Production Reality of Agentic AI
    381
  12. How to Activate or Waive Your UIUC Student Health Insurance
    478
  13. Complete Guide to Building a Machine Learning Model
    500
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,573
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    519
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,267
  17. Clean Python Environments: The Power of venv vs. Docker
    1,049
  18. What is Docker? Why is Docker also useful in a development environment?
    771
  19. UIUC 2026-2027 Academic Calendar
    1,896
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,011
  21. Open-Source LLMs: The AI Revolution
    937
  22. Resume 2.0: Leveling Up for My First Software Gig
    2,750
  23. Not everyone will understand what this man just did
    2,272
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,789
  25. Unpacking IU's Shopper
    940
  26. Jackie Chan's Police Story: The Action Masterpiece
    816
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,132
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,347
  29. Open Databases for Sex Crime Occurrences in the U.S.
    907
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,157
  31. My First Day at University of Illinois-Urvana Champaign
    1,341
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,351
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,432
  34. Sipping the Stars: My Starbucks Adventure
    9,996
  35. Exciting explore at Sequoia National Park
    7,833
  36. My Life Shot at Death Valley
    1,963
  37. Ip Man fights with Muay Thai Master
    1,098
  38. Mad Clown - Don't Die
    1,211
  39. How to get Student Enrollment and Degree Verification at UIUC
    5,525
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,055
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,302
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,120
  43. 10CM - To Reach You (너에게 닿기를)
    1,306
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,712
  45. BOYNEXTDOOR - If I Say I Love You
    1,336
  46. The Future of Software Engineer - AI Engineering
    1,059
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,062
  48. Lie - Legend song by BIGBANG
    7,958
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,037
  50. Reimbursement after Vaccination at McKinley Health Center
    1,167