Start learning free

LESSON 260 OF 671 · RECORDS, SORTING & BUILT-INS

Records in Java

Lesson

TL ; DR:

A record is a tiny class that only holds values, like a movie's title and year. One line declares it. You read each value by its name.


record Movie(String title, int year) {}   // outside Solution

Movie film = new Movie("Frozen", 2013);

System.out.println(film.title());         // Frozen

System.out.println(film.year());          // 2013

System.out.println(film);                 // Movie[title=Frozen, year=2013]


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. Java keeps values like these in a record.

  • record Movie(String title, int year) {} declares a record. Its values go in the parentheses, each with its type.
  • A record is a class, so it goes outside Solution. Java writes its constructor and methods for you.
  • new Movie("Frozen", 2013) makes one. The values go in the declared order.
  • film.title() reads the title, and film.year() the year. Don't forget the parentheses.

Java can't unpack a record in one line. Copy each value you need into a variable, like String title = film.title().

A method can return only one value. To return two, it returns a record that holds both.

A record can't be changed. Its values are fixed when it's made. To change one, make a new record, like new Movie("Frozen", 2014).

Printing a record shows all its values, like Movie[title=Frozen, year=2013].


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, declare a record Time that holds two ints, hours and mins.

Then make splitTime return a new Time: the whole hours and the minutes left.

Last, call splitTime(135). Keep its result in a Time named walk.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check