0

I'm new to Java and working on a existing, big project. A couple times, I came across code like this: variable = (CustomClass) "string";. Now, I really can't figure out why you would do that and how it is different from variable = new CustomClass("string");. The CustomClass has a constructor with one string argument.
In some situations, the above code just won't work which is why I came across it. But first, I want to understand what it does and Google doesn't seem to help. Or it is very possible I just don't know yet how to phrase the question accurately 😅

2
  • The code you came across appears to be trying to cast a string literal to CustomClass. This is suspicious to me, because String is a final class, can't be extended, and so I doubt that this class could be used to cast a string. Commented Aug 21, 2018 at 11:20
  • 1
    You can't cast String to CustomClass and still have the code compile. Commented Aug 21, 2018 at 11:23

1 Answer 1

1

variable = (CustomClass) another_variable_reference;

Above line of code will tell JVM that another_variable_reference is-a class type of variable reference class, here CustomClass. So assign the reference to which another_variable_reference it is pointing to reference variable

variable = new CustomClass(another_variable_reference);

Above will create a new Object of CustomClass and assign the object reference to the variable

Hence, in the first case, we create a new reference which point's to an existing object while in second, we create a new Object and assign it's reference to variable

Sign up to request clarification or add additional context in comments.

1 Comment

Finally found my problem. another_variable_reference was actually jListCustomers.getSelectedValue(), which my GUI editor somehow changed to type JList<String>. Changing the type to JList solved it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.