how to write a method in java code example
Example 1: calling method in java
public class MyClass {
void myMethod() {
System.out.println("You have called me! My name is: myMethod!");
}
public static void main(String[] args) {
new MyClass().myMethod();
}
}
Example 2: java method
public class Main {
public static void main(String args[]) {
SayHi();
int sum = AddNums(5, 6);
System.out.println(sum);
}
public static void SayHi() {
System.out.println("Hi!");
}
public static int AddNums(int a, int b) {
return a + b;
}
Example 3: java how to define a function
void function(int parameter1)
{
}
function(1);
Example 4: methods in java
A method in java is a group of statements to carry out some operation also
known as functions.
Example 5: java methods
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
Example 6: what is a method example in java
public int addNum(int num1, int num2) {
total = num1 + num2;
System.out.println("Total: " + total);
}