This is a mirror of official site: http://jasper-net.blogspot.com/

Immutable Law of Java #20: The new Keyword

| Sunday, March 6, 2011
im•mu•ta•ble [him-moo-tribble]
   – an adjective: not mutable; unchangeable; changeless.

If you’re learning Java, it’s important to know some of the immutable rules of the language. I’m going to discuss about a dozen of them in a series of articles, with the first one being discussed today: immutable rule #20. You may be wondering why are we starting at rule #20? You’ll have to wait for immutable rule #37 to find that out, so be patient.

So here’s the first immutable rule of Java, also known as immutable rule #20:

In Java, all objects are created using the keyword new, except for the objects that are created without using the keyword new.

You know, when you create an instance of an object, you need to do something like this:

Byte me = new Byte(1); or Long johns = new Long(2);

So, whenever you create an instance of an object in Java, you always use the keyword new; always; every time...except that is, for the times when you don’t.

Stringing us along.

One of those times you don't need to use the keyword new is with String objects. String objects don’t need to be created with the keyword new. You can create a String like this:

String bean = “lima”;

Of course, Strings really sit on the fence with regards to this issue, as you can use the keyword new to create them if you really want. So, you could actually do this:

String lima = new String(“Peru”);

Of course, you shouldn’t do that, unless of course, you think you should (another immutable rule, I guess). It has something to do with the String pool or something. If you use the keyword new when creating a String, that instance gets its own, unique, special memory location, even if there are a hundred other Strings that use the exact same set of characters in their composition. If you don’t use the keyword new, two Strings that are the same, such as “Peru” and “Peru” will end up sharing the same memory location. It’s a great optimization to slap two Strings that are the same into the same chunk of memory, especially if you’re using plenty of String objects in your application.

Posted via email from Jasper-net

0 comments: