strings - Strings Weve been using strings in our examples,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Strings We’ve been using strings in our examples, but we haven’t fully explored what we can do with them. First of all, String is a class defined by Java -- we haven’t talked about classes yet, but we will later one. The Java String class uses a character array to store the individual characters in the string, and then defines several commands that let us do things with that array. Here is how to declare a string variable: String s1; And here is how to initialize a string: s1 = “hello”; We can declare and initialize a string at the same time: String s1 = “hello”; Concatenation String concatenation is pushing two strings together with the + sign -- we’ve seen how to concatenate strings when printing things out. Here are some more examples: int age = 7; char initial = ‘L’; String first = “Bob”; String last = “Jones”; String about = first + “ “ + initial + “. “ + last + “, age “ + age; The string about will hold “ Bob L. Jones, age 7 ”. Notice that we can concatenate types other than strings, like ints and chars. In fact, we can do this with any variable type. The only confusion is when we’re concatenating several ints – does the + mean concatenation or integer addition? The answer, of course, is that it can mean both. The compiler interprets expressions by reading from left to right. If it sees a + and has only seen primitive types (like int a double) so far, it will assume you mean mathematical addition. If it has seen a string or object already on that line, it will assume you mean string concatenation. Here are some examples: String s1 = 4+7+“ hi “; //evaluates to “ 11 hi String s2 = “hi “+4+7; //evaluates to “ hi 47 String s3 = 4+7+“ hi “+4+7; //evaluates to “ 11 hi 47
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Length You can get the number of characters in a string by accessing its length. Here’s how: String s = “Hello”; int count = s.length(); //has value 5 Getting a Character A string is backed by an array of characters, but you can’t access a character in a string by using array notations ( [i] ). Instead, you need to use the charAt command. This returns the character at a particular index in the string. Like an array, the first index in a string is 0, and the
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/02/2010 for the course CIS 200 taught by Professor Staff during the Spring '08 term at Kansas State University.

Page1 / 6

strings - Strings Weve been using strings in our examples,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online