METHOD OVERLOADING.ZIP

Java Methods  

(updated at May 10, 2024)   124  
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 functio...





Java Methods

JK1436 
Created at Jul 15, 2023 06:47:31
Updated at May 10, 2024 14:09:15 
125   0   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 Share on Facebook Share on X

◀ PREVIOUS
Java Arrays

▶ NEXT
Java Scope

  Comments 0
Login for comment
OTHER POSTS IN THE SAME CATEGORY

Java Servlet Example

(created at Feb 19, 2024)

How do I replace content that based on the HTML UI Template

(created at Feb 12, 2024)

Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows

(created at Jan 28, 2024)

Dataset of California Foodbanks

(updated at Feb 12, 2024)

Java Tutorials associated with AP Computer Science A

(updated at Jun 15, 2024)

Java Inner Classes

(updated at May 10, 2024)

Java Polymorphism

(created at Jul 18, 2023)

Java Inheritance (Subclass and Superclass)

(updated at May 10, 2024)

Java Packages

(updated at May 10, 2024)

Java Abstract Classes and Methods

(updated at Jan 02, 2024)

Java Classes and Objects

(updated at May 10, 2024)

Java Recursion

(updated at May 10, 2024)

Java Scope

(updated at May 10, 2024)

Java Arrays

(updated at May 13, 2024)

Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue

(updated at May 13, 2024)

Java Switch Statements

(updated at May 15, 2024)

Java Short Hand If...Else (Ternary Operator)

(updated at May 15, 2024)

Java If ... Else

(updated at May 15, 2024)

Java Math

(updated at May 15, 2024)

Java Variables

(updated at May 15, 2024)

Java Comments

(updated at May 15, 2024)

The Print() Method

(updated at May 10, 2024)

Java Syntax

(updated at May 15, 2024)

Java Getting Started

(updated at May 15, 2024)

What is Java?

(created at Jul 07, 2023)

UPDATES

Block unwanted URLs for comfortable web browsing with Chrome Addon - URL Blocker

(updated at Nov 01, 2024)

The Gigant Cowboys of Virginia City, Nevada 1889 - AI Generated Photos

(updated at Oct 28, 2024)

Sushi Koto: The "Ohtani" Sushi Spot in Irvine

(created at Oct 26, 2024)

Irvine Restaurant American-Style Vietnamese Food Brodard (ft. Ultimate Spring Roll)

(updated at Oct 25, 2024)

Modern Web Indexing Technology - IndexNow

(updated at Oct 24, 2024)

Key Differences in Gen Z/Alpha/Zalpha based on Upbringing and Life Experiences

(updated at Oct 22, 2024)

Zalpha Generation: A New Term for the Children of Gen Z and Millennials

(updated at Oct 22, 2024)

Zalpha: A Global Trend, Not Just a Distant Concept

(updated at Oct 22, 2024)

The Generation Corona (+ Gen Z) is grappling with how to communicate and live alongside Gen Alpha

(updated at Oct 21, 2024)

Porto's Bakery in Buena Park: A Review from Irvine

(created at Oct 20, 2024)

Starship, Super Heavy, Successful Ground Landing

(updated at Oct 19, 2024)

Understanding Purdue University - a public land-grant research university

(updated at Oct 18, 2024)

Understanding Texas A&M - a leading research university, receiving significant funding from both the government and private sector

(updated at Oct 18, 2024)

Exploring UC Davis (aka UCD) - Schools and Majors

(updated at Oct 16, 2024)

AI Generated One-Punch Man with old school style TV shows

(updated at Oct 15, 2024)

One-Punch Man Analysis: The Bald Cape Hero

(updated at Oct 15, 2024)

Why One-Punch Man is a Great Action Anime?

(updated at Oct 15, 2024)

The War of Dogs and Cats - AI-Generated Video by AlgoContent

(updated at Oct 15, 2024)

Dreamy indie band Room402's song "Like the Moon in the Daytime" with AI-generated video

(updated at Oct 15, 2024)

One-Punch Man's Saitama: Motivational Quotes and the Hero's Story

(updated at Oct 13, 2024)

Cream Pan: A Must-Visit Japanese Bakery in Fountain Valley

(created at Oct 13, 2024)

NewJeans - Chicago Live at Lollapalooza 2023

(updated at Oct 12, 2024)

One-Punch Man: Saitama's Promotion Journey and the Final Goal as a Hero

(updated at Oct 12, 2024)

One-Punch Man Combat Power Rankings

(created at Oct 12, 2024)

Difference in HEAD and GET for HTTP Request - why HEAD Request could be used for DDoS Attack?

(updated at Oct 11, 2024)

AI Generated Sailor Moon Video - In the name of justice, I will not forgive you!

(updated at Oct 11, 2024)

Snack that makes my mouth happy when winter comes from the U.S - Hot Pockets

(updated at Oct 11, 2024)

One-Punch Man Crafted by AI - Witness the Limitless Power of Sora AI

(updated at Oct 11, 2024)

My chrome browser is annoying me by Language - How do I change the default language?

(updated at Oct 11, 2024)

AI-Generated Berserk: A Majestic Sight

(updated at Oct 11, 2024)

Global Electronic Medicine Trends and Market Outlook 

(updated at Oct 09, 2024)

What is Google Analytics?

(updated at Oct 09, 2024)

Understanding the Key Differences Between GIS and LBS: Purpose, Technology, and Applications

(updated at Oct 09, 2024)

The Evolution and Applications of Geographic Information Systems: From Thematic Mapping to Efficient Data Analysis and Management

(created at Oct 09, 2024)

Quantum computer and qubit generation method

(updated at Oct 08, 2024)

Green Premium, Eco-Certified Building

(updated at Oct 08, 2024)

Why Two Path Authentication is Essential - My Microsoft Account is Gone!

(updated at Oct 08, 2024)

Amazon's Return-to-Office Mandate: A Bold Move or a Step Backwards?

(updated at Oct 08, 2024)

Exploring UC Merced (aka UCM) - Schools and Majors

(updated at Oct 08, 2024)

Understanding Rose-Hulman Institute of Technology

(updated at Oct 08, 2024)

Understanding Rensselaer Polytechnic Institute based in New York

(updated at Oct 08, 2024)

Understanding Virgina Tech founded in 1872

(updated at Oct 08, 2024)

Spam's New Soul-Touching Gochujang Spam

(updated at Oct 08, 2024)

Japan's Current Status on Generative AI and Copyright: A Summary of Developments, Current Situation, and Key Issues

(updated at Oct 08, 2024)

I do enjoy Pasta rather than Cheese Cake at Cheese cake factory

(updated at Oct 05, 2024)

A Hurdle on the Court: My Basketball Injury Journey

(updated at Oct 03, 2024)

Difference between Java and Javascript

(updated at Oct 03, 2024)

Loading XML Data with JavaScript

(updated at Oct 03, 2024)

jQuery Example to make GET method call with $.ajax()

(updated at Oct 03, 2024)

Regular Expressions in JavaScript

(updated at Oct 03, 2024)