Strings
Overview: 2.6.0
- Strings are objects of the
String
class- 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
null
indicates that a variable doesn’t reference any object yet- A
reference
is 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
new
keyword 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
String
class, store the value in memory, and setmyString
to reference the new string
Packages and Inherence
- Full name for
String
isjava.lang.String
java.lang
is thepackage
name- Every class is in a package
java.lang
is used for standard packages
- Every object knows it’s class
- Every object knows it’s parent class
- class can
inherit
object fields and methods from a parent superclass
is 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 + 3
becomes"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
Strings
are objects of theString
class- Hold sequences of characters
- Created with a string literal…
String s = "hello";
- Or by calling the class constructor
String s = new String("Hello");
new
creates a new object of a classnull
indicates 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\n
to 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.