Module 3
Chapter Overview
Title: Introduction to Program Design and Data Structures
Author: John Lewis
Edition: Fifth Edition
Chapter Scope
Key Concepts:
Creating objects
Services of the String class
Java API class library
Random and Math classes
Formatting output
Introducing enumerated types
Wrapper classes
Creating Objects
Object Variables:
A variable can hold a primitive type or an object reference.
Example:
String title;
(No object created, just a reference variable)The object must be instantiated separately.
Instantiation:
Use
new
operator:title = new String("James Gosling");
This calls the String constructor, which initializes the object.
Creating Strings
String Instantiation:
Strings can be created without the
new
operator:title = "Java rocks!"
Each string literal represents a String object.
Invoking Methods
Method Invocation:
Use the dot operator:
count = title.length()
Methods may return values for assignments or expressions.
Invoking a method = asking an object to perform a service.
Object References
Variable Types:
Primitive variable contains the actual value.
Object variable contains the reference (address) of the object.
Reference can be visualized graphically.
Example:
name1
-> "Steve Jobs"num1
-> 38
Assignment Revisited
Primitive Types Assignment:
Assignment copies values (e.g.,
num2 = num1;
)Changes in
num1
will not affectnum2
.
Object References Assignment:
Assignment copies the reference (address).
Example:
name2 = name1;
Both now reference the same object, affecting each other.
Aliases
Definition:
Multiple references can refer to the same object.
Useful but requires careful management to avoid unintended changes.
Impact:
Changing an object through one reference changes it for all aliases.
Garbage Collection
Concept:
Objects without valid references are considered garbage.
Java performs automatic garbage collection, reclaiming memory.
Unlike other languages, Java handles this automatically.
The String Class
Immutability:
Strings cannot be changed after creation (e.g., length and values are fixed).
Methods return new modified String objects.
Accessing Characters:
Use numeric index to access characters in a string.
Example: In "Hello", 'H' is at index 0, 'o' is at index 4.
String Class Methods
Common Methods:
Constructor:
String(String str)
- creates a new string object.charAt(int index): returns character at specified index.
compareTo(String str): compares lexicographically with another string.
concat(String str): concatenates another string.
equals(String str): checks equality based on case sensitivity.
length(): returns the string's length.
replace(char oldChar, char newChar): replaces characters in the string.
substring(int offset, int endIndex): returns a subset of the string.
toLowerCase() and toUpperCase(): convert case of characters.
The Java API
Definition:
A collection of classes available in Java for program development.
API stands for Application Programming Interface.
Using Classes:
Classes like
System
,Scanner
, andString
are part of the Java API.Custom class libraries can also be created or obtained from vendors.
Packages
Organization:
Java API classes are organized into packages.
Import Declarations
Using Classes:
Fully qualify class names (e.g.,
java.util.Scanner
).Import classes for easier access (e.g.,
import java.util.Scanner;
).Wildcard to import all classes in a package (e.g.,
import java.util.*;
).
The java.lang Package
Automatic Import:
Classes in this package are automatically imported.
This includes
System
andString
.Scanner
must be imported explicitly as it's injava.util
.
The Random Class
Overview:
Part of the
java.util
package.Generates pseudorandom numbers using methods.
Common Methods:
Constructor:
Random()
- creates a number generator.nextFloat(): returns random float between 0.0 and 1.0.
nextInt(): generates an integer value.
nextInt(int num): ranges between 0 and specified limit.
The Math Class
Overview:
Part of the
java.lang
package.Contains static methods for mathematical functions.
Common Methods:
Math.abs(int num)
- absolute value.Math.sqrt(double num)
- square root.Math.pow(double num, double power)
- exponentiation.Math.random()
- generates a random number.
Formatting Output
Purpose:
Formats values for display.
Useful in presenting data clearly.
Classes:
NumberFormat
: formats as currency or percentages.DecimalFormat
: formats based on patterns.
Enumerated Types
Definition:
Defines a type with specified values.
Example:
enum Season {winter, spring, summer, fall};
Usage:
Type-safe, only assigns valid values from enumeration.
Each enumeration value has an ordinal integer starting from zero.
Wrapper Classes
Definition:
Classes in
java.lang
that correspond to primitive types (e.g., Integer, Double).
Usage:
Can be used where objects are required instead of primitive types (e.g., collections).
Contains static methods for type management, such as parsing strings to numbers.
Autoboxing:
Automatic conversion of a primitive type to a wrapper object (e.g.,
int
toInteger
).The opposite process is called unboxing.