Java Primitives, References, Variables, Math, Formatting, and Strings (Ch. 3 & 14)
Chapter 3 & 14 Recap: Java Primitives, References, Variables, and Strings
Course context
- Based on Marux Java programming sixth edition, chapters 3 and 14.
- Core ideas are largely stable across editions; minor changes may appear over time.
- Instructor uses slides for key points but emphasizes understanding through examples and recurring concepts.
- Quick setup example: create an IntelliJ project for “lecture two” in the same folder as the prior lecture’s project to stay organized.
Primitive vs. Reference types (Chapter 3 focus)
- Two major type categories in Java: primitive types and reference types.
- Primitives hold data directly; references point to objects stored on the heap.
- Example intuition:
- Primitive: stores the value 10 directly in a memory cell named a.
- Reference: the variable s holds a reference to an object created on the heap containing the string data.
- Heap and addresses
- Primitive variables contain the actual data in their memory location.
- Reference variables contain a memory address (a reference) that points to the actual object on the heap.
- Example illustration: memory location 0xFFAA22 (synthetic) holds the object; the reference variable contains the address to that object.
Primitive types and sizes (eight types)
- The eight primitive types in Java are:
- General sizes (as presented; note a common source of confusion in the talk):
- ext{byte}
ightarrow 1 ext{ byte} - ext{short}
ightarrow 2 ext{ bytes} - ext{int}
ightarrow 4 ext{ bytes} - ext{long}
ightarrow 8 ext{ bytes} - ext{float}
ightarrow 4 ext{ bytes} - ext{double}
ightarrow 8 ext{ bytes} - ext{char}
ightarrow 2 ext{ bytes (UTF-16)} - ext{boolean}
ightarrow ext{implementation-dependent (often 1 byte)} - Important note: The lecture transcript incorrectly stated float as 2 bytes and double as 4 bytes. The correct sizes are as listed above: float = 4 bytes, double = 8 bytes.
- Mnemonic: many beginners memorize the order by increasing size: 1, 2, 4, 8 bytes; except char is 2 bytes (UTF-16) and boolean varies.
- Practical tip: memorize the type names first; sizes are helpful but not always essential for day-to-day coding.
Declaring, initializing, and naming variables
- Declaration vs initialization/assignment
- Declaration: introduces a variable name and type, allocating memory. Example: int
um ext{ one;} - Initialization / assignment: gives the variable its first value. Example:
- Example variables and naming conventions
- Use expressive names, often in all caps with underscores for symbolic constants (conventional, not required):
- For non-constants, camelCase is common:
- Constants
- Use final to declare a constant:
- A common convention is to use all caps with underscores for symbolic constants (e.g., , often declared as within a class).
- Literals and notation
- Literal constants (e.g., 10, 20) are also constants in the sense of fixed values.
- Underscores in numeric literals improve readability; underscores are ignored by the compiler (e.g., ).
- Literal vs symbolic constants
- Literal constant: a numeric literal like or .
- Symbolic constant: a named constant like NUM_ONE.
Numeric literals, type inference, and casting
- Floating point literals and type matching
- A decimal like is a double by default in Java.
- Assigning a decimal literal to a float variable requires explicit casting or a suffix:
- Wrong: // error: double to float narrowing
- Right: or cast:
- Widening vs narrowing conversions
- Widening (lossless): converting a smaller type to a larger type (e.g., ).
- Narrowing (potential loss of data): converting a larger type to a smaller type (e.g., ) requires explicit casting.
- Example: casting a double to float:
- Type promotion and literals
- Decimal literals default to double: is a double literal.
- To force a float literal, suffix with : .
Operators: binary, unary, and increment/decrement nuances
- Binary operators (two operands): (modulus). Example: .
- Integer division behavior
- When both operands are integers, the result is an integer (decimal portion is discarded).
- Example: (not 1.75) and .
- Compound assignment operators
- Each arithmetic operator has a compound form: +=, -=, \*=, \/=, \%=. Example: is equivalent to
- Unary operators
- Increment and decrement: and , and positive/negative signs.
- Prefix vs postfix (++/-- in front vs after the variable):
- Prefix: increments then returns the value.
- Postfix: returns the old value, then increments.
- Example: let x = 14; results in x = 15, result = 15; while results in x = 15, result = 14.
- Arithmetic on chars is allowed because chars are integral values (Unicode/ASCII). Example: yields the next character, .
- Operator precedence (PEMDAS-style)
- Highest: increment/decrement, then unary plus/minus, then multiplication/division/modulus, then addition/subtraction.
- Parentheses can alter precedence to ensure correct evaluation order.
Math utilities (java.lang.Math)
- All methods are static; no object creation required.
- Common methods:
- Examples
- Rounding: .
- Power: (returns double)
- Square root:
- Min/Max: Given ,
- Random: returns a value in ; scale by 100 for a range .
- Note on conversion around Math methods
- Results are typically double; cast as needed for integer results.
Number formatting and locale (java.text.NumberFormat, java.util.Locale)
- NumberFormat basics
- Default locale formatting uses the system locale; currency and decimal placements adjust accordingly.
- Example: format a double amount like 12345.678 with default locale to show thousands separators and decimal places according to locale.
- Currency formatting
- NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
- String formattedCurrency = currencyFormat.format(amount);
- You can specify locales: NumberFormat.getCurrencyInstance(Locale.US) or Locale.GERMANY, etc.
- Distinction from Math class: NumberFormat handles locale-specific formatting for currencies and percentages, not arithmetic.
- Example walkthrough from transcript: converting 12345.678 to default format, then to currency format, then to a German locale currency format shows locale-specific symbols and separators (e.g., $1,212,345.68 vs. 1.212.345,68 €).
- Import details: NumberFormat is in java.text, Locale is in java.util.
Practical number formatting example (live coding idea from transcript)
- Code paths shown:
- Double amount = 12345.678;
- NumberFormat defaultFormat = NumberFormat.getInstance();
- String defaultFormatted = defaultFormat.format(amount);
- NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
- String formattedCurrency = currencyFormat.format(amount);
- NumberFormat germanCurrencyFormat = NumberFormat.getCurrencyInstance(Locale.GERMANY);
- String germanCurrency = germanCurrencyFormat.format(amount);
- Output expected:
- Default: 12,345.678 (depends on locale)
- US currency: $12,345.68 (rounded to two decimals)
- German currency: 12.345,68 € (locale-specific separators)
- Note: precision and locale affect both currency formatting and decimal separators.
System.out.printf and String formatting (printf-style)
- System.out.printf and System.out.format adopt printf-style formatting.
- Type codes (placeholders):
- %d for decimal integers
- %f for floating-point numbers
- %s for strings
- %n for a platform-independent newline (preferred over \n in some contexts)
- Placeholders and arguments
- The format string contains placeholders; subsequent arguments fill those placeholders in order.
- Example: System.out.printf("%s is %d years old%n", name, age);
- Formatting details
- You can control width, alignment, grouping separators, and decimal places: e.g., "%10.2f" formats a float with width 10 and 2 decimals, right-justified; "%-10.2f" left-justifies within width 10.
- The transcript shows examples with currency-like formatting and alignment for invoices.
- Relationship to NumberFormat
- String formatting via printf is a formatting aid; NumberFormat provides locale-aware numeric and currency formatting.
Strings: Chapter 14 overview (core string API concepts)
- Comparison and testing
- equals vs equalsIgnoreCase:
- equals performs case-sensitive comparison.
- equalsIgnoreCase ignores case differences.
- isEmpty checks for an empty string.
- startsWith and endsWith test prefixes/suffixes.
- contains checks for substring presence anywhere in the string.
- Common mistake to avoid
- Do not use == to compare strings; use equals or equalsIgnoreCase. The double equals compares object references, not content, and can produce misleading results.
- Basic string methods and properties
- length(): number of characters in the string.
- indexOf and lastIndexOf: locate characters or substrings; index starts at 0.
- charAt(index): get a character at a specific index.
- trim(): remove leading/trailing whitespace.
- Substring and splitting
- substring(beginIndex, endIndex): extracts a portion; endIndex is exclusive.
- If endIndex is omitted, substring goes to the end of the string.
- Practical string transformation examples
- Splitting a full name into first and last names using indexOf(' ') to find the space, then substring calls to separate parts.
- Reformatting a name into sentence case: first letter uppercase, remainder lowercase, then re-concatenate.
- Replace and reformatting
- replace(oldChar, newChar) or replaceAll/replace with regex (not explicitly mentioned, but commonly available).
- String manipulation patterns
- Use substring with index to extract parts; reassemble with + (concatenation).
- String concatenation with + is common; Java optimizes but can create temporary strings; StringBuilder offers a more efficient alternative for many concatenations (see below).
- Advanced string operations and data extraction
- Forming a string from parts, concatenating to correct capitalization, and addressing common input irregularities.
Text blocks and multi-line strings (Java 15+)
- Text blocks provide multi-line string literals for easier embedding of long strings or code samples.
- They can be used as an alternative to long string concatenations in multiline content.
String formatting helpers: String.format and String.format-style usage
- The transcript mentions a string formatting approach similar to printf, which is implemented via String.format and related APIs.
- This approach offers flexible control over numeric and textual formatting beyond basic concatenation.
Other string-related topics and patterns mentioned
- StringBuilder
- String is immutable in Java; modifications create new string instances, which can be inefficient for heavy string manipulation.
- StringBuilder allows in-place modification of character data, reducing allocations and improving performance for repeated edits.
- StringBuilder is in java.lang, so no extra imports are needed.
- Arrays and strings interplay (later chapters)
- Strings often get processed into arrays or are manipulated with array-like logic in more advanced examples (e.g., Hangman or file IO-based apps).
- File IO and more advanced demos
- The transcript hints at a Hangman-like application that uses file IO; this is more advanced and typically introduced after foundational topics.
Practical study tips and course pacing
- Expect a lot of new concepts in the early weeks; take it step-by-step and revisit core ideas repeatedly.
- Focus on understanding primitive vs reference types, how declarations and initializations work, and why immutability of String matters.
- Practice with small examples in IntelliJ to reinforce memory management concepts, type casting rules, and common pitfalls (like string comparison and numeric casts).
- Build familiarity with Math and NumberFormat utilities to handle numeric output and locale-specific formatting in real-world applications.
Quick recap of key, test-ready points
- Primitive types and their typical sizes (noting the transcript’s slip for float/double vs the actual):
- Strings are reference types; equals is used for content comparison; == checks reference equality.
- Decimal literals are double by default; cast or suffix with f to assign to float.
- The modulus operation satisfies: gives the remainder after division, e.g.,
- Use Math.* for common math tasks; use NumberFormat for locale-aware formatting; use System.out.printf for inline formatting with placeholders.
- String handling includes: length, indexOf, lastIndexOf, charAt, trim, substring, replace, equals/equalsIgnoreCase, startsWith, endsWith, contains.
- Text blocks (Java 15+) support multi-line strings; StringBuilder offers efficient in-place string modification when many edits are needed.