Java problem with method calling in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Java problem with method calling in java

Guys you understand what am trying to do here ,am calling the add() method (or function I don't know what it's called) the output gave me error that I haven't added return statement ,so I added return sum; but the output gave me infinite result of the answer like this 48 48 48 48 48 It even crashed my phone I have to restart it What is going on should I add break statement or what alternative do u guys have public class Program { public static void main(String[] args) { System.out.println("answer ="); add(); } public static int add(){ int x =6; int y=8; int sum=x*y; System.out.println(sum); } }

17th Jan 2022, 11:58 AM
Tony Jadesola
6 Answers
+ 3
Hello Tony Jadesola If you only want to print the value the return type of add() need to be void: public static void add(){ } with return type int: public static int add(){ int a = 3; int b = 4; return a+b; } In this case your method returns an integer. In your main: int sum = add();
17th Jan 2022, 12:32 PM
Denise Roßberg
Denise Roßberg - avatar
17th Jan 2022, 12:34 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Java sees this public static int add() Java thinks that function returns an `int`. But you didn't issue `return` in add() function. Java was reminding you about that. Solution: Return <sum> from add() ... return sum; P.S. There's no way you're getting infinite output unless you have a loop in the code. Is that the complete code? why I don't see any loop there ...
17th Jan 2022, 12:36 PM
Ipang
+ 1
Ipang that's all the code I don't know why a loop came out
17th Jan 2022, 12:53 PM
Tony Jadesola
+ 1
Denise Roßberg I replaced int with void and it worked well
17th Jan 2022, 12:59 PM
Tony Jadesola
+ 1
Ipang thanks I figured it out
17th Jan 2022, 1:00 PM
Tony Jadesola