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

Using boolean to compare if a string is true or false (equa or not)

Hello I just learning the java basics course. Instead of just following along with the course I decided to watch the videos and make a program using what I learned from each video.

I wanted to check to see if a string was equal to another. (Sample code below)

// Variables String myName = " Dervin"; String userName = console.readLine("What is your name? ");

boolean = myName;

console.printf("Hey computer do we have the same name? %n Checking ...... %s?",sameName); // this is where I want it to return true or false

    if (myName == userName){ 
      console.printf("We have the same name cool!:\n ");        
    } else { 
      console.printf("My name is %s I think you have a cool name %s.", myName, userName);
    } // Even if I type in my name the else always printout

My logic is off somewhere can someone offer some help?

It's best to use the .equals() method on a string when comparing:

if(myName.equals(userName){
   console.printf("Hey my name is %s too!", myName); // I would do it this way when using printf
}
else{
  console.printf("My name is %s I think you have a cool name %s.", myName, userName);
}
// When using printf it is looking for a String to format (%s for instance) the 'f' in printf is format; if there isn't anything to format it will throw an error.
// So when there isn't anything to format just use console.print or console.println instead.
console.print("This is an example message without any formatting");

Another String method that I use often is equalsIgnoreCase() this allows you to compare strings without being case sensitive. Doing it the other way if the user enters their name lower case and you were expecting the first letter to be uppercase then it would return false because they didn't match exactly.

1 Answer

Great thanks for the response the very next the same methods was introduced. The code is working I am just working on how to make the value come up as true or false