+ 1

Java newbie needs help

1) am i right to say if i dont add "return 5 ;" to the sayHello() method and instead i add other things,i need to add void to the sayHello() method? 2) can i conclude that when the keyword "return" is inside the method ,there should not be void present and same goes with when there is void in the method there is no "return"? class MyClass { static int sayHello() { return 5; } public static void main(String[ ] args) { int x= sayHello(); System.out.println(x); } }

15th Oct 2017, 5:51 PM
oyl
3 Answers
+ 10
if u want your method to return a value you must specify the type in the method name declaration. The keyword "return" can be used even in a method that doesn't return anything: to stop the method. For example: public static void printEvenNumbersOnly(int num){ if (num%2!=0){ //STAGE 1 return; //STAGE 2 } else{ //STAGE 3 System.out.println(num); //STAGE 4 } } In the above example if "num" is not even, the method will stop at STAGE 2 but if it is even it will go on to stage 4 where it prints "num"
15th Oct 2017, 8:18 PM
David Akhihiero
David Akhihiero - avatar
+ 1
@Ace what do you mean by return by itself.could you show me an example
15th Oct 2017, 6:46 PM
oyl
+ 1
@Ace what is use of the code u have written above? does it have an application?
15th Oct 2017, 6:55 PM
oyl