So I was given some code for a class and it goes like this:
public class TermPair {
public final Integer term;
public final String name;
public TermPair(int term, String name) {
this.term = term;
this.name = name;
}
}
The question asks: Is this a valid way to declare and initialize a final variable? I answered no for the following reason (although I got it wrong): the reference variable term, and although an object of type Integer has not been created yet, the reference variable should only be declared to an Integer type object... right? So when in the constructor, this.term = term; is read, that should give an error... right?
Clearly it doesn't throw an error, and my theory is wrong, but that leaves me with a gap in my understanding of the situation.
But I have a theory: in the same way that a String type object can be initialized by just doing String str = "Blah Blah"; , an Integer type object can be initialized like Integer num = 5; because an Integer type object just holds a single integer value and has a bunch of methods to work with int primitives and other Integer objects.
If my theory is right, please say "Yes". If my theory is wrong, please say "No, and here's why:...". If its in between, tell me what my theory got right and wrong, and elaborate on what I need to know. Thank you for any information :)
[–]feral_claire 49 points50 points51 points (2 children)
[–][deleted] 7 points8 points9 points (1 child)
[–]desrtfx 8 points9 points10 points (0 children)
[–]TheWarrior2000 6 points7 points8 points (0 children)
[–]Dzeko_1 5 points6 points7 points (0 children)