L4: Using Predefined Classes
Primitive Types vs. Classes
- Primitive Types: Hold the actual values (e.g.,
int
,double
). These variables are stored in a specific area of memory, and their value is directly accessible. - Classes (Reference Types): Hold a reference (memory address) to an object stored in the heap. When you declare a class-type variable, it points to an object, not the actual value.
Declaring Variables
Declaring a variable for a class is similar to declaring a primitive type:
String major; // Declares a reference variable of type String
For primitive types, the variable holds the actual value:
int age = 20; // 'age' holds the value 20
For reference types, the variable holds the address of the object in the heap, not the actual object.
Instantiation
To create an object and get its reference address, use the
new
keyword:String name = new String("Hello");
Here,
new String("Hello")
creates a newString
object in the heap, and the reference (address) is stored in the variablename
.Shortcut for Strings: Strings are special in Java; they can be initialized directly without using
new
:String greeting = "Hi";
Invoking Methods
Methods can be invoked on objects using the dot (
.
) operator:int length = greeting.length(); // Calls the 'length' method on the 'greeting' object
A method’s invocation executes the code inside it and returns a value, if applicable, without modifying the calling object unless specified.
Reference Variables
Reference variables store the address of an object in memory. When you assign one reference variable to another, you copy the address, not the actual object.
String major = new String("Computer Science"); String interest = major; // Copies the address, both 'major' and 'interest' point to the same object
If
major
is updated to point to a new string:Theinterest
variable still points to the original “Computer Science” object unless it is reassigned. In this way, reference variables can become aliases for the same object.major = "Long walks on the beach";
String Methods
- Method Signature: Consists of the method name and its parameters’ types and order.
- Example:
concat(String)
,replace(char, char)
,substring(int, int)
.
- Example:
- The object on which the method is called is known as the calling object.
toLowerCase()
Method:- Converts the string to lowercase and returns a new
String
object. Since strings are immutable, the original string remains unchanged.
String greeting = "HELLO"; String lowerGreeting = greeting.toLowerCase(); // "hello"
- Converts the string to lowercase and returns a new
concat(String str)
Method:Concatenates the specified string (
str
) to the end of the calling string and returns a newString
object.Example:
String firstName = "John"; String fullName = firstName.concat(" Doe"); // "John Doe"
Equivalent to using the
+
operator:String fullName = firstName + " Doe";
replace(char oldChar, char newChar)
Method:Replaces all occurrences of
oldChar
in the calling string withnewChar
and returns a newString
object.Example:
String text = "hello"; String replacedText = text.replace('l', 'p'); // "heppo"
substring(int start, int end)
Method:Returns a new substring starting from the
start
index and extending up to (but not including) theend
index.Indexing starts at 0, and the method throws a runtime error if the indexes are out of range.
Example:
String word = "programming"; String part = word.substring(0, 4); // "prog"
String “Arithmetic” and Immutability
String Concatenation: Uses the
+
operator to combine strings:String name = "John" + " " + "Doe"; // "John Doe"
Immutability: Strings in Java cannot be changed once created. Any modification results in a new string object. For example:
String original = "Hello"; String modified = original.toUpperCase(); // "HELLO" // 'original' remains "Hello"
Working with Predefined Classes
- Java provides many predefined classes, such as
String
. Using these classes involves:- Instantiation: Using the
new
keyword, though some classes likeString
offer shortcuts. - Invoking Methods: Calling methods on objects using the dot (
.
) operator.
- Instantiation: Using the
Summary
- Reference Variables: Store the address of an object, allowing multiple variables to point to the same object (aliases).
- String Methods: Perform various operations on strings while keeping them immutable.
- String Pool: Stores string literals to optimize memory. Directly assigned strings like
"Hello"
are stored in this pool. - Garbage Collection: Automatically frees memory used by objects that no longer have references.