Vlad
0
Q:

java methods

public class Main {
  public static void main(String args[]) {
    SayHi();
    
    int sum = AddNums(5, 6);
    System.out.println(sum);
  }
  
  public static void SayHi() { //This method has no return value
    System.out.println("Hi!");
  }
  
  public static int AddNums(int a, int b) { //This method has a return value
    return a + b;
}
5
A method in java is a group of statements to carry out some operation also 
known as functions.
0
//declare a function like this:
void function(int parameter1)
{
	//function body
}
//call the function like this:
function(1);
4
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 int addNum(int num1, int num2) {
  total = num1 + num2;
  System.out.println("Total: " + total);
}
0
Method is a collection of statements
which returns a value upon its execution
Method have a return and the method's name may or not be same as the class
name.
Method is invoked explicitly.
Method is not provided by compiler in any case.
Methods are inherited by child classes.
0

New to Communities?

Join the community