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: ,

Pass by what?

Posted on 27th January 2011

Here is a problem I hear over and over again from developer entering the Java realm. Many new developers have either never been introduced to the concept of pass-by-value/pass-by-reference or they just never understood what it meant. So I threw together some simple source code to demonstrate this basic concept that every developer of ANY language should know.


Here’s a simple object class that has only a string.

Something.java:

public class Something {
    String name;
}

Here are two objects, one to change the name attribute in the Something class, and one to change a primitive type, by simply changing an int to 1.

ObjectChanger.java:

public class ObjectChanger {
    public void changeSomething(Something s) {
        s.name = "changed";
    }
}

PrimitiveChanger.java:

public class PrimitiveChanger {
    public void change(int n) {
        n = 1;
    }
}

Now let’s look at the Main class which contains this projects main() function.

Main.java:

public class Main {
    public static void main(String[] args) {
        // Let's try changing an object type
        Something s = new Something();
        s.name = "unchanged";
 
        System.out.println("String before pass: " + s.name);
 
        ObjectChanger oc = new ObjectChanger();
        oc.changeSomething(s);
 
        System.out.println("String after pass: " + s.name);
 
        if(s.name.equals("unchanged")) {
            System.out.println("Objects are passed-by-value.");
        } else
            System.out.println("Objects are passed-by-reference.");
 
        // Now let's try changing a primitive type
        int n = 0;
 
        System.out.println(n);
 
        PrimitiveChanger pc = new PrimitiveChanger();
        pc.change(n);
 
        System.out.println(n);
 
        if(n == 0) {
            System.out.println("Primitives are passed-by-value.");
        } else
            System.out.println("Objects are passed-by-reference.");
    }
}

And finally the output:

String before pass: unchanged
String after pass: changed
Objects are passed-by-reference.
0
0
Primitives are passed-by-value.

As you can gather by reading through the code and output when an object is passed into a function it gets passed-by-reference meaning if that function changed that object within it’s logic then the original object will reflect those changes. A primitive type on the other hand is passed-by-value which means it basically gets a copy of the value to take away and do as it will with it. The called function can manipulate the passed in primitive value as much as it wants and the original value outside of the called function will remain the same as it was before it was passed to the function.

I hope this helps to clarify some of the misunderstanding surrounding this topic. This example does not take into account the overloading of the clone() function in your objects and then passing a reference to an objects clone rather than the original objects itself by using the obj.clone() syntax. Getting into the clone() function however deserves a whole other post.

Some things to look forward to

Posted on 9th January 2011

A long long time ago in a sub domain not so far away a couple friends and I ran a blog called WAFN. On this blog we explored a very big range of topics. The mistake we made however was trying to provide news even though we were not really plugged into that universe. After a recent conversation with a couple of other friends about starting a podcast we took a look at our old blog. After trying every credential set I could remember I was able to log into the admin page and we found that we still get an enormous amount of hits on that website. So there is talk about reviving WAFN perhaps under a different name but getting a similar group of people together to revive it.

The second project in talk is about the podcast our friends want to start which we might be involved with. As more news comes I’ll make sure to share but as it stands for now it is still in the planning stages. So stay tuned!

Why I’m glad I learned JQuery…

Posted on 10th November 2010

JQuery LogoAs some people may know I’ve been getting heavily into JavaScript as of late. Particularly the  AJAX aspects of the language and now the JQuery JavaScript library. Throughout school I always kind of hated JavaScript for it’s unstructured “dirtiness” (as I would say) as I am a prophet of OO development and long time Java devotee. Although I disliked the look of the language I was never ignorant to the benefits of client side programming. After I graduated I found that because of my dislike for the language I had ignored opportunities to learn it and use it so I was particularly weak with the language and unaware of it’s advanced potential.

So here I am today making up lost ground learning JavaScript, AJAX, and JQuery. After looking at some of my other options for JavaScript libraries and a wiki page comparing a number of them I am very happy that I am making the effort to learn JQuery out of the many options available. I’ve looked pretty deeply into Script.aculo.us, JQuery (obviously), Google Web Toolkit, and Dojo. What I’ve found is that JQuery, on top of having the most features and support for different things while remaining astonishingly small in file size, provides the most simplistic coding options, and seems to take heed of the non-intrusive client-side programming virtue that I outlined in a previous blog. I should point out that Scipt.acoul.us does have very good API documentation though.

