7 min read•Last Updated on June 18, 2024
Avanish Gupta
user_sophia9212
Avanish Gupta
user_sophia9212
It may surprise you that the string literals that we have looked at in Unit 1 are actually objects too! String literals are part of the aptly named String class included in Java and have a set of methods that come along with it. We'll see what we can do with the String class in the next topic!
There are two ways to make strings: using a preinitialized string or by using a constructor. We have learned how to use preinitialized strings in Unit 1. As a reminder, you do this as follows:
String preInit = "Hello, I am a string!";
This will set preInit to be a reference to the string "Hello, I am a string!" so that when we call preInit, we are referencing this above string.
Meanwhile, we can use a constructor to make a string. Here is the constructor signature followed by a call to the constructor:
String(String string)
String newString = new String("This is a new string");
Calling the constructor makes a copy of the string in parentheses and sets it to the variable of interest. This makes it so when using the pre-initialized string, the variable and the pre-initialized string are the same string. On the other hand, the string in the constructor and the variable are copies and are two different strings.
Sometimes, you want to put a quote in a string. However, you quickly find out that the opening quotation in the quote marks the "end" of the string and you can't type out your quote unless you want the program to crash. What can you do? Luckily, you know about escape characters and you can type out your quote?
What are escape characters anyways? Escape characters are characters preceded by "" that prints a certain character or whitespace (empty space, like a space or a tab) to the console or adds it to a string. Here is a table of some important escape characters:
Escape Character | What it Prints |
" | " (a quotation mark) |
\ | \ (a backslash) |
\n | A line break, so the remainder of the string is printed on a new line |
Sometimes, we also want to combine two strings together, and this is done with the help of string concatenation. String concatenation is done through the + operator and combines two strings together. Here is an example of string concatenation:
"3" + "3" = "33"
Did you think that the result of the concatenation would be 6 due to the two 3s? Remember that the quotations mean that 3 is a string, so the "+" represents string concatenation and not mathematical addition, so the strings are combined.
Here is another example. Do you think that the result of the string concatenation will equal "6", "33" again, or cause the program to crash?
3 + "3"
Once again, the result of this concatenation will be "33". Even though there is both a string and an integer, since there is a string, Java automatically knows that this is string concatenation and converts the integer to a string. In fact, if we are using string concatenation and one of the sides of the addition is any other type, it will be converted to a string.
For integers and doubles, the string is the textual representation of that number, while for booleans, the string will either be "true" or "false". If there is a mathematical expression on one side of the string concatenation, the expression is first evaluated before it is converted to a string. If you use an object when trying to concatenate a string, the object's toString() method is called, which usually converts the object's information to a String.
Moreover, we can also concatenate variables which is useful when you are doing user input. Let's try to concatenate my name!
String firstName = "Peter";
String lastName = "Cao"
System.out.println(firstName + lastName);
Oops, we accidentally printed out "PeterCao" without a space! This is because string concatenation combines the two strings as if they were just squished together. If you want to add a space, you would need to concatenate an actual space in addition to that as follows:
System.out.println(firstName + " " + lastName);
Use my example above and try it for yourself! First, create two variables (firstName and lastName) and assign them to your first and last names respectively. Then, concatenate firstName and lastName to get your full name. Lastly, use System.out. println() to print your full name! Make sure to concatenate a space so that your full name appears correctly.
Given the following code segment, what is in the string referenced by s1?
String s1 = "abc";
String s2 = "def";
s1 = s1 + s2 + "ghi";
A. abcdefghi
B. abcabcdefghi
C. abc abc def ghi
D. abc def ghi
E. def ghi
Answer: A. abcdefghi
Given the following code segment, what is in the string referenced by s1?
String s1 = "hello";
String s2 = "world";
s1 = s1 + s2 + "!";
A. hello
B. helloworld!
C. hello hello world!
D. hello world!
E. world!
Answer: B. helloworld!
Given the following code segment, what is in the string referenced by s1?
String s1 = "cat";
String s2 = "dog";
s1 = s1 + “ ” + s2 + “ ” + "bird";
A. cat
B. catdogbird
C. cat cat dog bird
D. cat dog bird
E. dog bird
Answer: D. cat dog bird
Given the following code segment, what is in the string referenced by s1?
String s1 = "1";
String s2 = "2";
s1 = s1 + s2 + "3";
A. 1
B. 123
C. 1 1 2 3
D. 1 2 3
E. 2 3
Answer: B. 123
Given the following code segment, what is in the string referenced by s1?
String s1 = "abc";
String s2 = "def";
s1 = s1 + s2 + "ghi" + "jkl";
A. abcdefghijkl
B. abcabcdefghijkl
C. abc abc def ghi jkl
D. abc def ghi jkl
E. def ghi jkl
Answer: A. abcdefghijkl
Let’s make it a little more difficult by incorporating the String methods from the previous guides!
Given the following code segment, what is in the string referenced by s1?
String s1 = "abc";
s1 = s1.substring(0,2) + s1.substring(2).toLowerCase();
A. abc
B. ABC
C. Abc
D. aBC
E. abC
Answer: A. abc
Given the following code segment, what is in the string referenced by s1?
String s1 = "HELLO";
s1 = s1.substring(0,2) + s1.substring(2).toLowerCase();
A. HELLO
B. hello
C. HEllo
D. hELLO
E. hEllo
Answer: C. HEllo
Given the following code segment, what is in the string referenced by s1?
String s1 = "CAT";
s1 = s1.substring(0,2) + s1.substring(2).toLowerCase();
A. CAT
B. cat
C. CaT
D. cAT
E. CAt
Answer: E. CAt
Given the following code segment, what is in the string referenced by s1?
String s1 = "DOg";
s1 = s1.substring(0,1).toUpperCase() + s1.substring(1).toLowerCase();
A. DOg
B. dog
C. dOG
D. Dog
E. dOg
Answer: D. Dog
Given the following code segment, what is in the string referenced by s1?
String s1 = "123";
s1 = s1.substring(0,1) + s1.substring(1,2).toUpperCase() + s1.substring(2).toLowerCase();
A. 123
B. 123
C. 123
D. 1 2 3
E. 1 2 3
Answer: C. 123
Let’s make it just a little bit harder… Use what you know about writing classes and what you learned about string concatenation for the next two practice problems.
Write a class that prints out "Hello, my name is (your name)". You should have a variable called name so that you can change the name without rewriting the entire code.
Example Answer:
public class GreetingExample
{
public static void main(String[] args)
{
String greeting = "Hello, my name is";
String firstname = "John";
System.out.println(greeting + " " + firstname);
}
}
Output: Hello, my name is John
Write a class that prints out a haiku about AP Computer Science using backslash n (\n) to create line breaks. The haiku should have three lines and should follow the traditional 5-7-5 syllable pattern. The program should use a single string variable to store the entire haiku and should print it to the console using the System.out.println() method.
Example Answer:
public class HaikuExample
{
public static void main(String[] args)
{
String haiku = "AP Computer Science\nA journey through code and logic\nEndless possibilities.";
System.out.println(haiku);
}
}
Output:
AP Computer Science
A journey through code and logic
Endless possibilities.
The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.
Term 1 of 10
The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.
Term 1 of 10
The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.
Term 1 of 10
The String class is a built-in class in Java that represents a sequence of characters. It provides various methods to manipulate and work with strings.
substring: A substring is a smaller part of a larger string. It refers to extracting a portion of characters from a string.
length: The length is the number of characters in a string. It helps determine the size or amount of content within the string.
concatenation: Concatenation is combining two or more strings together to create one longer string.
Escape characters are special characters that are used to represent certain actions or non-printable characters within a string. They are preceded by a backslash (\) and allow you to include characters like quotes, newlines, or tabs in your strings.
String literals: A sequence of characters enclosed in double quotes ("") or single quotes ('').
Backslash (\): An escape character used to indicate the start of an escape sequence.
Newline character (\n): An escape sequence that represents a line break in a string.
String concatenation is the process of combining two or more strings together into one longer string. It is achieved using the "+" operator in most programming languages.
String interpolation: A method of constructing new strings by embedding expressions inside string literals.
Concatenation assignment operator (+=): A shorthand way of appending one string to another.
Immutable strings: Strings that cannot be modified once created.
The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.
Arithmetic operators: Mathematical symbols used to perform calculations, such as addition, subtraction, multiplication, and division.
Comparison operators: Symbols used to compare values and determine their relationship (e.g., greater than, less than).
Logical operators: Symbols used to combine or manipulate boolean values (e.g., AND, OR).
The toLowerCase() method in Java converts all uppercase characters in a string to lowercase. It returns a new string with the converted characters.
Character: A single unit of information that represents a letter, digit, or symbol. The toLowerCase() method operates on each character within a string.
ASCII: A character encoding standard that assigns unique numeric codes to represent characters. The conversion performed by toLowerCase() follows ASCII rules for changing uppercase letters.
Method Chaining: In programming, method chaining refers to calling multiple methods in sequence on an object. You can chain methods like substring() and toLowerCase() together for more complex transformations on strings.
The toUpperCase() method is a built-in function in Java that converts all the characters in a string to uppercase letters.
toLowerCase(): This is another built-in function in Java that converts all the characters in a string to lowercase letters.
charAt(): This method returns the character at a specified index position within a string.
length(): The length() method returns the number of characters in a string.
A public class is one that can be accessed and used by any other class or program. It serves as the blueprint for creating objects and contains variables and methods.
private class: This refers to a class that can only be accessed within its own file. Other classes cannot directly access its variables or methods.
static keyword: When applied to variables or methods, it means they belong to the class itself rather than instances of the class.
inheritance: Inheritance allows one class (the child) to inherit properties and behaviors from another (the parent).
System.out.println() is a method in Java that allows you to display output on the console. It takes an argument (a value or a variable) and prints it as text.
String: A sequence of characters, such as words or sentences, in programming. Strings are often used as arguments for System.out.println() to display specific messages.
Variable: A named storage location in computer memory that holds a value. Variables can be passed as arguments to System.out.println() to print their current values.
Concatenation: The process of combining two or more strings together. You can use concatenation with System.out.println() to display multiple strings in one line.