Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within foundations
Search Coderanch
Advance search
Google search
Register / Login
Win a copy of
OCP Oracle Certified Professional Java SE 21 Developer Study Guide: Exam 1Z0-830
this week in the
Programmer Certification
forum!
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Tim Cooke
Liutauras Vilda
Jeanne Boyarsky
paul wheaton
Sheriffs:
Ron McLeod
Devaka Cooray
Henry Wong
Saloon Keepers:
Tim Holloway
Stephan van Hulst
Carey Brown
Tim Moores
Mikalai Zaikin
Bartenders:
Frits Walraven
Forum:
Java Foundations Exam
initialization of variables
Tiam Bezalel
Ranch Hand
Posts: 67
posted 1 year ago
Number of slices to send:
Optional 'thank-you' note:
Send
hi,
why do i have "nullB" as output? i was expecting "XB" as output. please explain.
class Message { String msg = "X"; //Line n1 Message() { Message(); //Line n2 } void Message() { //Line n3 System.out.println(msg += "A"); //Line n4 } } class MyMessage extends Message { String msg = "Y"; //Line n5 MyMessage() {} //Line n6 void Message() { //Line n7 System.out.println(msg += "B"); //Line n8 } } public class Test { public static void main(String[] args) { new MyMessage(); //Line n9 } }
thanks.
To conquer without peril, one ends up triumphing without glory
Stephan van Hulst
Saloon Keeper
Posts: 15731
368
posted 1 year ago
Number of slices to send:
Optional 'thank-you' note:
Send
This is the order of operations:
n9: new MyMessage(); n1: Message.msg = "X"; n2: Message(); n8: System.out.println(MyMessage.msg += "B"); n5: MyMessage.msg = "Y"; n6: Empty constructor body
For clarity, I qualified
msg
to clearly distinguish between
Message.msg
and
MyMessage.msg
, which are two different variables.
As you can see, Line
n8
is executed before line
n5
, meaning that before
"B"
is appended to
MyMessage.msg
, it still has its default value of
null
.
Danger, 10,000 volts, very electic .... tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Inheretance OCA 1Z0 -808
understanding the code
Polymorphism, Constructors and Methods
Depth first search recursive, problem on graph[picture + code]
More than a sorting with dupplicate elimination
More...