pycan
pycan

Reputation: 351

Method is not executed

I am trying to grasp a basic Java concept and I cant figure out why my method is not get executed. I would like to print out substring from word bunny if it has more than 3 characters, else print out the original string. My code:

package com.company;

public class Main {

    static String bunny = "bunny";

    public static String subStringBunny(String bunny) {
        if (bunny.length() > 3) {
            bunny = bunny.substring(2, 4);
        }
        return bunny;
    }

    public static void main(String[] args) {
        System.out.println("this is substring from bunny: " + bunny);
    }
}

It still prints the original string so I suppose the subStringBunny method does not get executed. Any help would be greatly appreciated! Thanks!

Upvotes: 0

Views: 1687

Answers (2)

Tom O.
Tom O.

Reputation: 5941

You're not calling subStringBunny method from the main method. This code should do what you're trying to achieve:

package com.company;
public class Main {    
    static String bunny = "bunny";    
    public static String subStringBunny (String bunny) {
        if (bunny.length() > 3) {
            bunny =  bunny.substring(2,4);
        }    
        return bunny;
    }

    public static void main(String[] args) {    
        System.out.println("this is substring from bunny: " + Main.subStringBunny(bunny));
    }
}

Upvotes: 3

michaelitoh
michaelitoh

Reputation: 2340

You're not calling the method. You most do this:

System.out.println("this is substring from bunny: " + subStringBunny(bunny));

Upvotes: 1

Related Questions