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: extinta=10;ext{int } a = 10; stores the value 10 directly in a memory cell named a.
    • Reference: extStrings="John";ext{String } s = "John"; 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: byte,short,int,long,float,double,char,boolean.byte, short, int, long, float, double, char, boolean.
    • 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: extnumOne=10;ext{numOne} = 10;
    • Example variables and naming conventions
    • Use expressive names, often in all caps with underscores for symbolic constants (conventional, not required):
      • finalextintNUMONE=10;final ext{ int } NUM_ONE = 10;
    • For non-constants, camelCase is common: inttotalPrice=100;int totalPrice = 100;
    • Constants
    • Use final to declare a constant: finalextintNUMONE=1;final ext{ int } NUM_ONE = 1;
    • A common convention is to use all caps with underscores for symbolic constants (e.g., PI=3.14159PI = 3.14159, often declared as staticfinaldoublePI=3.14159;static final double PI = 3.14159; 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., intbudget=10000;int budget = 10_000;).
    • Literal vs symbolic constants
    • Literal constant: a numeric literal like 1010 or 2020.
    • Symbolic constant: a named constant like NUM_ONE.
  • Numeric literals, type inference, and casting

    • Floating point literals and type matching
    • A decimal like 12.512.5 is a double by default in Java.
    • Assigning a decimal literal to a float variable requires explicit casting or a suffix:
      • Wrong: floatf=12.5;float f = 12.5; // error: double to float narrowing
      • Right: floatf=12.5f;float f = 12.5f; or cast: floatf=(float)12.5;float f = (float)12.5;
    • Widening vs narrowing conversions
    • Widening (lossless): converting a smaller type to a larger type (e.g., intolongint o long).
    • Narrowing (potential loss of data): converting a larger type to a smaller type (e.g., doubleofloatdouble o float) requires explicit casting.
    • Example: casting a double to float: floatf=(float)12.5;float f = (float) 12.5;
    • Type promotion and literals
    • Decimal literals default to double: 12.512.5 is a double literal.
    • To force a float literal, suffix with ff: 12.5f12.5f.
  • Operators: binary, unary, and increment/decrement nuances

    • Binary operators (two operands): +,,imes,/,mod+, -, imes, /, \bmod (modulus). Example: a+b,ab,aimesb,a/b,amodba + b, a - b, a imes b, a / b, a \bmod b.
    • Integer division behavior
    • When both operands are integers, the result is an integer (decimal portion is discarded).
    • Example: 14/8=114 / 8 = 1 (not 1.75) and 14mod8=614 \bmod 8 = 6.
    • Compound assignment operators
    • Each arithmetic operator has a compound form: +=, -=, \*=, \/=, \%=. Example: total+=100;total += 100; is equivalent to total=total+100;total = total + 100;
    • 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; result=++x;result = ++x; results in x = 15, result = 15; while result=x++;result = x++; results in x = 15, result = 14.
    • Arithmetic on chars is allowed because chars are integral values (Unicode/ASCII). Example: c+1'c' + 1 yields the next character, d'd'.
    • 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: extMath.round,extMath.pow,extMath.sqrt,extMath.max,extMath.min,extMath.random.ext{Math.round}, ext{Math.pow}, ext{Math.sqrt}, ext{Math.max}, ext{Math.min}, ext{Math.random}.
    • Examples
    • Rounding: extMath.round(1.6667)=2;extMath.round(1.49)=1.ext{Math.round}(1.6667) = 2; ext{Math.round}(1.49) = 1. extNote:1.66isroundedtothenearestlongbydefaultext{Note: 1.66… is rounded to the nearest long by default}.
    • Power: extMath.pow(2,2)=4.0;extMath.pow(2,3)=8.0;extMath.pow(5,2)=25.0.ext{Math.pow}(2,2) = 4.0; ext{Math.pow}(2,3) = 8.0; ext{Math.pow}(5,2) = 25.0. (returns double)
    • Square root: extMath.sqrt(9)=3.0ext{Math.sqrt}(9) = 3.0
    • Min/Max: Given x=67,y=23x=67, y=23, extMath.max(x,y)=67,extMath.min(x,y)=23ext{Math.max}(x,y) = 67, ext{Math.min}(x,y) = 23
    • Random: extMath.random()ext{Math.random}() returns a value in [0,1)[0,1); scale by 100 for a range [0,100)[0,100).
    • 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):
    • byte:1extbyte,short:2extbytes,int:4extbytes,long:8extbytes,char:2extbytes,boolean:implementationdependent(often1byte),float:4extbytes,double:8extbytes.byte: 1 ext{ byte}, short: 2 ext{ bytes}, int: 4 ext{ bytes}, long: 8 ext{ bytes}, char: 2 ext{ bytes}, boolean: implementation-dependent (often 1 byte), float: 4 ext{ bytes}, double: 8 ext{ bytes}.
    • 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: amodba \bmod b gives the remainder after division, e.g., 14mod8=6.14 \bmod 8 = 6.
    • 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.