Reputation: 259
So what I expected this code to display on console was
"hi"
"Ken is a legend"
"forkbomb"
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
ken();
System.out.println("fork bomb");
}
public static String ken() {
return ("ken is a legend");
}
}
But instead it only displays hi
and forkbomb
. When I change it to public static void ken()
then it returns what I wanted the value to be but I was wondering. Why doesn't this current code work?
Upvotes: 0
Views: 61
Reputation: 2147
You should use return
value in print statement which is string as "ken is a legend"
.
Your final code should be like this ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi");
System.out.println(ken());
System.out.println("fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
or more clear version of code ;
public class ForkBombOnClick {
public static void main(String[] args) {
System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
}
public static String ken() {
return "ken is a legend";
}
}
In this System.out.println("hi" + "\n" + ken() + "\n" + "fork bomb");
\n
refers to newline.Upvotes: 1
Reputation: 37377
You know the answer yourself!
Why do you use System.out.println
? To print on the screen string that you pass to the function.
You do it correctly by System.out.println("hi");
, so it prints hi
.
Now, you want to print string returned by ken()
method. It has string as return type, so you can think of ken();
invocation as a string. Just like hi
.
So if you want to print it, you need to use System.out.println
and supply result of ken()
method to it, just like with other strings: System.out.println(ken());
.
Upvotes: 1
Reputation: 8653
You need to use the string returned by method ken();
like
System.out.println(ken());
Once a method returns something, you need to get hold of it to use it.
You can also use it like:
String returnValue = ken();
System.out.println(returnValue);
This will also yield same result.
Upvotes: 3