Difference between revisions of "Strings"

From CompSciWiki
Jump to: navigation, search
m
(added summary)
 
(40 intermediate revisions by 6 users not shown)
Line 1: Line 1:
This section will introduce you to the concept of a <code>String</code>, and how to create and use them. More advanced topics on mutability and escape sequences are presented for those interested in exploring Java <code>String</code>s further.
+
{{Template:1010Topic
 +
|Chapter_TOC=[[Java Fundamentals]]
 +
|Previous=[[Increment and Decrement Operators]]
 +
|Next=[[Casting]]
 +
|Body=
 +
 
 +
==Introduction==
 +
Strings are a fundamental data type that are used to represent sentences, words, user input and more. By the end of the section, you should have a basic understanding of creating and manipulating Strings.  
 +
See page 70 in the Gaddis text: http://tinyurl.com/gaddis70
 +
 
  
 
== What are Strings ==
 
== What are Strings ==
Line 5: Line 14:
 
[[image:String_diagram.png|right]]
 
[[image:String_diagram.png|right]]
  
[[Strings]] are variables that contain a list of [[Common Primitive Variables|characters]]. We can represent things such as words or sentences of human language, text from a file, or [[Input using JOptionPane|input from the user's keyboard]] as Strings. To the computer, a String is simply a consecutive list of characters in memory (this is actually an [[Arrays|array]], more on these later) as the diagram to the right shows.
+
[[Glossary#string|Strings]] are variables that contain a list of [[Common Primitive Variables|characters]]. We can represent things such as words or sentences of human language, text from a file, or [[Input using JOptionPane|input from the user's keyboard]] as Strings. To the computer, a String is simply a consecutive list of characters in memory (this is actually an [[Arrays|array]], more on these later) as the diagram to the right shows.
 +
 
  
 
== Creating Strings ==
 
== Creating Strings ==
  
There are many ways we can create Strings in Java, the easiest of which is to simply write the desired contents of the String into a program. When Strings are created in this fashion, the resulting String is known as a ''String literal''. To create a String literal in Java, use double-quotes (<code>"</code>) around the characters that you would like to include, and simply write them into your code.  
+
Strings are declared much in the same way as [[Common_Primitive_Variables|ints, chars, etc....]] are.  The difference is that the S in String is capitalized.
 +
 
 +
{{CodeBlock
 +
|Code=
 +
String address;
 +
}}
 +
 
 +
 
 +
There are many ways we can create Strings in Java, the easiest of which is to simply write the desired content of the String into a program. To create a String in Java, use double-quotes (<code>"</code>) around the characters that you would like to include, and write them into your code.  
  
 
Here are some examples of Strings that may occur within your code:
 
Here are some examples of Strings that may occur within your code:
<pre>
+
{{CodeBlock
 +
|Code=
 
"This is a String"
 
"This is a String"
 
"ABC123"
 
"ABC123"
Line 18: Line 37:
 
"    "
 
"    "
 
"Q"
 
"Q"
</pre>
+
}}
  
To use a string you have written, simply place it within an expression or assign it to a variable for later use. To create a String variable, simply declare a variable of type <code>String</code> and assign the literal to it.
 
  
<pre>
+
Now that you know what types of things a string can store and how to write them, here is how you assign a value to a String. This is done with the assignment operator just like any other variable.
 +
 
 +
{{CodeBlock
 +
|Code=
 
String address = "66 University Crescent";
 
String address = "66 University Crescent";
</pre>
+
}}
 +
 
 +
Now address is available and contains the String <code>66 University Crescent</code>. Strings can also be used as part of an expression, most often to add something to them.
  
Now, address is available and contains the String <code>66 University Crescent</code>. Strings can also occur as part of an expression, most often to add something to them.
 
  
 
== String Expressions ==
 
== String Expressions ==
  
Sometimes when creating a String literal you want to display the contents of a variable, but don't know what the value of the variable will be until after the program has started. In these cases, you can simply ''append'' the variables to the String literal using the <code>+</code> operator.
+
Sometimes when creating a String literal you want to display the contents of a variable but don't know what the value of the variable will be until after the program has started. In these cases, you can ''append'' the variables to the String literal using the <code>+</code> operator.
  
 
For example, if we have a number that we want to include within a String, we can write it as follows:
 
For example, if we have a number that we want to include within a String, we can write it as follows:
  
<pre>
+
{{CodeBlock
 +
|Code=
 
   double kilometersToSchool = 14.5;
 
   double kilometersToSchool = 14.5;
 
   String message = "The University is " + total + " kilometers away!";
 
   String message = "The University is " + total + " kilometers away!";
</pre>
+
}}
  
 
The second line of code above can be read as 'add (or append) the double <code>total</code> to the end of the String <code>The University is </code>, and then append <code> kilometers away!</code> to the end of that result.  When this code is executed, the variable <code>message</code> will contain the text <code>The University is 14.5 kilometers away!</code>.
 
The second line of code above can be read as 'add (or append) the double <code>total</code> to the end of the String <code>The University is </code>, and then append <code> kilometers away!</code> to the end of that result.  When this code is executed, the variable <code>message</code> will contain the text <code>The University is 14.5 kilometers away!</code>.
  
Note that when creating a String expression, a String must come first before any <code>+</code> operators, or else it will not work. For example, you might think the following code creates the string <code>17 ducks are in the pond</code>:
 
  
<pre>
+
== Special Cases ==
int ducks = 17;
+
String message = ducks + " ducks are in the pond";
+
</pre>
+
  
But actually, Java doesn't know how to add a <code>String</code> to an <code>int</code> (but it does know how to add an <code>int</code> to a <code>String</code>!)
+
There are two special cases to consider when dealing with Strings.
  
== Special Cases ==
 
  
These are two special cases to consider when dealing with Strings. First, when we want to include a double-quote within a String, we cannot simply place it into a String literal, because Java will confuse it with the two double-quotes occuring at either end of the String. However, we can include a double-quote inside a String by preceding it with a backslash. The second special case is that of double-quotes occuring without any characters in between. In this case, the result is an empty String (known often as ''the empty string''). The following examples demonstrate these special cases:
+
1.Including a double-quote within a String.
<pre>
+
 
 +
Since the double-quote character is the delimiter for a String, we cannot simply place it into a String literal. Java will confuse it with the two double-quotes occuring at either end of the String causing early termination of the String as well as a syntax error. To include a double-quote inside a String it must be 'escaped' by using backslash.  
 +
{{CodeBlock
 +
|Code=
 
"\"That's the beauty of it, it doesn't do anything!\" - anonymous"
 
"\"That's the beauty of it, it doesn't do anything!\" - anonymous"
"" (the empty string)
+
}}
</pre>
+
 
 +
When your String is read by the computer, the <code>\"</code> combination will be replaced with a double-quote character, <code>"</code>. The first String in the example above would contain <code>"That's the beauty of it, it doesn't do anything!" - anonymous</code>
 +
 
 +
 
 +
2.An empty String.
 +
 
 +
An empty String is a String with no characters in it.
 +
{{CodeBlock
 +
|Code=
 +
String empty = ""; (the empty String)
 +
}}
 +
 
 +
This can be useful for initializing Strings.
  
When your String is read by the computer, the <code>\"</code> combination will be replaced with a double-quote character, <code>"</code>. So the first String in the example above would contain <code>"That's the beauty of it, it doesn't do anything!" - anonymous</code>
 
  
 
== Length ==
 
== Length ==
  
Strings are known as having a particular length. The length of a String is simply the count of the number of characters that occurs within it. This count is represented as an [[Your_First_Java_Program#Primitive_Type_int|integer]], and can be obtained via the [[Calling_Methods#String_Methods]] method. Knowing the length is useful because you might want to restrict user input based on the number of characters they type, or only process Strings greater than a particular length.
+
Strings are known as having a particular length. The length of a String is the number of characters contained within it. This count is represented as an [[Your_First_Java_Program#Primitive_Type_int|integer]], and can be obtained via the [[String_Methods#length|length]] method. Knowing the length is useful because you might want to restrict user input based on the number of characters they type or only process Strings greater than a particular length.
 +
 
 +
For more String methods visit [[String_Methods|String methods]]
 +
 
 +
String literals can range from 0 to 2<sup>16</sup> (65536) characters. Strings obtained from sources such as files or user input have no practical limit on length. Also note that the empty String, <code>""</code>, has a length of zero since it contains no characters.
 +
 
 +
 
 +
== String Methods ==
 +
See [[String_Methods|String methods]]
 +
 
 +
 
 +
== Advanced String Topics ==
 +
 
 +
This section covers more advanced String topics, which are not necessary to using Strings, but are necessary for fully understanding how they are handled in Java. These topics include mutability, special String characters, and escape sequences.
 +
 
 +
 
 +
=== Mutability ===
 +
 
 +
Java Strings are known as ''immutable'', meaning you cannot change the characters that are contained within a particular String. This means that when you append something to a String, or attempt to modify the contents of a String, a new String is returned and the original is unaffected. However, this does not mean that you cannot change a variable to hold a different String altogether.
 +
 
 +
 
 +
=== Special Characters ===
 +
 
 +
Strings can contain characters that have special meaning to the Java compiler, which are called 'escape sequences'. Escape sequences are characters that programmers would like to use, but either do not occur on a standard keyboard, or have no single-character on-screen representation. Escape sequences are preceded by a backslash, and are considered together as a single character.  For example, the escape sequence <code>\t</code> is interpreted by the computer as a tab.
 +
 
 +
The following table lists all of Java's common escape sequences:
 +
 
 +
<table border=1>
 +
<tr>
 +
<td>Escape sequence
 +
<td>Meaning
 +
<tr>
 +
<td><code>\b</code>
 +
<td>Backspace
 +
<tr>
 +
<td><code>\t</code>
 +
<td>Horizontal tab
 +
<tr>
 +
<td><code>\n</code>
 +
<td>Line feed* (a new line)
 +
<tr>
 +
<td><code>\f</code>
 +
<td>Form feed
 +
<tr>
 +
<td><code>\r</code>
 +
<td>Carriage return*
 +
<tr>
 +
<td><code>\"</code>
 +
<td>Double quote
 +
<tr>
 +
<td><code>\'</code>
 +
<td>Single quote
 +
<tr>
 +
<td><code>\\</code>
 +
<td>Backslash
 +
</tr>
 +
</table>
 +
 
 +
For example, given the meanings above, the following String would be a list of names that occur on separate lines: <code>"Bob Dylan\nAndrew Jackson\nJohn MacDonald"</code>
 +
 
 +
* "Carriage return" and "line feed" are archaic terms from the days of manual typewriters, when a line feed would literally be a new line being moved underneath the cursor, and a carriage return would be the physical moving of the carriage to the far end of the machine.
 +
 
  
String literals can range from 0 to 2<sup>16</sup> (65536) characters, though Strings obtained from other sources, such as files or user input, have no practical limit on length. Also note that the empty String, <code>""</code>, has a length of zero since it contains no characters.
+
==Summary==
 +
You should now have a firm grasp on how to use Strings in your programs. This is very important for representing different types of data including user input.
 +
}}

Latest revision as of 12:17, 4 December 2011

COMP 1010 Home > Java Fundamentals


Introduction

Strings are a fundamental data type that are used to represent sentences, words, user input and more. By the end of the section, you should have a basic understanding of creating and manipulating Strings. See page 70 in the Gaddis text: http://tinyurl.com/gaddis70


What are Strings

String diagram.png

Strings are variables that contain a list of characters. We can represent things such as words or sentences of human language, text from a file, or input from the user's keyboard as Strings. To the computer, a String is simply a consecutive list of characters in memory (this is actually an array, more on these later) as the diagram to the right shows.


Creating Strings

Strings are declared much in the same way as ints, chars, etc.... are. The difference is that the S in String is capitalized.

 String address; 


There are many ways we can create Strings in Java, the easiest of which is to simply write the desired content of the String into a program. To create a String in Java, use double-quotes (") around the characters that you would like to include, and write them into your code.

Here are some examples of Strings that may occur within your code:

 "This is a String"
"ABC123"
"100100100"
"    "
"Q" 


Now that you know what types of things a string can store and how to write them, here is how you assign a value to a String. This is done with the assignment operator just like any other variable.

 String address = "66 University Crescent"; 

Now address is available and contains the String 66 University Crescent. Strings can also be used as part of an expression, most often to add something to them.


String Expressions

Sometimes when creating a String literal you want to display the contents of a variable but don't know what the value of the variable will be until after the program has started. In these cases, you can append the variables to the String literal using the + operator.

For example, if we have a number that we want to include within a String, we can write it as follows:

 double kilometersToSchool = 14.5;
  String message = "The University is " + total + " kilometers away!"; 

The second line of code above can be read as 'add (or append) the double total to the end of the String The University is , and then append kilometers away! to the end of that result. When this code is executed, the variable message will contain the text The University is 14.5 kilometers away!.


Special Cases

There are two special cases to consider when dealing with Strings.


1.Including a double-quote within a String.

Since the double-quote character is the delimiter for a String, we cannot simply place it into a String literal. Java will confuse it with the two double-quotes occuring at either end of the String causing early termination of the String as well as a syntax error. To include a double-quote inside a String it must be 'escaped' by using backslash.

 "\"That's the beauty of it, it doesn't do anything!\" - anonymous" 

When your String is read by the computer, the \" combination will be replaced with a double-quote character, ". The first String in the example above would contain "That's the beauty of it, it doesn't do anything!" - anonymous


2.An empty String.

An empty String is a String with no characters in it.

 String empty = ""; (the empty String) 

This can be useful for initializing Strings.


Length

Strings are known as having a particular length. The length of a String is the number of characters contained within it. This count is represented as an integer, and can be obtained via the length method. Knowing the length is useful because you might want to restrict user input based on the number of characters they type or only process Strings greater than a particular length.

For more String methods visit String methods

String literals can range from 0 to 216 (65536) characters. Strings obtained from sources such as files or user input have no practical limit on length. Also note that the empty String, "", has a length of zero since it contains no characters.


String Methods

See String methods


Advanced String Topics

This section covers more advanced String topics, which are not necessary to using Strings, but are necessary for fully understanding how they are handled in Java. These topics include mutability, special String characters, and escape sequences.


Mutability

Java Strings are known as immutable, meaning you cannot change the characters that are contained within a particular String. This means that when you append something to a String, or attempt to modify the contents of a String, a new String is returned and the original is unaffected. However, this does not mean that you cannot change a variable to hold a different String altogether.


Special Characters

Strings can contain characters that have special meaning to the Java compiler, which are called 'escape sequences'. Escape sequences are characters that programmers would like to use, but either do not occur on a standard keyboard, or have no single-character on-screen representation. Escape sequences are preceded by a backslash, and are considered together as a single character. For example, the escape sequence \t is interpreted by the computer as a tab.

The following table lists all of Java's common escape sequences:

Escape sequence Meaning
\b Backspace
\t Horizontal tab
\n Line feed* (a new line)
\f Form feed
\r Carriage return*
\" Double quote
\' Single quote
\\ Backslash

For example, given the meanings above, the following String would be a list of names that occur on separate lines: "Bob Dylan\nAndrew Jackson\nJohn MacDonald"

  • "Carriage return" and "line feed" are archaic terms from the days of manual typewriters, when a line feed would literally be a new line being moved underneath the cursor, and a carriage return would be the physical moving of the carriage to the far end of the machine.


Summary

You should now have a firm grasp on how to use Strings in your programs. This is very important for representing different types of data including user input.

Previous Page: Increment and Decrement Operators Next Page: Casting