Needless to say I am coming around to JavaScript and even starting to understand the beautiful potential in the ability to do things in code that I would have at one point thought to be “dirty”. It must be that little spark of a Perl developer in me that has matured and let me come to terms with a scripting style that uses dirty trick but still feels clean to me.

Cats are cute

Posted on 7th November 2010

I can haz window sibling?!

6 things you can do to be a better driver and by extension a better person

Posted on 5th November 2010

Since 99% of drivers seem uninformed here is a list of things you can do to be a safer driver:

  1. Keep to the right.
  2. Pay attention to the lights.
  3. Do your checks.
  4. Signal.
  5. Don’t pass on the right. It’s dangerous.
  6. Don’t follow too closely.

Only six things to remember and apply people. Why is it so difficult for the vast majority?

20 steps to being a better developer and by extension a better person

Posted on 3rd November 2010

Okay so I’m going to share this now because as time goes on I find myself faced with sloppier and more careless developers and it is really starting to upset me. Programming by nature is a pretty damn easy specialty to get into and be relatively successful at with only amateur experience or knowledge. As a programmer, if your too lazy to adhere to a code of constant learning, quality, and ethics then you just suck by nature. So following is my list of things that develops should do/use/learn:

  1. Format your code. I don’t care whether you like K&R, Allman, or One True Brace just pick a style and be consistent with it.
  2. Use a directory structure that makes sense.
  3. Write comments. (If your doing Java then use Javadoc)
  4. Gather requirements and stick to the design documents. Which leads me to my next point…
  5. Test your code. If you don’t know how to test then it’s about time you learned. Believe it or not there is more than unit testing when it comes to good software production and good design documents will determine the tests that need to be run.
  6. Be considerate of the blind, deaf, stupid (not mentally challenged… just plain stupid people), or mobile browsing people. In other words, develop with accessibility in mind. It’s not hard so stop being a douche and do it.
  7. W3C has validation tools for a reason. Use them.
  8. Use non-obtrusive client-side programming. In fact, be modular about everything you do.
  9. Use namespaces, or packages, or whatever the hell your favourite programming language calls them.
  10. Learn to use OOP effectively. Learn what design patterns are and use them.
  11. Compress your code files before moving them into production.
  12. Remember that thing I said about design patterns? Well there is one called MVC it’s particularly important.
  13. Write documentation.
  14. Use a revisioning system.
  15. PL/SQL… learn it. If your requesting large data-sets from a database you best be using it.
  16. Learn about security and have your sites tested for penetration points. If you have any data or portion of your websites which need to be protected then they should damn well be protected. Doing anything else will only continue to give web applications (and software developers by  proxy) a bad wrap.
  17. Asynchronous request objects are not the icing… they are part of the cake.
  18. Algorithm design is important. Math sucks but you have to learn it sooner or later if you want to process large sets of data efficiently.
  19. Test cross-browser functionality. Test cross-OS functionality.
  20. Learn what’s happening at the bit level.

Basically it’s not our job as software developers to be arrogant douche bags. Developers who don’t adhere to the code of constant learning, quality, and ethics need to wipe their ass with the back of their head while their down there and come to reality. We’re artists of technology, engineering, and by extension the future. Artists of the nature of mankind as we are the shapers of how our people interact and will interact with the single greatest power next to our own creative drive that we’ve ever uncovered: technology.

P. s. I don’t care if you think this post was boring. It had to be said.

P. p. s. It was hard to limit this list to 20. Expect another list.

Ces’t l’halloween!

Posted on 31st October 2010

It’s halloween! My most favourite holiday of all! Where the night is all about mischief and fun and that’s been accepted. As nice as Christmas is, along with most other holidays, to focus on time with family ecetera it’s nice to have one evening dedicated to good old plain fun. Have a fun and mischievous Halloween everybody!

Episode 5: Return of the Antoine Dodson

Posted on 29th October 2010

Umm yeah Antoine Dodson is a celebrity because some awesome dudes on the internet took his interview and turned it into a super catchy song. It’s funny how the internet works like that. Most people don’t even consider the fact that it’s the dude who made the song who deserve to be famous because they are obviously highly talented and skilled music creators. Anyways see the video below where Antoine Dodson is apparently now a salesman for an app to track sex offenders.

Thanks to my friend imthinking for pointing me to this one.

Pornkins… Interesting.

Posted on 28th October 2010

Well a friend of mine shared a link to these on Facebook today. They are called Pornkins. Don’t know what to say about them except to laugh silently to myself.

Note: I tried to post a video but Vimeo’s embedding abilities suck. So follow the link above and watch the promo on the Pornkins website.