Method in Java : – A Method is a Block of Code Which Only Runs When it is Called.
Note 1 : If a Method is void than that Method cannot return any value. Hence The Below Program Throws Error.
Method in Java
public class A {
public static void main( String[] args) {
}
public void test () {
return "mike" ; // Error
}
}
Example 2
public class A {
public static void main( String[] args) {
A a1 = new A();
int x=a1.test();
System.out.println(x);
}
public int test () {
return 100;
}
}
Output : 100
Note 2: If You Write Anything After return Keyword than That Line of Code Will Never Run, and Hence You Will Get Unreachable Code Error.
public class A {
public static void main( String[] args) {
A a1 = new A();
int x=a1.test();
System.out.println(x);
}
public int test () {
return 100;
System.out.println(10); //Unreachable Code Error
}
}
Example 2
public class A {
public static void main( String[] args) {
A a1 = new A();
a1.test();
System.out.println(10);
}
public void test () {
return; // return keyword optional when method is void
}
}
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exception in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
Output : 10
Example 3 Method in Java
public class A {
public static void main( String[] args) {
A a1 = new A();
a1.test(10,'R',"Raj",true);
}
public void test (int x,char c,String s, boolean b) {
System.out.println(x);
System.out.println(c);
System.out.println(s);
System.out.println(b);
}
}
Output :
10
R
Raj
true
Note 3 : Methods Breaks The Code into Module That Makes the Code Reusable.
Example 1
public class A {
public static void main( String[] args) {
A a1 = new A();
a1.test(10,20,30,40,50);
}
public void test (int ...i) {
System.out.println(i[0]);
System.out.println(i[1]);
System.out.println(i[2]);
System.out.println(i[3]);
System.out.println(i[4]);
}
}
Output :
10
20
30
40
50