Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects (Retired) Creating the MVP Storing Guesses

Can you have String variable of just one character?

It seems that, in the tutorial, every time a single character occurs in an expression, it is delimited by single quotes. Does that mean a String variable, whose value is delimited by double quotes, can never be a single character? That would seem very odd to me.

I don't see why the argument of the indexOf() method is a char only. Is there an override which accepts String input of one or more characters? There has to be a method for finding a substring in a variable, correct?

1 Answer

Rob Bridges
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 Points

Hey Adiv,

You can certainly make a string equal a single character if you wish, it takes more overheard from resources but, it's certainly do able, this would unlock many methods on that string as well.

And yes, there are ways to check to see if a certain word is contained in string.

String.contains(); would be an easy and practical way to do this.

String example = "This is my example String";

boolean exampleContains() = example.contains("my");

In the above we're just setting up an example string, then setting a boolean value to if that word is contained in String, this would return true.

You could also pass in a value to check for if in a console environment like workspace using console, if in an IDE you can use a scanner, to keep it simple and assume console is made available.

String exampleString = "Another example string";
String wordToSearchFor = console.readLine("What word do you want to search for?");
boolean isContainedInExample = exampleString.contains(wordToSearchFor);

This will return true to the boolean value if the word that the user passes into console in contained in the String we want to check.

Based on it being true we can print a statement staying that it is, or whichever way you wanted to use that info.

Thanks, I hope this helps. Shout if it doesn't.

Thanks, Rob. Your discussion really clarified an issue that I was confused about. The examples provided are very helpful and I am sure I'll be using such code many times as I progress in the study of Java. Thanks again!