Seems obvious…

Posted on 31st August 2011

Easter is on its way!

Posted on 14th February 2011

My brother didn’t kill his meat rabbits and now he has more meat.

[Feb 14 2011] Update

Posted on 14th February 2011

Hey all,

I very much enjoy bringing you the tutorials I’ve been making an effort to write as of late. However life caught up to me as usual and I am a little swamped at the moment. For one I am finishing up a course of algorithm analysis which is hogging most of my time (or at least should be). Outside of the educational realm I’m trying to get re-integrated into the open source community. I was hoping to get involved with a Google Labs project but there is nothing that really piques my interest right now so I’ve been looking at getting involved with Mozilla again. Another thing that’s going on is a friend and I are in the process of starting our own little open source project that will remain secret for now (expect announcements in the future).

On the musical front I have a couple projects on the go also. The most active one being a project which I have been recruited as a session guitarist for. The second most active one right now would be my enrollment in a band (more to come on this later). And the third musical project is my writing project whereby I hope to create an album of just my own music for friends and family.

On top of all these things I am working about 50 hours a week right now because I’m currently in “transition” between being a chauffeur and working in development. I’ve been spending my weekends at my property logging a trail and using the wood from that process to build a corduroy road up another trail that is too wet to use in the summer. MY girlfriend and I are also going through the feasibility phase of moving to Toronto. This all depends on both of our abilities to get jobs relatively close to the core and whether we can find reasonable living accommodations whereby we’ll be happy but not burnt out of all our money to stop us from enjoying the other aspects of living in the big smoke. This is all while maintaining a 5-day-a-week workout regime and trying to be a good boyfriend and family member. Needless to say it’s been very hectic and I look forward to bringing more tutorials and fun stuff to you all soon.

Look at it this way, in the near future I’ll be bringing you all some new programming tutorials, music tracks, maybe videos, and definitely some info on the open source stuff I’m getting into. I’d like to find a way to do some guitar and music tutorials also but it’s just a matter of finding a way to do that effectively at the moment.

You’ll hear back from me soon!

What’s in the fridge?

Posted on 2nd February 2011

As I hope some of you have noticed the more I write these tutorials the more I try to make them fun for us all. So today I’ve prepared a fun little web services tutorial to show off some super basic web service stuff using JAX-WS (Java API for XML – Web Services). As usual let’s not blubber on with the lead up lets get right into it!


Here’s the plan: We’re going to design and code a web service that uses a singleton to store objects. The important things the web service will be able to do is add an object to it’s collection, take an object out of the collection, and get a list of the objects in the collection.

To address this I’ve come up with the idea of using a fridge as our collection. The fridge will store a number of items that are just Strings for the purpose of this tutorial. So here is the fridge web service interface.

FridgeWSI.java:

package wssample1;
 
import javax.jws.WebMethod;
import javax.jws.WebService;
 
@WebService
public interface FridgeWSI {
    @WebMethod String whatsInFridge();
    @WebMethod void putSomethingInFridge(Object o);
    @WebMethod Object takeSomethingOutOfFridge(Object o);
}

Now let’s implement the FridgeWSI interface.

FridgeWS.java:

package wssample1;
 
import javax.jws.WebService;
 
@WebService
public class FridgeWS implements FridgeWSI {
    private static FridgeWSI self;
    private static java.util.ArrayList<Object> fridge;
 
    private FridgeWS() {
        fridge = new java.util.ArrayList<Object>();
    }
 
    public static FridgeWSI getInstance() {
        if(self == null) {
            self = new FridgeWS();
        }
 
        return self;
    }
 
    @Override
    public String whatsInFridge() {
        String ret = "";
 
        if(!fridge.isEmpty()) {
            for(Object o: fridge) {
                ret += o.toString() + ", ";
            }
        } else {
            ret = "nothing";
        }
 
        return ret;
    }
 
    @Override
    public void putSomethingInFridge(Object o) {
        fridge.add(o);
    }
 
    @Override
    public Object takeSomethingOutOfFridge(Object o) {
        Object ret = null;
 
        if(fridge.indexOf(o) > -1) {
            ret = fridge.get(fridge.indexOf(o));
            fridge.remove(o);
        }
 
        return ret;
    }
}

