Java Notes Prev: Java Example: Console: Take me to your leader

Java Example: Console: Capitalize

This program reads a word, makes the first letter upper case and the remainder lower case, and outputs it. The input-process-output organization is very common in simple programs.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
// File   : examples1-sequential/CapitalizeConsole.java
// Purpose: Capitalize first letter and make remainder lower case.
//          Uses String methods: substring, toUpperCase, toLowerCase.

// Author : Fred Swartz - 27 Mar 2007 - Placed in public domain.

import java.util.*;

public class CapitalizeConsole {

    public static void main(String[] args) {
        //.. Create and initialize a scanner to read from the console.
        Scanner in = new Scanner(System.in);

        //.. Input a word
        System.out.println("Enter a word");
        String inputWord = in.next();   // Reads one "word"

        //.. Process - Separate word into parts, change case, put together.
        String firstLetter = inputWord.substring(0,1);  // Get first letter
        String remainder   = inputWord.substring(1);    // Get remainder of word.
        String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();

        //.. Output the result.
        System.out.println(capitalized);
    }
}

Where to declare local variables: at beginning or at first use?

Local variables can be declared anywhere before they are used. There are two styles of declaration.

Clarity first. Use whichever style makes the program clearer for you, or whichever style your instructor requires. Most of my programs use the declare-at-first-use style.