Using Classes and Objects in Java: A Comprehensive Guide
Overview of Using Classes and Objects
This material focuses on the foundational concepts of utilizing predefined classes and their resulting objects to create complex Java programs.
Key focus areas include:
Object creation and the mechanics of object references.
The
Stringclass and its specific behaviors and methods.Exploration of the Java API (Application Programming Interface) class library.
Utilizing the
RandomandMathclasses for specialized computations.Techniques for formatting output for user presentation.
Introductory concepts regarding enumerated types.
The use and behavior of wrapper classes.
Creating Objects and Object References
In Java, a variable serves as a storage location for either a primitive value (like an
intordouble) or a reference to an object.A class name acts as a type when declaring an object reference variable. For example:
String title;This declaration does not create an object; it only creates a variable capable of holding the address of a
Stringobject.
Object references can be conceptualized as pointers to the memory location where the actual object resides.
The object itself must be created separately from the declaration through a process called instantiation.
The new Operator and Instantiation
Instantiation is the act of creating a new instance of a particular class.
Generally, the
newoperator is used to create an object:title = new String("Java Software Solutions");
This line of code performs several actions:
It invokes the
Stringconstructor, which is a special method designed to set up the object.It allocates memory for the new object.
It returns the address of that memory, which is then stored in the
titlereference variable.
Invoking Methods
Once an object is instantiated, the dot operator is used to invoke its methods.
Syntax:
numChars = title.length().Method invocation is effectively asking an object to perform a service or provide information.
Methods may return a value, which can then be utilized in expressions or assigned to other variables.
Object References vs. Primitive Variables
A primitive variable contains the actual value itself (e.g., the number ).
An object variable does not contain the object; it contains the address (reference) where the object is stored.
Assignment Behavior:
For primitive types:
num2 = num1;creates a copy of the value innum1and stores it innum2. Both variables remain independent.For object references:
name2 = name1;copies the address stored inname1intoname2. Both variables now point to the exact same object in memory.
Aliases and Side Effects
Two or more references that point to the same object are known as aliases.
This creates a scenario where one object is accessible through multiple variables.
Caution is required: changing an object's state through one reference variable changes it for all its aliases, as only one underlying object actually exists.
Garbage Collection
An object becomes "garbage" when it no longer has any valid references pointing to it, making it inaccessible to the program.
Java features automatic garbage collection, where the runtime system periodically identifies and reclaims the memory used by garbage objects to return it to the system.
This differs from languages like C++, where the programmer is manually responsible for memory deallocation.
The String Class
The
Stringclass is unique in Java because strings are so fundamental to programming.Special Syntax:
Stringobjects can be created without thenewoperator using string literals:title = "Java Software Solutions";
Every string literal enclosed in double quotes is technically a
Stringobject.Immutability:
Stringobjects are immutable. Once created, neither their value nor their length can be modified. Methods that appear to modify a string actually return a completely newStringobject.
String Indexes
Individual characters within a string are accessed via a numeric index.
Java uses zero-based indexing:
In the string
"Hello":'H'is at index'e'is at index'l'is at index'l'is at index'o'is at index
String Class Method Examples
length(): Returns the number of characters in the string.concat(String str): Returns a new string that is the original string concatenated with the argument.toUpperCase(): Returns a new string with all characters converted to uppercase.replace(char oldChar, char newChar): Returns a new string where all instances ofoldCharare replaced bynewChar.substring(int beginIndex, int endIndex): Returns a new string that is a subset of the original, starting atbeginIndexand ending atendIndex - 1.
Class Libraries and the Java API
A class library is a collection of pre-written classes that provide common functionality.
The Java Standard Class Library is an essential part of the Java development environment.
Java API (Application Programming Interface): The library is often referred to as the API, providing documentation on how to use these classes.
Related classes are organized into clusters called packages:
java.lang: General support classes (automatically imported).java.util: Utility classes (likeScannerandRandom).java.net: Network communication.javafx.scene.shape: Graphical shapes.javafx.scene.control: GUI controls.
The import Declaration
To use a class from a package, you can use the fully qualified name (e.g.,
java.util.Scanner) or animportstatement.import java.util.Scanner;allows the use of justScannerin the code.The wildcard character
*imports all classes in a package:import java.util.*;.Classes in
java.lang(likeStringandSystem) are imported automatically into every Java program.
The Random and Math Classes
The Random Class
Part of
java.util.It produces pseudorandom numbers based on a seed value and complex calculations.
Methods:
nextInt(): Returns a randomintacross the entire range of possible values.nextInt(n): Returns a randomintin the range of to .nextFloat(): Returns a randomfloatbetween (inclusive) and (exclusive).
The Math Class
Part of
java.lang.Contains static methods for mathematical functions. Because they are static, no
Mathobject needs to be instantiated to use them.Example:
Math.sqrt(25)orMath.pow(base, exponent).Quadratic Formula Context:
Given the equation:
The discriminant is calculated as:
The roots are calculated using:
Formatting Output
Java provides classes in the
java.textpackage to format values for display.
NumberFormat Class
Provides generic formatters for currency and percentages.
It uses static methods to get formatter objects:
getCurrencyInstance(): Localizes currency symbols (e.g., adds$and decimals).getPercentInstance(): Converts a fraction to a percentage (e.g., to6%).
The
format()method converts the numeric value into the formatted string.
DecimalFormat Class
Allows for specific custom formatting patterns for floating-point numbers.
Patterns are passed to the constructor. For example,
new DecimalFormat("0.###")specifies that the number should be rounded/truncated to three decimal places if they exist.
Wrapper Classes
Each primitive type has a corresponding wrapper class in
java.langthat allows a primitive value to be treated as an object.Mapping:
byte»Byteshort»Shortint»Integerlong»Longfloat»Floatdouble»Doublechar»Characterboolean»Boolean
Use Cases:
Useful when working with classes (like collection containers) that can only store objects, not primitives.
Provide utility constants like
Integer.MIN_VALUEandInteger.MAX_VALUE.Provide utility methods like
Integer.parseInt(str)to convert a String to anint.
Autoboxing and Unboxing
Autoboxing: The automatic conversion of a primitive value to its corresponding wrapper object (e.g., assigning an
intto anIntegervariable).Unboxing: The automatic conversion of a wrapper object back to its primitive type when needed (e.g., assigning an
Integerobject to acharvariable if the object is aCharactertype).
Questions & Discussion
Q: What output is produced by the following?
String str = "Space, the final frontier.";
System.out.println(str.length());
System.out.println(str.substring(7));
System.out.println(str.toUpperCase());
System.out.println(str.length());
A:
the final frontier.SPACE, THE FINAL FRONTIER.
Q: Given a Random object gen, what is the range of gen.nextInt(10) - 5?A: The range is to .
Q: Write an expression for a random integer from 15 to 20.A: gen.nextInt(6) + 15 (Generates to , then shifts by ).
Q: Are the following assignments valid?
Double value = 15.75;Character ch = new Character('T'); char myChar = ch;A:Yes, the
doubleliteral is autoboxed into aDoubleobject.Yes, the
charin the object is unboxed back to a primitivecharfor the assignment.