So what do we do now that we have our web service functionality coded and ready to use? Well since it is a “web service” we’ll need to host it somehow. For the purpose of this tutorial we’re just going to do it locally with GlassFish on localhost:8080. You will set where you want this beast deployed in a main method. Once you run this main method it will keep running until you kill the process. So be mindful of this as you go through the next couple steps.

Note: Our FridgeWS is a Singleton meaning only one will ever exist as long as the following main process is running.

Main.java:

package wssample1;
 
import javax.xml.ws.Endpoint;
 
public class Main {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/WS/FridgeWS", FridgeWS.getInstance());
    }
}

Run this naow! We’ll need the WSDL (Web Services Description Language – Just an XML file that describes your web service) to be available for the next step. Before we get into the implementation of the consumer we’ll need to get the necessary stubs from our web service’s WSDL. There are a couple ways to go about this depending on the IDE you are using. You can do it the old school way using the wsimport command in your command line utility or you can use whatever facility your IDE has made available to you to make this process easier. Execute the following command in your project source directory to use wsimport:

wsimport -s . http://localhost:8080/WS/FridgeWS?wsdl

What this does is grab some method symbols and other fun stuff which allows the compiler (and your IDE) to understand what’s going on between your consumer code and the web service.

Moving on we need to consume our web service now. I’ve done this by writing a bridge class that will be my entry point, on the consumer side, to accessing the FridgeWS web service.

FridgeBridge.java:

package wsconsumerator;
 
public class FridgeBridge {
    private static FridgeBridge self;
 
    private FridgeBridge() {    }
 
    public static FridgeBridge getInstance() {
        if(self == null) {
            self = new FridgeBridge();
        }
 
        return self;
    }
 
    public String whatsInFridge() {
        wssample1.FridgeWSService service = new wssample1.FridgeWSService();
        wssample1.FridgeWS port = service.getFridgeWSPort();
        return port.whatsInFridge();
    }
 
    public void putSomethingInFridge(java.lang.Object arg0) {
        wssample1.FridgeWSService service = new wssample1.FridgeWSService();
        wssample1.FridgeWS port = service.getFridgeWSPort();
        port.putSomethingInFridge(arg0);
    }
 
    public Object takeSomethingOutOfFridge(java.lang.Object arg0) {
        wssample1.FridgeWSService service = new wssample1.FridgeWSService();
        wssample1.FridgeWS port = service.getFridgeWSPort();
        return port.takeSomethingOutOfFridge(arg0);
    }
}

As you can see accessing your web service is pretty simple now. We create an instance on the FrisgeWSService then we use that instance to get an instance of a FridgeWSPort. Using our instance of the FridgeWSPort we can call on our web methods.

Now finally after all of this coding we can try using our web service! Yay! I know it’s been a long wait but it will soon be worth it. The first thing we’re going to do is create a process that puts a bunch of items in the fridge for us. So let’s do that.

FridgePacker.java:

package wsconsumerator;
 
public class FridgePacker {
    public static void main(String[] args) {
        System.out.println("What's in the fridge? " + FridgeBridge.getInstance().whatsInFridge());
 
        System.out.println("Put a bazooka in the fridge.");
        FridgeBridge.getInstance().putSomethingInFridge("Bazooka");
 
        System.out.println("Put a cat in the fridge.");
        FridgeBridge.getInstance().putSomethingInFridge("Cat");
 
        System.out.println("Put a bandana ooka in the fridge.");
        FridgeBridge.getInstance().putSomethingInFridge("Bandana");
 
        System.out.println("Put black face paint in the fridge.");
        FridgeBridge.getInstance().putSomethingInFridge("Black face paint");
    }
}

The output:

What's in the fridge? nothing
Put a bazooka in the fridge.
Put a cat in the fridge.
Put a bandana ooka in the fridge.
Put black face paint in the fridge.

And now we can use a separate process (just to show that you can) to look in the fridge and see what’s there.

FridgeChecker.java:

package wsconsumerator;
 
public class FridgeChecker {
    public static void main(String[] args) {
        System.out.print("What's in the fridge? ");
 
        if(FridgeBridge.getInstance().whatsInFridge().equals("Bazooka, Cat, Bandana, Black face paint, ")) {
            System.out.print("COMMANDO KITTEH!");
        } else {
            System.out.print(FridgeBridge.getInstance().whatsInFridge());
        }
    }
}

And finally the output from our FridgeChecker:

What's in the fridge? COMMANDO KITTEH!

