Strings
Overview: 2.6.0
- Strings are objects of the
Stringclass- Hold sequence of characters
- Class defines the data that that object has
- Classes begin with capital letter
- Primitives start with a lower case letter
Null and Object References
- The keyword
nullindicates that a variable doesn’t reference any object yet- A
referenceis a way to find the actual object in memory- Like a contact in your phone
- A
Constructing a String
- Two ways to construct a string
- Using the
newkeyword and a class constructorString myString = new String("Hello, world");
- Create a
string literal- A set of characters in double quotes
- `String myString = “Hello, world”;
- Using the
- Both ways create a
Stringclass, store the value in memory, and setmyStringto reference the new string
Packages and Inherence
- Full name for
Stringisjava.lang.Stringjava.langis thepackagename- Every class is in a package
java.langis used for standard packages
- Every object knows it’s class
- Every object knows it’s parent class
- class can
inheritobject fields and methods from a parent superclassis another word fromparent- All classes inherit from
java.lang.Object
- class can
String Operators - Concatenation: 2.6.1
- Strings can be appended to each other with
+or+=- Called
concatenation - Works with non-string values
- these will be converted using
toString
- these will be converted using
- Called
- Spaces are not added automatically
- Variables are never put inside quotes
Order of operations
- The same operators are processed left to right
"12" + 4 + 3becomes"1243"- 4 becomes a string, then 3 does too
- to print
"127", use addition
Escape characters
- To print a literal double quote, you need to “escape” it with a backslash
- double quote is a reserved character in Java
"\""
- To use a literal backslash, escape it with a bashslash
"\\"
"\n"is a newline character
Summary: 2.6.3
Stringsare objects of theStringclass- Hold sequences of characters
- Created with a string literal…
String s = "hello";
- Or by calling the class constructor
String s = new String("Hello");
newcreates a new object of a classnullindicates that an object reference doesn’t refer to anything- Strings can be concatenated with
+or+=- Primitives can be concatenated with Strings
- causes implicit conversions of the values
- Primitives can be concatenated with Strings
- Escape sequences start with backslash (
\) and have special meanings- This course covers
\",\\, and\nto mean a literal doublequote, literal backslash, and newline character.
- This course covers

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.