Introduction to Programming in Java/Strings

< Introduction to Programming in Java

Strings are a collection of characters implemented under the String class. However, they may also appear directly in the source code.

String operations

The only operation permitted on a string is the + operator. In the context of a string, this operator performs concatenation. The value on the right, a string, is appended to the string on the left.

Strings can also be concatenated with integers or other numbers. If this is the case, the variable or object is automatically converted to a string.

String performance

Even though you may be able to concatinate strings indefinitely, this is not the best means to do what you want. Since strings are immutable objects, attemtping to change a string will create a new string object, and making identical copies of the strings.

If you need to constantly append characters to a string, you may want to use a StringBuilder class.


String constructors

You can also create strings using these methods. Explanation to below every example of the String constructor.

	
String aString= new String();
// aString is a reference to an empty string. aString can be any name that you want to name the variable
	
String aGreeting;
// aGreeting is reference to a String
aGreeting = new String("Hello world");


Greeting1 = "Hello world";
// Shortcut for constructing String objects.
String Greeting2 = new String(Greeting1);
// Greeting2 is a copy of the String Greeting1
Introduction to Programming in Java/Strings is a stub. Learn how you can help Wikiversity to expand it.
Project: Introduction to Programming in Java
Previous: Boolean Variables Introduction to Programming in Java/Strings Next: Java Classes
This article is issued from Wikiversity - version of the Wednesday, January 26, 2011. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.