Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Harnessing the Power of Objects Helper Methods and Conditionals

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

What exactly is a helper method?

What exactly is a helper method in Java? Is there anything that differentiates itself from any other method?

The best explanation I can see is that it is a piece of code that "noone needs to ask for time and again" but that doesn't really explain to me what a helpful function is and why they exist?

I'm lost. :-)

2 Answers

A helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again n again. Whereas the class-specific methods define its behaviour, the helper methods assist in that process. You can think of Integer.parseInt() as a helper method that we have been using across multiple classes irrespective of their independent behaviour.

Helper methods are often declared as public static so they can be invoked with the class name like Classname.method(). For example, below I have created a HelperMethods class which consists of helper methods that I can use across multiple classes. I have created another Test class and used the HelperMethods.preMr() helper method to prepend "Mr." to the name. I can create more classes if I want to and use the same helper methods with them. One can even build a custom library of functions that can be used in any project due to its generic nature.

public class HelperMethods {
    public static String preMr(String name) {
        return "Mr. " + name;
    }
    public static String preMs(String name) {
        return "Ms. " + name;
    }
    public static String preDr(String name) {
        return "Dr. " + name;
    }
}
public class Test {
    public static void main(String[] args) {
        String name = "Manav";
        System.out.println(HelperMethods.preMr(name)); // Mr. Manav
    }
}
Marcus Quarles
Marcus Quarles
14,598 Points

Hello Jonathan,

As I understand it helper methods assist other methods to do their job. You will see them being used when there is a method performing a complex task in which the helper methods help execute some of the smaller tasks. I hope I have explained that well enough