Fiveable
Fiveable
pep
Fiveable
Fiveable

or

Log in

Find what you need to study


Light

2.6 String Objects: Concatenation, Literals, and More

7 min readdecember 26, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

A Technical Look At Strings

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 included in Java and have a set of methods that come along with it. We'll see what we can do with the 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.

Escape Characters

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 and you can type out your quote?

What are anyways? 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 CharacterWhat it Prints
\"" (a quotation mark)
\\\ (a backslash)
\nA line break, so the remainder of the string is printed on a new line

String Concatenation

Sometimes, we also want to combine two strings together, and this is done with the help of . is done through the + operator and combines two strings together. Here is an example of :

"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 and not mathematical addition, so the strings are combined.

Here is another example. Do you think that the result of the 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 and converts the integer to a string. In fact, if we are using 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 , 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 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.

String Concatenation Practice Problems

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 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:

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:

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.

Summary of String Objects

  • Strings are objects in Java and are part of the , which has a set of methods that can be used to manipulate strings

  • There are two ways to create strings: using a pre-initialized string or using a constructor

    • String greeting = "Hello";

    • String greeting = new String("Hello");

  • are special characters preceded by a backslash that can be used in strings to print special characters or whitespace (ex: \n)

  • combines two strings using the + operator, and if one side of the concatenation is not a string, it will be converted to a string before being combined

  • It is possible to concatenate variables and objects, and if an object is concatenated, its toString() method is called to convert it to a string

Key Terms to Review (10)

+ Operator

: The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.

Escape characters

: 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.

main method

: The main method is the entry point of any Java program. It acts as the starting point for execution when you run your code, and it must be present in every Java program.

public class

: 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.

String class

: 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.

String Concatenation

: 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.

substring()

: The substring() method in Java is used to extract a portion of a string based on specified starting and ending indexes. It returns a new string containing the extracted characters.

System.out.println()

: 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.

toLowerCase()

: The toLowerCase() method in Java converts all uppercase characters in a string to lowercase. It returns a new string with the converted characters.

toUpperCase()

: The toUpperCase() method is a built-in function in Java that converts all the characters in a string to uppercase letters.

2.6 String Objects: Concatenation, Literals, and More

7 min readdecember 26, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

A Technical Look At Strings

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 included in Java and have a set of methods that come along with it. We'll see what we can do with the 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.

Escape Characters

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 and you can type out your quote?

What are anyways? 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 CharacterWhat it Prints
\"" (a quotation mark)
\\\ (a backslash)
\nA line break, so the remainder of the string is printed on a new line

String Concatenation

Sometimes, we also want to combine two strings together, and this is done with the help of . is done through the + operator and combines two strings together. Here is an example of :

"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 and not mathematical addition, so the strings are combined.

Here is another example. Do you think that the result of the 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 and converts the integer to a string. In fact, if we are using 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 , 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 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.

String Concatenation Practice Problems

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 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:

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:

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.

Summary of String Objects

  • Strings are objects in Java and are part of the , which has a set of methods that can be used to manipulate strings

  • There are two ways to create strings: using a pre-initialized string or using a constructor

    • String greeting = "Hello";

    • String greeting = new String("Hello");

  • are special characters preceded by a backslash that can be used in strings to print special characters or whitespace (ex: \n)

  • combines two strings using the + operator, and if one side of the concatenation is not a string, it will be converted to a string before being combined

  • It is possible to concatenate variables and objects, and if an object is concatenated, its toString() method is called to convert it to a string

Key Terms to Review (10)

+ Operator

: The "+" operator is an arithmetic operator commonly used for addition. However, it also serves as the concatenation operator for combining strings together.

Escape characters

: 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.

main method

: The main method is the entry point of any Java program. It acts as the starting point for execution when you run your code, and it must be present in every Java program.

public class

: 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.

String class

: 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.

String Concatenation

: 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.

substring()

: The substring() method in Java is used to extract a portion of a string based on specified starting and ending indexes. It returns a new string containing the extracted characters.

System.out.println()

: 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.

toLowerCase()

: The toLowerCase() method in Java converts all uppercase characters in a string to lowercase. It returns a new string with the converted characters.

toUpperCase()

: The toUpperCase() method is a built-in function in Java that converts all the characters in a string to uppercase letters.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.