FreeCode

Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Java Methods

Code Description:

Methods are reusable collections of code. Static methods can be run by themselves or you can have instance methods which are called from an object. You can define parameters within the parenthesis of the method. Our runnable example shows how static methods are used.

Method Syntax:

public static void methodName() {

}

Runnable Method Example Code:

public class Demo {

    public static void main(String[] args) {
		
	doSomething();
	System.out.println("Returned value after calculation: " + doCalculation(2, 5));
	
    }
	
    public static void doSomething() {
	System.out.println("Something was done!");
    }
	
    public static int doCalculation(int number1, int number2) {
	int numberTotal = number1 + number2;
	return numberTotal;
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Method Output Image

Related Links:

Java Classes