• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exercise 9-2 K&B SCJP 5

 
Paul Stat
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello folks,

Just practicing away and I came across this exercise where you have to Synchronize on a StringBuffer object that initialised with a value of "A". You then have to print that out 100 times on a line, then increment the value. We're supposed to create 3 instances of this thread and start them one after the other so when main is run it should print out 3 lines, one with A's, one with B's and one with C's.

It asks us to use the StringBuffer object so that we don't have to create a new object as StringBuffers are mutable. It also says to increment the value of the StringBuffer to check the methods available to us in Chapter 6.

Now I've managed to do the exercise, but not in exactly the way they are describing, see below



Ok so I got the desired result, but I'm not satisfied that I haven't been able to acheive it in the way K&B describes! Any hints?
 
Ankit Garg
Sheriff
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
did you see that there is a setCharAt method in the StringBuffer class ...
 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I gave it a shot. I made sb static so after running this:




I got the output desired:


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic