This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Well, one way would be to loop over the characters and check each one:
Another approach, useful in only specific situations, would be to use the Integer.parseInt(String, int) method, specifying base 2; this method will return the binary value as an int if it can, or otherwise throw a NumberFormatException. This would be useful if you were sure the value would always be less that Integer.MAX_VALUE .
The previously suggested solution won't work quite as desired. It will match only the String "01" and will result in false in the example input String. Allow me to suggest a slight modification that should work well. ---- Also MSanjeevMehra, We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy. Thanks Pardner! Hope to see you 'round the Ranch!