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

The difference between public void and public String/int/boolean

Hello, i don't understand what is the difference between using public void and public boolean on String. In the course Craig uses both when he is programming. Thanks,

Itai

2 Answers

Hi Itai Shin,

the keyword after the access modifier public is called the return type. Let's say you'd use:

public String returnsString() {
   // this method has to return a String  at some point, otherwise you will receive an error
   String word = "word";
   return word;
}

This method expects a return value of the type String. If you chose the return type of boolean, it expects boolean and so on.

The type void is saying that no return value is expected. Often you will alter the value of a variable or print something out to the display with a method with such a method.

Hope it helps.

Thank you. I know in language like Swift you just write -> String but in Java the syntax is a little bit different. Thanks again for the fast answer.

Itai

You are welcome mate. If you still have any questions then let me know :-)

When your method return "void" he do something and not return nothing. Ex:

public void callMyDad( String numberPhone )
{
       System.out.println("Call my dad: " + numberPhone );
}

When your method return something like: String, boolean, int, etc... he do something and return value for called. Ex:

public boolean isAdult( int age )
{
       if(age >= 18)
            return true;

       return false;
}

Thanks also, now i understand the meaning of the boolean keyword in the function.

Itai