You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

A Java String contains an immutable sequence of Unicode characters. Unlike C/C++, where string is simply an array of char, A Java String is an object of the class java.lang.

Java String is, however, special. Unlike an ordinary class:

  • String is associated with string literal in the form of double-quoted texts such as "Hello, world!". You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.
  • The '+' operator is overloaded to concatenate two String operands. '+' does not work on any other objects such as Point and Circle.
  • String is immutable. That is, its content cannot be modified once it is created. For example, the method toUpperCase() constructs and returns a new String instead of modifying the its existing content.

Java String vs Python string

In the following example, we initialize an integer to zero, then convert it to a string, then check to see if it is empty. Note the data declaration (highlighted), which is necessary in Java but not in Python. Notice also how verbose Java is, even in an operation as basic as comparing two strings for equality.

Strings in Java
int    myCounter = 0;
String myString = String.valueOf(myCounter);
if (myString.equals("0")) ...
Strings in Python
myCounter = 0
myString = str(myCounter)
if myString == "0": ...
Strings in Java
// print the integers from 1 to 9
for (int i = 1; i < 10; i++)
{
   System.out.println(i);
}
Strings in Python
	print the integers from 1 to 9
for i in range(1,10):
    print i
  • No labels