So we’ve not only successfully created a fridge web service that has persistence and behaves as a singleton, but we’ve successfully turned an ordinary household cat into a commando. But wait! That’s not all! We’ve also created one awesome magic fridge!

Well actually we just did the fridge and web service thing successfully and the commando cat and the magic fridge are actually just kind of a fun unit test I put in our FridgeChecker code. But it was fun! It was fun? Wasn’t it?

Anyways so now you have a very basic grasp on how to make a web service.

Go tinker!

Java 1.5.0 – Varargs

Posted on 1st February 2011

Here something interesting I just discovered in the 1.5.0 release of Java: varargs. Basically the ability send a variable number of arguments to a method. No longer must we define our methods to accept arrays!

Here’s a quick sample I put together to demonstrate the concept:


Main.java:

public class Main {
    public static void main(String[] args) {
        System.out.println("countArgs(5, 1, 2, 3, 4, 5) -" +
                (countArgs(5, 1, 2, 3, 4, 5) ? "passed" : "failed"));
    }
 
    public static boolean countArgs(int numArgs, Object... args) {
        int numCounted = 0;
 
        for(Object o: args) {
            ++numCounted;
        }
 
        return numCounted == numArgs;
    }
}

Above is our main method which makes a call to a method countArgs() which accepts a variable number of Object type arguments. The countArgs() method then counts the number of arguments received and compares them against the first argument which is a number we sent to the method to tell it how many arguments we sent. The output is as follows:

countArgs(5, 1, 2, 3, 4, 5) -passed

You’ll notice that varargs are denoted by the following syntax:

Object... varName

Now go, be free, make use of this awesome new language feature!

Also, if you want more information on Java 1.5.0 features head over to the Oracle J2SE 1.5.0 New Features and Enhancements Site.

I concur — concurrency craves a curator

Posted on 1st February 2011

Over the past day or so I’ve been doing some tinkering with multi-threading. I created a situation where there is a static list of integers that I want a group of threads to eat away at together. The problem is that I want each integer eating thread to eat only its fair share of the available ints.

I started with my StaticListContainer class which is the static class holding my list of integers. It provides all the required methods to be a singleton and two additional methods related to the necessary operations for the integer eaters to eat the numbers: a pop() method which returns the current int and a isEmpty() method which returns whether the list is empty or not. Here is the StaticListContainer class.

StaticListContainer.java:

public class StaticListContainer {
    private static StaticListContainer self;
    private static int[] list;
    private static volatile int pos;
 
    /*
     * Private constructor that creates a list of 10000 integers.
     */
    private StaticListContainer() {
        list = new int[10000];
 
        for(int i = 0; i &lt; 10000; i++) {
            list[i] = i;
        }
 
        /*
         * Since the array is 0-indexed we need to subtract 1 from the array.length data member.
         */
        pos = list.length - 1;
    }
 
    /*
     * Returns an instance of the StaticListContainer. If the StaticListContainer
     * has not yet been initialized then this method initializes it.
     */
    public static StaticListContainer getInstance() {
        if(self == null) {
            self = new StaticListContainer();
        }
 
        return self;
    }
 
    /*
     * Returns the current integer and decrements the current position by 1.
     */
    public synchronized int pop() {
        int ret = list[pos];
 
        pos -= 1;
 
        return ret;
    }
 
    /*
     * Returns true if the current position is below 0, signifying the list is empty,
     * otherwise returns false.
     */
    public synchronized boolean isEmpty() {
        return pos &lt; 0;
    }
}

Here is the IntEater thread.

IntEater.java:

public class IntEater extends Thread implements Runnable {
    private String threadName = "";
    private int fullness = 0;
 
    public IntEater(String threadName) {
        this.threadName = threadName;
    }
 
    @Override
    public void run() {
        do {
            // Pop the next integer and eat it
            this.eatInt(StaticListContainer.getInstance().pop());
            fullness++;
        } while (!StaticListContainer.getInstance().isEmpty());
 
        // Once all the numbers have been eaten -- display how full each thread is
        double fullperc = (fullness / 2500.0) * 100.0;
        System.out.println(threadName + " is " + fullperc + "% full after eating " + fullness + " ints.");
    }
 
    private void eatInt(int x) {
        System.out.println(threadName + " is eating " + x);
    }
}

For brevity sake I’m only going to put the summary of fullness and items eaten from the end of the ouput here:

