Aqua Phoenix
     >>  Lectures >>  Java 1  


1.11 Strings

Strings are treated somewhat special in Java, as in many other programming languages. They can be considered primitive data types, but in reality are complete Objects. Notice that String is capitalized, and hence it is an Object.

To declare a String, we can follow several conventions:

  • String s = "I want to be a doughnut";
  • String s = new String("Ich bin ein Berliner");

Both of these expressions produce a String object, upon which methods from the String class can be used to act upon the String.

Strings in Java have some overloaded operators, specifically the summation sign ( + ). Adding 2 Strings is the operation of concatenation:

String a = "Berliners";
String b = "are not";
String c = "Doughnuts";
String d = a + b + c;
String variable d now contains the value: "Berlinersare notDoughnuts";

To correct for the missing spaces, we can re-create the string as follows, and mix existing String objects and newly created String objects:

String d = a + " " + b + " " + c;
String variable d is now: "Berliners are not Doughnuts";

It is also possible to mix in numerical values when creating String objects:

int i = 6;
double j = 86.9;
String s = "I have " + i + " Berliner doughnuts, each weighing " + j + " kg";
String s now contains: "I have 6 Berliner doughnuts, each weighing 86.9 kg"Variables i and j are converted to their String representation in the process of concatenating with other Strings.

Comparison of string values cannot be performed using the equality operator == . Instead, a method call to "equals" is required, for example:

if (s.equals("apple") {