Maggie
0
Q:

how to create a method in java

public static void main(String[] args)
{
	int length=getLength();
  	System.out.println("Your length is: "+length);
}
//methods are outside of main method
public static int getLength()
{
	int length=5;
  	return length;
}
5
public class MyClass {
  static int myMethod(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(myMethod(3));
  }
}
// Returns 8
2
public class MyClass {
  private int value = 10;
  // getter method
  public int getValue() {
    return value;
  }
  // setter method
  public void setValue(int value) {
    this.value = value;
  }
}
3
public class MyClass {
  static void myMethod() {
    
    // a method comes before the main method
    // use source for more information
    // code to be executed
  }
}
 
0
public int addNum(int num1, int num2) {
  total = num1 + num2;
  System.out.println("Total: " + total);
}
0
public class MyClass {
  static void myMethod() {
    // code to be executed
  }
}
 
0

New to Communities?

Join the community