Charlie is 119.83999999999999% full after eating 2996 ints.
Catehrine is eating 1372
Catehrine is 14.799999999999999% full after eating 370 ints.
Oswald is eating 234
Oswald is 213.0% full after eating 5325 ints.
Bingo is eating 1284
Bingo is 52.35999999999999% full after eating 1309 ints.

First thing that is noticeable about this output is that things are kind of wild and out of control. This is very reflective of nature as it is survival of the fittest; whoever eats the most survives and has no regard for the other IntEater’s around them. The second thing I notice here is that Catherine starved to death, Charlie is full, Bingo is still hungry, and Oswald is a glutton.

This group of IntEaters need to be controlled somehow. We need to control whose turn it is to eat the next int. In order to control this I created a class called a ThreadPool (I know EaterMediator would have been a way cooler name but I guess I was a little lame than I am now when I wrote this code). What ThreadPool does is keeps track of a group of threads and iterates through them cyclically using a next() method. It also provides a helper method called yielding() which forces a thread to yield if it is not that threads turn. If used correctly all threads will yield until the threads whose turn it is executes and calls the next() method.

ThreadPool.java:

public class ThreadPool {
    private static ThreadPool self;
    private static java.util.ArrayList
 threads;
    private int current;
 
    /*
     * Private constructor initializes the threads list.
     */
    private ThreadPool() {
        threads = new java.util.ArrayList
();
    }
 
    /*
     * Singleton getInstance() method.
     */
    public static ThreadPool getInstance() {
        if(self == null) {
            self = new ThreadPool();
        }
 
        return self;
    }
 
    /*
     * Tell the ThreadPool that the next thread may use the processor now.
     */
    public void next() {
        if(current == threads.size() - 1) {
            current = 0;
        } else {
            current += 1;
        }
    }
 
    /*
     * Add a thread to the pool.
     */
    public void addThread(Thread thread) {
        threads.add(thread);
    }
 
    /*
     * Start all the threads in this pool.
     */
    public void startThreads() {
        for(Thread t: threads) {
            t.start();
        }
    }
 
    /*
     * Force a thread to yield if it is not their turn to use the processor.
     */
    boolean yielding(Thread t) {
        boolean ret = false;
 
        if(threads.indexOf(t) != current) {
            t.yield();
            ret = true;
        }
 
        return ret;
    }
}

Making use of the ThreadPool our IntEater class should change to reflect the following:

IntEater.java:

