- Java Introduction
- Java Getting Started
- Java Syntax
- Java Comments
- Java Variables
- Java Data Types
- Java Type Casting
- Java Operators
- Java Strings
- Java Math
- Java Booleans
- Java If ... Else
- Java Switch
- Java While Loop
- Java For Loop
- Java Break And Continue
- Java Arrays
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Scope
- Java Recursion
- Java OOP
- Java Classes And Objects
- Java Class Attributes
- Java Class Methods
- Java Constructors
- Java Modifiers
- Java Encapsulation
- Java Packages
- Java Inheritance
- Java Polymorphism
- Java Inner Classes
- Java Abstraction
- Java Interface
- Java Enums
- Java User Input (Scanner)
- Java Date And Time
- Java ArrayList
- Java LinkedList
- Java HashMap
- Java HashSet
- Java Iterator
- Java Wrapper Classes
- Java Exceptions - Try...Catch
- Java Regular Expressions
- Java Threads
- Java Lambda Expressions
- Java Files
- Java Create And Write To Files
- Java Read Files
- Java Delete Files
Java Methods
Create A Method
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.
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:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod()
is the name of the methodstatic
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
Practice Excercise Practice now
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:
Example
Inside main
, call the myMethod()
method:
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:
Example
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!
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP