Java Reference
In-Depth Information
Strings
A string is a sequence of characters. Keep in mind that strings are not primitive
data types in Java, and therefore need to be represented by a class. Java has a
class named String to represent string objects. I have always liked the String
class from the moment I first learned Java because it makes working with
strings much simpler than in other languages.
A String object is created automatically for the string literals in your Java
code. For example, suppose that you had the following println() statement:
System.out.println(“Hello, World”);
The string literal “Hello, World” is converted to a String object, which is
then passed into the println() method. Consider the following statements:
int x = 10;
System.out.println(“x = “ + x);
The string literal “x = “ is converted to a String object. The + operator then
becomes string concatenation, so the variable x needs to be converted to a
String and then concatenated to “x = “ to create a third String, “x = 10”. It is this
third String object that gets passed to println().
In Java, every primitive data type being concatenated to a String will be
automatically converted to a new String object. This simplifies the process
of working with built-in types and displaying or outputting them. In fact,
any object in Java (not just the built-in types) is convertible to a String
because every object in Java will have a toString() method. The toString()
method is discussed in detail in Chapter 6, “Understanding Inheritance.”
The following StringDemo program demonstrates string literals and String
objects. Study the program and try to determine what the output will be.
public class StringDemo
{
public static void main(String [] args)
{
String first = “Rich”, last = “Raposa”;
String name = first + “ “ + last;
System.out.println(“Name = “ + name);
double pi = 3.14159;
String s = “Hello, “ + first;
System.out.println(s + pi + 7);
System.out.println(pi + 7 + s);
}
}
Search WWH ::




Custom Search