Robert Cuber Robert Cuber - 1 year ago 67
Java Question

"return" in my method doesn't return the value when the method is called

Just finished up an assignment for my Java class; it was to create a class with a method that, when given two strings, searches for the second string in the first and counts the number of times it is found.

Here's the important bit:

for (int count = 0; count < l1; count++) {
if (one.charAt(count) == two.charAt(0)) {
for (int count2 = 0; count2 < l2; count2++) {
if (one.charAt(count) != two.charAt(count2)) {
if (count2 == l2 - 1) {
System.out.println("There are " + twoCount + " \"" + two + "\"");
return twoCount;

I included the
at the end because when I call the method in another program,
doesn't actually return anything, as such:

test.stringFind(one, two);

output being:

----jGRASP exec: java StringSearchRun

There are 2 "love"

----jGRASP: operation complete.

Notice how there's just that one line from my
? My method in the class is defined as an
, as well as the
variable. So what stupid mistake did I make?

Answer Source

If you're method return type is int, then you have to do something with the returned value. By just calling the method and doing nothing else, nothing happens because there's either

A) No way to retrieve the returned value or

B) Nothing being done to the returned value

Why is this so? Think about it, where is the value being returned to after executing test.stringFind(one,two);? The method when called by itself returns a value that is garbage collected right away since the value's scope is only within the method call. Therefore, once the call is done, the value is discarded because it doesn't leave the scope of the method. So to fix this, either store it in another variable or use it in an expression. Here are some examples of what you can do with it in your main method,

int result = test.stringFind(one,two);