UIL CS: Java Fundamentals

This is part of the UIL CS study series. See also:

Main topic list: https://www.uiltexas.org/files/academics/UILCS-JavaTopicList2526.pdf


2. printf (Java)

Common formatting codes

Use: System.out.printf("format", values...);

CodeMeaningExample
%dinteger%d
%ffloating point%f
%.nffloat w/ n decimals%.2f
%sstring%s
%cchar%c
%bboolean%b
%nnewline%n
%%literal percent sign%%

Width + alignment

  • %10d width 1010 right-aligned
  • %-10d width 1010 left-aligned
  • %05d pad with zeros

Examples

int x = 42;
double pi = Math.PI;
String name = "UIL";

System.out.printf("x=%d%n", x);            // x=42
System.out.printf("pi=%6.3f%n", pi);       // pi= 3.142
System.out.printf("%10d%n", x);            // [       42]
System.out.printf("%-10s%n", name);        // [UIL      ]
System.out.printf("%05d%n", x);            // 00042
System.out.printf("100%% done%n");         // 100% done

3. Operator Precedence

  1. Parentheses: ()
  2. Unary: !, ++, --, unary + -
  3. Multiply: * / %
  4. Add: + -
  5. Shift: << >> >>>
  6. Relational: < <= > >= instanceof
  7. Equality: == !=
  8. Bitwise: & then ^ then |
  9. Logical: && then ||
  10. Ternary: ? :
  11. Assignment: = += -= ...

Memorization trick: "PUMA SREBLTA"

  • Parentheses
  • Unary
  • Note: postfix operators return the old value of a variable and update the variable immediately
  • Multiplicative
  • Additive
  • Shift
  • Relational
  • Equality

6. Memory Allocated for Java Data Types

Primitive types (fixed sizes)

TypeBitsBytesNotes
booleanJVM-dependentusually 1 byte in arrays, not guaranteed
byte81-128..127
short162
char162unsigned 0..65535
int324
float324IEEE 754
long648
double648IEEE 754

Reference types

String, arrays, objects, collections store:

  • a reference in the variable
  • actual object is on the heap

Reference size depends on JVM (commonly 44 bytes with compressed oops, or 88 bytes). UIL questions typically focus on primitive sizes.