...
public void run() {
        do {
            // If the current thread is not supposed to be yielding then do the work
            if(!ThreadPool.getInstance().yielding(this)) {
                //Pop the next integer and eat it
                this.eatInt(StaticListContainer.getInstance().pop());
                fullness++;
 
                /* Must call this method to tell the ThreadPool that it is the next
                 * threads turn to do it's work.
                 */
                ThreadPool.getInstance().next();
            }
        } while (!StaticListContainer.getInstance().isEmpty());
...

After the changes our output summary is as follows:

Charlie is 100.0% full after eating 2500 ints.
Catehrine is 100.0% full after eating 2500 ints.
Bingo is 100.0% full after eating 2500 ints.
Oswald is 100.0% full after eating 2500 ints.

Which indicates that each IntEater ate sufficiently what they required to be full and shared the list on ints equally.

Our main method looked like this the whole time because I was always using the ThreadPool but not using the flow control it provided for the first part of this tutorial. So now I permit you to finally read the main code.

Main.java:

public class Main {
    public static void main(String[] args) {
        StaticListContainer.getInstance();
 
        ThreadPool.getInstance();
        ThreadPool.getInstance().addThread(new IntEater("Charlie"));
        ThreadPool.getInstance().addThread(new IntEater("Catehrine"));
        ThreadPool.getInstance().addThread(new IntEater("Oswald"));
        ThreadPool.getInstance().addThread(new IntEater("Bingo"));
        ThreadPool.getInstance().startThreads();
    }
}

What’s next? Hmm I would be interested to see about extending the ThreadPool class to be a Thread itself which could then be used by itself to be a ThreadPool within a ThreadPool. By doing that we could make sure ThreadPools take turns using the processor equally. There would have to be a number of changes but it’s not unimaginable.

I hope this helps to bring to light some of the issues surrounding concurrency. I have a analogy for how the JVM controls multi-threading which I find helpful: picture a lineup of people waiting to read a piece of paper inside a key-locked safe. A key drops from the sky and the first person to grab it opens the safe and reads the paper. That person then closes the safe and throws the key in the air above the crowd. Everybody jumps to try and grab the key and only the person who does can access the safe. The person who catches the key might even be the same person who threw it. There is no control over the process. Now in relation to threading. Each person in the crowd is a thread waiting to access a synchronized resource. The safe is the synchronized resource and the key is the window/semaphore. Multi-threading is a pretty chaotic process which sometimes needs to be tightly controlled depending on your application. What I’ve done above is give you one such way to control it.

Don’t forget: 5 to 10 ints and vegetables a day!

I can haz ceiling friend?

Posted on 28th January 2011

See Ceiling Cat.

What I’m reading

Posted on 28th January 2011


PubSub fun fun

Posted on 27th January 2011

Here’s a concept: Your developing a piece of code that needs to let objects subscribe to the actions of another object but you need to keep it all nice and tidy and decoupled as possible.


To the left is a simple class diagram demonstrating a one possible design for such a problem. We have a Subscriber object which must be extended by objects who want to subscribe to a Publisher object. The Publisher object must be extended by objects who want to publish information to a series of subscribers. We use a feed object to monitor and control the interaction between the two. Although I’ve put association lines in the diagram between the Feed and the two other objects there is actually no concrete relationship and the two objects Subscriber and Publisher are completely decoupled.

Ler’s hop to it. Here’s our Publisher class.

Publisher.java:

public abstract class Publisher {
    public final void send(String message) {
        Feed.getInstance().send(message);
    }
}

Pretty simple stuff right. We have to declare it abstract because we want to control the declaration of the send() function. We also don’t want anybody to ever change how the send() function is declared so we declare it final.

Next we have the Subscriber class.

Subscriber.java:

public abstract class Subscriber {
    public final void subscribe(Subscriber s) {
        Feed.getInstance().subscribe(s);
    }
 
    public abstract void message(String msg);
}

Also very simple, we declare it abstract because we need to defer the implementation of the message() function and we want to control the implementation of the subscribe() function. We declare subscribe() final to stop future implementation from reimplementing how our subscribe() function.

The following is the code for the Feed class.

Feed.java:

public final class Feed {
    private static Feed self;
    private static java.util.ArrayList subs;
 
    private Feed() {
        subs = new java.util.ArrayList();
    }
 
    public static Feed getInstance() {
        if(self == null) {
            self = new Feed();
        }
 
        return self;
    }
 
    protected final void subscribe(Subscriber s) {
        subs.add(s);
    }
 
    protected final void send(String msg) {
        for(Subscriber s: subs) {
            s.message(msg);
        }
    }
}

This is an immutable class meaning it is as it is nobody can ever touch it this implementation. We declare it as a Singleton because we want it to behave as such by allowing our program to only ever have one instance of the Feed class. The class has three methods and a private constructor: getInstance() which is part of the Feed being a Singleton it provides a way to get an instance of the Feed by returning a reference to itself, subscribe() is called by Subscriber objects and puts the parameter Subscriber object into a list of subscribers, and finally the send() function which loops through all the Subscribers registered with the Feed object and calls their message() functions.


Please keep in mind this is a very very basic implementation. This implementation is literally only to send a String message to it’s subscribers. These classes could be designed to allow any type of object to be sent as in Event driven programming where the message in this example would instead be an event object of some type. We could also change the Feed to allow different type of Subscribers to subscribe to different types of Publishers all through the singleton feed. This concept is also very similar to the Observer design pattern which I might explain in a later post. I just wanted to post this for some interesting reading. Hope you enjoyed it!

Objects and Pointers: Pointer confusion

Posted on 27th January 2011

Here’s another little tutorial that most amateur developers need to take the time to read through. When it comes to objects and pointers in Java people seem to get confused without the explicit *’s and &’s that most C-based languages offer. New developers seem to often lose track of whats a pointer and whats a value when programming in Java and therefore end up with lot’s of unexplained behavior/bugs or exceptions in their code.

Below is a series of tests which demonstrates most (if not all) the scenarios where pointer confusion takes place. The following should at least solidify this basic concept for Java programmers to a degree of comfort that pointer confusion is no longer an issue. Enjoy:


Here is a class, Something, that is composed of another class, SomethingElse.

Something.java:

public class Something {
    private SomethingElse somethingelse;
 
    public SomethingElse getSomethingelse() {
        return somethingelse;
    }
 
    public void setSomethingelse(SomethingElse somethingelse) {
        this.somethingelse = somethingelse;
    }
 
    public void print() {
        somethingelse.print();
    }
}

Here is the SomethingElse class that Something is composed of:

SomethingElse.java:

class SomethingElse {
    public int n = 0;
 
    public void print() {
        System.out.println(n);
    }
}

Finally, here is the Main class which contains out main() method with all our tests. The tests purposes are identified in the comments:

Main.java:

public class Main {
    public static void main(String[] args) {
        SomethingElse a = new SomethingElse();
        SomethingElse b = new SomethingElse();
        SomethingElse c = new SomethingElse();
        a.n = 1;
        b.n = 2;
        c.n = 3;
 
        Something something = new Something();
        something.setSomethingelse(a);
 
        System.out.print("Value of something before any modifications to a: ");
        something.print();
 
        /*
         * Let's try assigning a new value to a in the Main class to see if it
         * affects the value held within the something object.
         */
        System.out.println("==Test 1==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a.n = 100;
 
        System.out.print("Value of a after modification: ");
        a.print();
 
        System.out.print("Value of something after first modification of a: ");
        something.print();
 
        /*
         * Let's try assigning the pointer in b to the pointer in a then changing b and printing out a.
         */
        System.out.println("==Test 2==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        b = a;
        b.n = 25;
 
        System.out.print("Value of a after modification of b: ");
        a.print();
 
        System.out.print("Value of something after first modification of b: ");
        something.print();
 
        /*
         * Let's try assigning the pointer in a to the pointer in c.
         */
        System.out.println("==Test 3==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a = c;
 
        System.out.print("Value of a after modification: ");
        a.print();
 
        System.out.print("Value of something after second modification of a: ");
        something.print();
 
        /*
         * Let's try setting the pointer in a to null.
         */
        System.out.println("==Test 4==");
        System.out.print("Value of a before modification: ");
        a.print();
 
        a = null;
 
        System.out.println("Attempting to print a after nullifying it's pointer will throw a NullPointerException so let's move on.");
 
        System.out.print("Value of something after third modification of a: ");
        something.print();
    }
}

Output:

Value of something before any modifications to a: 1
==Test 1==
Value of a before modification: 1
Value of a after modification: 100
Value of something after first modification of a: 100
==Test 2==
Value of a before modification: 100
Value of a after modification of b: 25
Value of something after first modification of b: 25
==Test 3==
Value of a before modification: 25
Value of a after modification: 3
Value of something after second modification of a: 25
==Test 4==
Value of a before modification: 3
Attempting to print a after nullifying it's pointer will throw a NullPointerException so let's move on.
Value of something after third modification of a: 25

So to explain what’s happening here.

In the first test we’re testing to see whether changing the value of a in the Main class will affect the value within something’s somethingelse class because it holds a pointer to the same memory space that a does. The test does change the value of a both within the Main class and the value of n within something’s somethingelse class.

In the second test were attempting to show how you can assign object pointers and alter the same memory space through different object pointers. We’re doing this by assigning b the same pointer held by a and then changing b and printing out the value of a which prints out the new value that we just assigned b. This happens because when we assign b the pointer held by a we have assigned both a and b to point to the same memory space. When we alter b we are altering the data in that memory space and when we go to look at it through a we are still looking at the same memory space we just altered with b. Get it? Got it? Good.

The third test is to show the opposite of test two where something’s somethingelse class holds a reference to the memory space held by Mains a object pointer but then we assign a the same pointer held by c thereby losing our pointer from a to the same memory location as something’s somethingelse class. This test is to show that assignment of objects with the ‘=’ operator only works on pointers so after we do this something’s somethingelse class doesn’t take on the value of c we just effectively eliminate our pointer through a to the same memory space held by something’s somethingelse class.

The last test is just to reinforce the same concept the previous three were trying to demonstrate. We eliminate the pointer held in a so if we try to access it the code would throw a NullPointerException in the Main class but something’s somethingelse class still holds the reference to the original memory space and the value printed remains the same.

I hope this demonstrates enough examples of object pointers to clear up some of the confusion. There are a number of other things I could have shown in this code but they would have been just as redundant as the fourth test in the code already provided.

Keep coding!

tags: ,