Java Record Constructor and Final Field Assignment Issue

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
uditorflatt
Posts: 1
Joined: Tue Dec 03, 2024 6:16 am
Contact:

Java Record Constructor and Final Field Assignment Issue

Post by uditorflatt »

Hi everyone,

I’m working with Java records, and I’m having a bit of trouble understanding how to handle the assignment of a final field in a constructor. Here’s the code I’m working with:

java
Copy code
public record Book(int id, String title)subway surferssubway surfers are a game for all ages{

public Book { //1
id = id + 1;
}

public Book(int id, String title) { //2
this.id = id;
}

}
My question is:
Would the code still compile if I remove the second constructor (line 2)?
I understand that id is a final field, and therefore it cannot be reassigned. Given that, would the constructor at line 1 (id = id + 1) cause any issues, or would the compiler not allow it?
Thanks in advance for your help! I’d really appreciate any insights or explanations on how this works.

admin
Site Admin
Posts: 10464
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Java Record Constructor and Final Field Assignment Issue

Post by admin »

What happened when you tried it out?
The id at //1 is not the same as record component id.
Please go through the Records chapter of
Deshmukh's OCP Java 17 21 Fundamentals
. It explains this in detail.

lisamartin
Posts: 4
Joined: Wed Dec 11, 2024 10:59 pm
Contact:

Re: Java Record Constructor and Final Field Assignment Issue

Post by lisamartin »

Great question! If you remove the second constructor, the first one will indeed cause a compilation error. In Java records, the fields are implicitly final, which means they cannot be reassigned after initial assignment. When you try to do id = id + 1 dummies world cup; in the canonical constructor, it would lead to an attempt to reassign a final field, resulting in a compilation error.
To modify the value of id, you would need to handle it in the second constructor or use a different approach. Hope that helps clarify things!

Post Reply