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 String class and its specific behaviors and methods.

    • Exploration of the Java API (Application Programming Interface) class library.

    • Utilizing the Random and Math classes 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 int or double) 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 String object.

  • 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 new operator is used to create an object:

    • title = new String("Java Software Solutions");

  • This line of code performs several actions:

    • It invokes the String constructor, 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 title reference 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 3838).

  • 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 in num1 and stores it in num2. Both variables remain independent.

    • For object references: name2 = name1; copies the address stored in name1 into name2. 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 String class is unique in Java because strings are so fundamental to programming.

  • Special Syntax: String objects can be created without the new operator using string literals:

    • title = "Java Software Solutions";

  • Every string literal enclosed in double quotes is technically a String object.

  • Immutability: String objects are immutable. Once created, neither their value nor their length can be modified. Methods that appear to modify a string actually return a completely new String object.

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 00

    • 'e' is at index 11

    • 'l' is at index 22

    • 'l' is at index 33

    • 'o' is at index 44

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 of oldChar are replaced by newChar.

  • substring(int beginIndex, int endIndex): Returns a new string that is a subset of the original, starting at beginIndex and ending at endIndex - 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 (like Scanner and Random).

    • 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 an import statement.

  • import java.util.Scanner; allows the use of just Scanner in the code.

  • The wildcard character * imports all classes in a package: import java.util.*;.

  • Classes in java.lang (like String and System) 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 random int across the entire range of possible values.

    • nextInt(n): Returns a random int in the range of 00 to n1n-1.

    • nextFloat(): Returns a random float between 0.00.0 (inclusive) and 1.01.0 (exclusive).

The Math Class
  • Part of java.lang.

  • Contains static methods for mathematical functions. Because they are static, no Math object needs to be instantiated to use them.

  • Example: Math.sqrt(25) or Math.pow(base, exponent).

  • Quadratic Formula Context:

    • Given the equation: ax2+bx+c\text{ax}^2 + \text{bx} + \text{c}

    • The discriminant is calculated as: discriminant=b24ac\text{discriminant} = b^2 - 4ac

    • The roots are calculated using:

    • root1=b+discriminant2a\text{root1} = \frac{-b + \sqrt{\text{discriminant}}}{2a}

    • root2=bdiscriminant2a\text{root2} = \frac{-b - \sqrt{\text{discriminant}}}{2a}

Formatting Output

  • Java provides classes in the java.text package 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., 0.060.06 to 6%).

  • 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.lang that allows a primitive value to be treated as an object.

  • Mapping:

    • byte »Byte

    • short »Short

    • int»Integer

    • long»Long

    • float »Float

    • double »Double

    • char »Character

    • boolean » Boolean

  • Use Cases:

    • Useful when working with classes (like collection containers) that can only store objects, not primitives.

    • Provide utility constants like Integer.MIN_VALUE and Integer.MAX_VALUE.

    • Provide utility methods like Integer.parseInt(str) to convert a String to an int.

Autoboxing and Unboxing
  • Autoboxing: The automatic conversion of a primitive value to its corresponding wrapper object (e.g., assigning an int to an Integer variable).

  • Unboxing: The automatic conversion of a wrapper object back to its primitive type when needed (e.g., assigning an Integer object to a char variable if the object is a Character type).

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:

  • 2626

  • the final frontier.

  • SPACE, THE FINAL FRONTIER.

  • 2626

Q: Given a Random object gen, what is the range of gen.nextInt(10) - 5?A: The range is 5-5 to 44.

Q: Write an expression for a random integer from 15 to 20.A: gen.nextInt(6) + 15 (Generates 00 to 55, then shifts by 1515).

Q: Are the following assignments valid?

  1. Double value = 15.75;

  2. Character ch = new Character('T'); char myChar = ch; A:

  3. Yes, the double literal is autoboxed into a Double object.

  4. Yes, the char in the object is unboxed back to a primitive char for the assignment.