Sams Teach Yourself C in 21 Days

(singke) #1
Java Language Fundamentals 713

BD4


LISTINGB4.1 StringTest.Java demonstrates some uses of the Stringclass
1: import java.lang.System;
2: import java.lang.String;
3:
4: public class StringTest {
5:
6: public static void main(String args[]) {
7:
8: String s1 = “Teach Yourself C in 21 Days”;
9:
10: System.out.println(“The original string: “ + s1);
11: System.out.println(“Converted to uppercase: “ + s1.toUpperCase());
12: System.out.println(“Converted to lowercase: “ + s1.toLowerCase());
13: System.out.println(“The first Y is at position “ + s1.indexOf(‘Y’));
14: System.out.println(“Replacing ‘e’ with ‘!’: “+s1.replace(‘e’, ‘!’));
15: System.out.println(“This string has “ + s1.length()+” characters.”);
16: }
17: }

The original string: Teach Yourself C in 21 Days
Converted to uppercase: TEACH YOURSELF C IN 21 DAYS
Converted to lowercase: teach yourself c in 21 days
The first Y is at position 6.
Replacing ‘e’ with ‘!’: T!ach Yours!lf C in 21 Days
This string has 27 characters.
The original string is unchanged: Teach Yourself C in 21 Days
This is a simple program. Lines 1–6 should be familiar to you, performing the
necessary imports, defining the program class, and defining the mainmethod.
Withinmain, line 8 declares an instance of the Stringclass and initializes it. Then, the
remaining code uses some of the methods of the Stringclass to manipulate the string
and display the results on screen. It’s important to note that methods of the Stringclass
do not modify the original string, but rather they return a new string with the changes.

Input and Output ................................................................................................


The most basic Java applications are called consoleapplications because their input and
output consist entirely of text input from the keyboard and output to the screen. Java has
plenty of graphic capabilities, implemented in the Abstract Windowing Toolkit (AWT) or
the Swing class library, but coverage of that topic is beyond the scope of this brief intro-
duction. Console input/output is all you’ll need to get started with Java.
Outputting text to the screen is done with the printlnmethod of the System.outclass.
You saw this method used in the Hello, Worldexample from Bonus Day 1. The syntax
is simple:

OUTPUT

ANALYSIS

39 448201x-Bonus4 8/13/02 11:19 AM Page 713

Free download pdf