Home Java Java-tips Data Strings Q-pr-string-if Exercise - Capitalize

Ask Questions?

View Latest Questions

Advertisement


 
 

Exercise - Capitalize
Posted on: July 26, 2006 at 12:00 AM
Write a method, capitalize, which takes one string parameter and returns a string .

Java: Exercise - Capitalize

Name ___________________________

Problem. Write a method, capitalize, which takes one string parameter and returns a string that is the same as the parameter, except the first character is changed to uppercase. If the parameter has no characters in it, just return that same value. Examples:

   capitalize("abc") returns "Abc"
   capitalize("ABC") returns "ABC"
   capitalize("123") returns "123"
   capitalize("") returns ""

The method will look like this, where you have to write the ". . .".

   public static String capitalize(String s) {
       . . .
   }

Static. This method is declared static (ie, it's a class method) because it doesn't reference instance fields -- it depends only on parameters. Static (class) methods can be called by either static or instance methods.

Solution. Capitalize - Solution

Additional credit

One case that this doesn't handle is when the parameter hasn't been initialized, and therefore has the value null. Calling the string methods with null will cause a NullPointerException. What should happen? One philosophy is that only strings should be passed, so passing null is a programming error and it's ok to let an error occur. Another, more permissive, philosophy is that if null is passed in, we should just ignore it, and return null again. How would you modifiy the program to do that?

Copyleft 2005 Fred Swartz MIT License
Advertisement


DMCA.com