Nhảy tới nội dung

Variables, Data Types & Math Operations

Variables

Use only letters & numbers, camelCase. First character cannot be a number.

int total;
int totalStudent;
int 2much; // <- error

Instantiate & Initialize

  • Instantiation: creating an object by using the new keyword.
Person p = new Person();
  • Initialization: assigning a value to a variable is called initialization.
int a = 10;
// or
Person p = new Person();
p.setName("Alice");
p.setAge(30);

Constants

final keyword when it is used on:

  • variable/field: means cannot reassign
  • method: means cannot override
  • class: means cannot inherit

Usage

Variables can be declared final, means the value cannot be changed once set.

final int maxStudents = 25;
// you declare it first
final int someVar;
int someDummyVar = 100;
someVar = someDummyVar;
someVar = 100; // <- error

With object, the reference is constant, but not the object, so you still call method to change fields.

final Person jennie = new Person("Jennie");
jennie = new Person("Lisa"); // <- error
jennie = null; // <- error
jennie.changeName("Lisa"); // can call method to change fields

Read more about Objects.

final can also be used on classes & methods. Read more at final class/method.

Constants vs. Immutable

  • Constants: applies to variables, including object references. It means that you can't reassign the variable.
  • Immutable: applies to objects (e.g. strings). It means that you can't change the state of the object.

Primitive Types

Primitive types are stored by value, means each variable's values are unrelated to any others. These are foundation of all other types:

Integer

TypeBitsMin valueMax valueLiteral form
byte8-1281270
short16-32768327670
int32-214748364821474836470
long64-922337203685477580892233720368547758070L
byte a = 25;
short b = 5280;
int c = 92960000;
long d = 5879000000000L;

Floating Point

TypeBitsSmallest positive valueLargest positive valueLiteral form
float321.4 x 10^-453.4 x 10^380.0f
double644.9 x 10^-3241.7 x 10^3080.0 or 0.0d
float a = 42.195f;
float b = -273.15f;
double c = 0.0000000001d;

Character

char a = 'B';
char b = '\u00DA'; // Ú (for Unicode code points, use \u + 4-digit hex value)

Boolean

boolean a = true;

Objects

Read more about Objects.

Reference Types

They are used to access objects, which are addresses of the objects in memory (4 or 8 bytes). It can refer to any object of declared/compatible type.

In Java, classes and various type of array variables are reference type.

Special References

this

Implicit reference to current object. This is optional to use in class.

null

Represents an uncreated object. Sometimes, we just declare it and create after. Null Exception is a common error, to avoid that using initialization.

Type Conversion

Implicit Type Conversion

Conversion automatically performed by the compiler.

int a = 50;
long b = a;

Implicit widening conversions are automatically done:

  • Mixed integer sizes: use largest integer
  • Mixed floating point sizes: use double
  • Mixed integer and floating point: use largest floating point

Compiler cannot automatically do narrowing conversions \rightarrow explicit by developers.

Explicit Type Conversion

Conversion performed explicitly in code with cast operator.

long b = 50;
int a = (int) b;

Consider with explicit conversions:

  • Narrowing: significant bits may be discarded
  • Floating point \rightarrow integer: fractional portion may be discarded
  • Integer \rightarrow floating point: precision may be lost (10000 may be 9999,9999)

Time and Date

  • Time of events: primarily interested in sequencing and timestamp.
  • Human-friendly time: date and/or time of day.
  • Global human-friendly time: date and time of day, understands time zone.

Instant

Instant nowInstant = Instant.now();
Instant otherInstant

otherInstant.compareTo(nowInstant) // > < = 0

LocalTime

09:15:10.000000

LocalDate

2023-12-3

LocalDateTime

ZonedDateTime

DateTimeFormatter

LocalDate today = LocalDate.now();  // 2023-03-30

DateTimeFormatter usDateFormat = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String output = today.format(usDateFormat); // 03-30-2023

Enumeration Types

A type with a finite list of valid values.

Enums support equality tests:

  • == and !=
  • switch statement
public enum FlightCrewJob {
FLIGHT_ATTENDANT, // all upper case
COPILOT,
PILOT
}

FlightCrewJob job1 = FlightCrewJob.PILOT;
FlightCrewJob job2 = FlightCrewJob.COPILOT;
job1 != job2

switch(job) {
case FLIGHT_ATTENDANT:
// statement
break;
}

It can be declared in a class and access through ClassName.EnumName.EnumValue.

Relative Comparisons

The values are not just simple a list, they are ordered:

  • first value is lowest
  • last value is highest
  • use compareTo

Enum Methods

MethodDescription
valuesReturns an array contain all values
valueOfReturns the value that corresponds to a string (case sensitive)

Enum Types as Classes

Enum types can be treated as classes:

  • each value is an instance of the enum type:
public enum FlightCrewJob {
FLIGHT_ATTENDANT,
COPILOT,
PILOT; // semicolon before adding members
private String title;
public String getTitle() { return title; }
private FlightCrewJob(String title) {
this.title = title;
System.out.println("count");
}
}

It means FLIGHT_ATTENDANT, COPILOT and PILOT are instances of FlightCrewJob. Therefore, we can leverage the enum type's constructor:

public enum FlightCrewJob {
FLIGHT_ATTENDANT("Flight Attendant"),
COPILOT("First Officer"),
PILOT("Captain");
private String title;
public String getTitle() { return title; }
private FlightCrewJob(String title) {
this.title = title;
System.out.println("count");
}
}
  • declaring the value creates the instance:
public static void main(String[] args){
System.out.println(FlightCrewJob.COPILOT.getTitle());
System.out.println(FlightCrewJob.PILOT.getTitle());
}

> count
> count
> count
> First Officer
> Captain

Note that, enum declaration can be done outside a Class or inside a Class but not inside a Method.

Records

Some classes serve only as data carriers (data-only classes/data-transport objects):

  • initialized with required data values
  • those values never change \rightarrow involves a lot of boilerplate code.

record come to rescue:

public class Person {
private String name;
private int age;
// constructor
public Person(String name, int age) { this.name = name; this.age = age; }
// getters
public String getName() { return name; }
public int getAge() { return age; }
// common methods
public boolean equals(Object o) { }
public int hashCode() { }
public String toString() { }
}

public record Person(String name, int age) { }

// constructor
Person bob = new Person("Bob", 2);
// getters
String name = bob.name();
int age = bob.age();
// common methods
bob.equals(alice);

Collections

They are collections of similar data elements stored at contiguous memory locations.

They are different from primitives type, since they are references. See more at Collections.