What is the class and object of:
String tree = new String(“oak”);
Class: String
Object: tree
Null in Java
Represents an object or class data type that has not been created.
Two basic types of data types in Java
Primitive types and class (reference) types.
Primitive type
Holds only one piece of data at a time (e.g. int,double,boolean)
Class (reference) type
Can hold more than one piece of data at a time and is a blueprint that defines the properties and methods that objects created from it will have.
How primitive data types are stored in memory
As the actual value (e.g., int number 13, stores 13)
How class data types are stored in memory
As a memory address pointing to where the actual value is stored (e.g., String a = "Howdy";
).
No reference set for a String
Holds the value null
Strings are immutable
They cannot be changed once created. If you modify a string, a new one is created instead of altering the original.
What would be the output of this code?
String alpha = "Toy Story";
String beta = alpha;
alpha = alpha + " 2";
System.out.println(alpha);
System.out.println(beta);
Toy Story 2
Toy Story
Three ways to create Strings in Java
String alpha = "Wonder Woman";`
String beta;
beta = "Superman";
String gamma = new String("Spiderman");
+ operator in Java
Concatenates strings and adds integers.
Concatenation with strings
"Glues" two strings together (e.g.
+= operator with strings
combines the two strings into one
Controlling order of operations with strings and integers
By using parentheses
Escape sequences in Java
\"
- double quote
\n
- new line
\t
- horizontal tab
\\
- backslash
\'
- single quote
Characters stored in a string
Each character is stored with an index starting at 0.
.length() method
Returns the number of characters in the string.
String s = “charizard”;
String t = “charizard”;
s.equals(t)
Tests if two strings are equal (returns true or false).
.substring(start,stop)
gets a part of a string from the start index to the stop index (not including the stop)
.toUpperCase() and .toLowerCase() methods
Convert all letters to uppercase or lowercase
.compareTo(other)
Compares two strings alphabetically.
.indexOf(str)
Searches for a character or string and returns its index position.
Class in Java
"Recipe" for creating objects.
Object in Java
Specific instance of a class.
Example of creating a String object
String tree = new String("oak")
Keyword new in Java
Allocates memory for the new object.
Assigning one object to another
Both variables now point to the same memory location.