Showing posts with label java constructors. Show all posts
Showing posts with label java constructors. Show all posts

Tuesday, January 25, 2011

Chapter 12: Constructors and Instantiation

Objects are constructed. You can’t make a new object without invoking a constructor. In fact, you can’t make a new object without invoking not just the constructor of the object’s actual class type, but also the constructor of each of its superclasses including the Object class itself! Constructors are the code that runs whenever you use the keyword new. To be a bit more accurate, there can also be initialization blocks that run when you say new (init blocks), but we’re going to cover them, and their static initialization counterparts, in the next chapter.
We already have a lot to discuss here. So let’s get started.

Constructor Basics

Every class, including abstract classes, MUST have a constructor. Hard Code that into your brain. But just because a class must have one, doesn’t mean the programmer has to type it. A constructor looks like this:

class Car {
Car() { } // The constructor for the Car class
}

You notice anything missing in the declaration above? There’s no return type! Two key points to remember about constructors are that they have no return type and their names must exactly match the class name. Typically, constructors are used to initialize instance variable state, as follows:

class Car {
int size;
String name;
Car(String name, int size) {
this.name = name;
this.size = size;
}
}

In the preceding code example, the Car class does not have a no-arg constructor. That means the following will fail to compile:
Car f = new Car(); // Won't compile, no matching constructor

but the following will compile:

Car f = new Car("Ford", 43); // No problem. Arguments match
// the Car constructor.

So it’s very common for a class to have a no-arg constructor, regardless of how many other overloaded constructors are in the class (constructors can be overloaded just like methods). You can’t always make that work for your classes; occasionally you have a class where it makes no sense to create an instance without supplying information to the constructor. A java.awt.Color object, for example, can’t be created by calling a no-arg constructor, because that would be like saying to the JVM, “Make me a new Color object, and I really don’t care what color it is....” Do you seriously want the JVM making your color choices?

Constructor Chaining

We know that constructors are invoked at runtime when you say new on some class type as follows:
Lamborghini h = new Lamborghini();

But what really happens when you say new Lamborghini() ? (Assume Lamborghini extends Car and Car extends Object.)

1. Lamborghini constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(),
2. Car constructor is invoked (Car is the superclass of Lamborghini).
3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Car extends Object even though you don’t actually type “extends Object” into the Car class declaration. It’s implicit.) At this point we’re on the top of the hierarchy.
4. Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the variables are declared, like “int x = 27”, where “27” is the explicit value (as opposed to the default value) of the instance variable.
5. Object constructor completes.
6. Car instance variables are given their explicit values (if any).
7. Car constructor completes.
8. Lamborghini instance variables are given their explicit values (if any).
9. Lamborghini constructor completes.

Rules for Constructors

The following list summarizes the rules you’ll need to know about Constructors. There are very important and you MUST remember these to answer the questions related to Constructors in the SCJP Exam.

• Constructors can use any access modifier, including private. (We will deal with private constructors in one of the later chapters)
• The constructor name must match the name of the class. (100% Case Sensitive)
• Constructors must not have a return type.
• It’s legal (but probably stupid) to have a method with the same name as the class, but that doesn’t make it a constructor. If you see a return type, it’s a method and not a constructor. In fact, you could have both a method and a constructor with the same name—the name of the class—in the same class, and that’s not a problem for Java. Be careful not to mistake a method for a constructor—be sure to look for a return type.
• If you don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.
• The default constructor is ALWAYS a no-arg constructor. (Obviously the compiler has no clue what all arguments you might want for your class. So it takes the safe way out with a no argument constructor)
• If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code, the compiler won’t provide the no-arg constructor (or any other constructor) for you. In other words, if you’ve typed in a constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself!
• Every constructor has, as its first statement, either a call to an overloaded constructor “this()” or a call to the superclass constructor “super()”. (You cant do both in the same constructor)
• If you do type in a constructor, and you do not type in the call to super() or a call to this(), the compiler will insert a no-arg call to super() for you, as the very first statement in the constructor.
• A call to super() can be either a no-arg call or can include arguments passed to the super constructor. (The compiler will not insert the super with arguments call by itself. You have to do it manually)
• A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although the default constructor is always a no-arg constructor. The default constructor is the one the compiler provides! While the default constructor is always a no-arg constructor, you’re free to put in your own no-arg constructor.
• You cannot make a call to an instance method, or access an instance variable, until after the super constructor runs.
• Only static variables and methods can be accessed as part of the call to super() or this(). (Example: super(Car.NAME) is OK, because NAME is declared as a static variable.)
• Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.
• Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
• The only way a constructor can be invoked is from within another constructor. In other words, you can’t write code that actually calls a constructor explicitly as follows:

class Lamborghini {
Lamborghini() { } // constructor
void doStuff() {
Lamborghini(); // calling the constructor - illegal!
}
}

Determine Whether a Default Constructor Will Be Created

The following example shows a Lamborghini class with two constructors:
class Lamborghini {
Lamborghini() { }
Lamborghini(String name) { }
}

Will the compiler put in a default constructor for the class above? “No!” What about for the following variation of the class?
class Lamborghini {
Lamborghini(String name) { }
}

Now will the compiler insert a default constructor? “No Again!” What about this class?
class Lamborghini { }

Now we’re talking. The compiler will generate a default constructor for the preceding class, because the class doesn’t have any constructors defined. OK, what about this one below?
class Lamborghini {
void Lamborghini() { }
}

You might be tempted to say that, the compiler won’t create one, since there already is a constructor in the Lamborghini class? Take another look at the Lamborghini class.
What’s wrong with the Lamborghini() constructor? It isn’t a constructor at all! It’s simply a method that happens to have the same name as the class. Remember, the return type is a dead straight way to tell us that we’re looking at a method, and not a constructor. So, here again the compiler will put the default no-arg constructor in the class.

Some Questions:

Q: How do you know for sure whether a default constructor will be created?
A: Because you didn’t write any constructors in your class.

Q: How do you know what the default constructor will look like?
A: Because...
• The default constructor has the same access modifier as the class.
• The default constructor has no arguments.
• The default constructor includes a no-arg call to the super constructor (super()).

What happens if the super constructor has arguments?

Constructors can have arguments just as methods can, and if you try to invoke a method that takes, say, an int, but you don’t pass anything to the method, the compiler will complain.
So if your super constructor (that is, the constructor of your immediate superclass/parent) has arguments, you must type in the call to super(), supplying the appropriate arguments. Crucial point: if your superclass does not have a no-arg constructor, you must type a constructor in your class (the subclass) because you need a place to put in the call to super with the appropriate arguments.
The following is an example of the problem:
class Car {
Car(String name) { }
}

class Lamborghini extends Car {
Lamborghini() {
super(); // Problem!
}
}

And once again the compiler treats us with the stunningly lucid:
Lamborghini.java:7: cannot resolve symbol
symbol : constructor Car ()
location: class Car
super(); // Problem!
^

If you’re lucky (and it’s a full moon), your compiler might be a little more explicit. But again, the problem is that there just isn’t a match for what we’re trying to invoke with super()—an Car constructor with no arguments.
Another way to put this is that if your superclass does not have a no-arg constructor, then in your subclass you will not be able to use the default constructor supplied by the compiler. It’s that simple. Because the compiler can only put in a call to a no-arg super(), you won’t even be able to compile something like this:

class Dress {
Dress(String s) { }
}
class Skirt extends Dress { }

Trying to compile this code gives us exactly the same error we got when we put a constructor in the subclass with a call to the no-arg version of super():

Dress.java:4: cannot resolve symbol
symbol : constructor Dress ()
location: class Dress
class Skirt extends Dress { }
^

In fact, the preceding Dress and Skirt code is implicitly the same as the following code, where we’ve supplied a constructor for Skirt that’s identical to the default constructor supplied by the compiler:

class Dress {
Dress(String s) { }
}
class Skirt extends Dress {
// Constructor identical to compiler-supplied
// default constructor
Skirt() {
super(); // Won't work!
} // Invokes a no-arg Dress() constructor,
} // but there isn't one!

One last point on the whole default constructor thing, constructors are never inherited. They aren’t methods. They can’t be overridden (because they aren’t methods and only instance methods can be overridden). So the type of constructor(s) your superclass has in no way determines the type of default constructor you’ll get. Some folks mistakenly believe that the default constructor somehow matches the super constructor, either by the arguments the default constructor will have (remember, the default constructor is always a no-arg), or by the arguments used in the compiler-supplied call to super().

So, although constructors can’t be overridden, you’ve already seen that they can be overloaded, and typically are.

Overloaded Constructors

Overloading a constructor means typing in multiple versions of the constructor, each having a different argument list, like the following examples:

class Car {
Car() { }
Car(String s) { }
}

The preceding Car class has two overloaded constructors, one that takes a string, and one with no arguments. Because there’s no code in the no-arg version, it’s actually identical to the default constructor the compiler supplies, but remember—since there’s already a constructor in this class (the one that takes a string), the compiler won’t supply a default constructor. If you want a no-arg constructor to overload the with-args version you already have, you’re going to have to type it yourself, just as in the Car example.

Overloading a constructor is typically used to provide alternate ways for clients to instantiate objects of your class. For example, if a client knows the Car name, they can pass that to a Car constructor that takes a string. But if they don’t know the name, the client can call the no-arg constructor and that constructor can supply a default name. Here’s what it looks like:

1. public class Car {
2. String name;
3. Car(String name) {
4. this.name = name;
5. }
6.
7. Car() {
8. this(makeRandomName());
9. }
10.
11. static String makeRandomName() {
12. int x = (int) (Math.random() * 5);
13. String name = new String[] {"Ferrari", "Lamborghini",
"Rover", "Spyker",
"Lotus"}[x];
14. return name;
15. }
16.
17. public static void main (String [] args) {
18. Car a = new Car();
19. System.out.println(a.name);
20. Car b = new Car("Proton");
21. System.out.println(b.name);
22. }
23. }

Running the code four times produces this output:

% java Car
Lotus
Proton

% java Car
Ferrari
Proton

% java Car
Rover
Proton

% java Car
Ferrari
Proton

There’s a lot going on in the preceding code. Figure 2-7 shows the call stack for constructor invocations when a constructor is overloaded. Take a look at the call stack, and then let’s walk through the code straight from the top.

• Line 2 Declare a String instance variable name.
• Lines 3–5 Constructor that takes a String, and assigns it to instance variable name.
• Line 7. Assume every Car needs a name, but the client (calling code) might not always know what the name should be, so you’ll assign a random name. The no-arg constructor generates a name by invoking the makeRandomName() method.
• Line 8 The no-arg constructor invokes its own overloaded constructor that takes a String, in effect calling it the same way it would be called if client code were doing a new to instantiate an object, passing it a String for the name. The overloaded invocation uses the keyword this, but uses it as though it were a method name, this(). So line 8 is simply calling the constructor on line 3, passing it a randomly selected String rather than a client-code chosen name.
• Line 11 Notice that the makeRandomName() method is marked static! That’s because you cannot invoke an instance (in other words, nonstatic) method (or access an instance variable) until after the super constructor has run. And since the super constructor will be invoked from the constructor on line 3, rather than from the one on line 7, line 8 can use only a static method to generate the name. If we wanted all Cars not specifically named by the caller to have the same default name, say, “Ford,” then line 8 could have read this("Ford"); rather than calling a method that returns a string with the randomly chosen name.
• Line 12 This doesn’t have anything to do with constructors, but since we’re all here to learn...it generates a random integer between 0 and 4.
• Line 13 We’re creating a new String object (just a single String instance), but we want the string to be selected randomly from a list. Except we don’t have the list, so we need to make it. So in that one line of code we

1. Declare a String variable, name.
2. Create a String array (anonymously—we don’t assign the array itself to anything).
3. Retrieve the string at index [x] (x being the random number generated on line 12) of the newly created String array.
4. Assign the string retrieved from the array to the declared instance variable name. We could have made it much easier to read if we’d just written
5. String[] nameList = {"Ferrari", "Lamborghini", "Rover", "Spyker","Lotus"};
6. String name = nameList[x];
• Line 18 We’re invoking the no-arg version of the constructor (causing a random name from the list to be passed to the other constructor).
• Line 20 We’re invoking the overloaded constructor that takes a string representing the name.

The key point to get from this code example is in line 8. Rather than calling super(), we’re calling this(), and this() always means a call to another constructor in the same class. OK, fine, but what happens after the call to this()? Sooner or later the super() constructor gets called, right? Yes indeed. A call to this() just means you’re delaying the inevitable. Some constructor, somewhere, must make the call to super().

Key Rule: The first line in a constructor must be a call to super() or a call to this().
No exceptions. If you have neither of those calls in your constructor, the compiler will insert the no-arg call to super(). In other words, if constructor A() has a call to this(), the compiler knows that constructor A() will not be the one to invoke super().

The preceding rule means a constructor can never have both a call to super() and a call to this(). Because each of those calls must be the first statement in a constructor, you can’t legally use both in the same constructor. That also means the compiler will not put a call to super() in any constructor that has a call to this().

Thought question: What do you think will happen if you try to compile the following code?
class A {
A() {
this("Car");
}
A(String s) {
this();
}
}

Your compiler may not actually catch the problem (it varies depending on your compiler, but most won’t catch the problem). It assumes you know what you’re doing. Can you spot the flaw? Given that a super constructor must always be called, where would the call to super() go? Remember, the compiler won’t put in a default constructor if you’ve already got one or more constructors in your class. And when the compiler doesn’t put in a default constructor, it still inserts a call to super() in any constructor that doesn’t explicitly have a call to the super constructor—unless, that is, the constructor already has a call to this(). So in the preceding code, where can super() go? The only two constructors in the class both have calls to this(), and in fact you’ll get exactly what you’d get if you typed the following method code:

public void go() {
doStuff();
}

public void doStuff() {
go();
}

Now can you see the problem? Of course you can. The stack explodes! Two overloaded constructors both calling this() are two constructors calling each other. Over and over and over, resulting in

% java A
Exception in thread "main" java.lang.StackOverflowError

The benefit of having overloaded constructors is that you offer flexible ways to instantiate objects from your class. The benefit of having one constructor invoke another overloaded constructor is to avoid code duplication. In the Car example, there wasn’t any code other than setting the name, but imagine if after line 4 there was still more work to be done in the constructor. By putting all the other constructor work in just one constructor, and then having the other constructors invoke it, you don’t have to write and maintain multiple versions of that other important constructor code. Basically, each of the other not-the-real-one overloaded constructors will call another overloaded constructor, passing it whatever data it needs (data the client code didn’t supply).

Constructors and instantiation become even more exciting (just when you thought this chapter is going to end), when you get to inner classes, but I know you can stand to have only so much fun in one chapter, so I am holding the rest of the discussion on instantiating inner classes until a later point in time (A Future Chapter)

Previous Chapter: Chapter 11 - Legal Return Types

Next Chapter: Chapter 13 - Statics

Saturday, January 1, 2011

Chapter 2: Declarations

Classes and Interfaces are the basis based on which the java programming universe revolves. Everything in Java is an object but an object is nothing but the runtime orientation of a class. In other words, an object is nothing but a class that is being executed.

Whenever you write any java code, it implicitly means that you are writing classes or interfaces. Within those classes, as you know, are variables and methods (plus a few other things). How you declare your classes, methods, and variables dramatically affects your code’s behavior

Source File Declaration Rules:

Before we dig into class declarations, let’s do a quick review of the rules associated with declaring classes, import statements, and package statements in a source file:
• There can be only one public class per source file.
• Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
• If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Rock { } must be in a source code file named Rock.java.
• If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
• If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn’t a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
• import and package statements apply to all classes within a source code file. In other words, there’s no way to declare multiple classes in a file and have them in different packages, or use different imports.
• A file can have more than one nonpublic class.
• Files with no public classes can have a name that does not match any of the classes in the file.

Now that we have taken a look at the rules for declaring a java source code file, let us get into the real thing about declaring classes.

Declaring Classes:

A Class can be declared with the following statement:

public class AnandsFirstclass {}

Irrespective of the fact that this class does not have any code, this piece of code when saved in a file called AnandsFirstclass.java compiles just fine. Here public is an access modifier (we will see access modifiers in greater detail in one of the subsequent chapters), class is the keyword that is used to specify that a class is being declared and AnandsFirstclass is the name of the class we are creating.

There are many different types of classes that you can create. Some of which are:
1. Final Classes – A class that cannot be inherited (Dont worry about inheritance just yet. We will look into it in full detail in one of the later chapters)
2. Normal Classes – The type of class that we declared a few lines back
3. Abstract Classes – A class that is similar to a normal class but that does not provide full functional behaviour by itself. It has to be subclassed/inherited in order to be used.

Abstract Classes in Detail:
An Abstract class is a special kind of class that cannot be instantiated. It has one or more methods which are not implemented in the class. These methods are declared abstract and they do not contain any code inside them.

Ex:
abstract class Parent {
public abstract String getSon();
public abstract String getDaughter();
....
....
//More methods that contain specific behaviour/code in them
}

The above is an abstract class “Parent” that has a lot of functionality but it has declared two abstract methods which have no code inside them. Any class that has one or more abstract methods has to be abstract. This abstract class cannot be instantiated.

i.e., the below piece of code will not work. The code will not even compile.

Parent object = new Parent();

Purpose of Abstract Classes:
Abstract classes are generally used where you want an amount of behaviour to be used by the class that extends the abstract class while at the same time giving options to the child class to provide a certain amount of behaviour itself.

A Child Class extending the Abstract Class:

public class Child extends Parent {
public String getSon() {
return “Sons Name”;
}

public String getDaughter(){
return “Daughters Name”;
}
...
... //Code specific to the Child class
}

Declaring Interfaces:

When you create an interface, you’re defining a contract for what a class can do, without saying anything about how the class will do it. Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic.

Ex: You can create an interface Drivable which in effect means that it has the feature of being driven. Any class that implements this Drivable interface must provide an implementation of the drive() method can be driven. But how it will be driven is up to the classes to provide the implementation. Both a car and a bus can be driven but the how part is different. So the classes Car and Bus will implement this interface and provide their specific behavior about being driven.

Tip: An Interface is an 100% Abstract class

Comparison between an Abstract Class and an Interface:

While an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods. Another way interfaces differ from abstract classes is that interfaces have very little flexibility in how the methods and variables defined in the interface are declared. These rules are strict:

• All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract. (You can use any kind of modifiers in the Abstract class)
• All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables.
• Interface methods must not be static.
• Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
• An interface can extend one or more other interfaces.
• An interface cannot extend anything but another interface.
• An interface cannot implement another interface or class.
• An interface must be declared with the keyword interface.

You must remember that all interface methods are public and abstract regardless of what you see in the interface definition.

Look out for questions where interface methods are declared with any combination of public, abstract, or no modifiers. For example, the following five method declarations, if declared within their own interfaces, are legal and identical!

void bbb();
public void bbb();
abstract void bbb();
public abstract void bbb();
abstract public void bbb();

whereas the below declarations wont compile:

The following interface method declarations won’t compile:
final void bbb(); // final and abstract can never be used
// together, and abstract is implied
static void bbb(); // interfaces define instance methods
private void bbb(); // interface methods are always public
protected void bbb(); // (same as above)

Declaring Variables in an Interface

We are allowed to declare variables in an interface. By default these variables would be constants because they would static and final. By placing the constants right in the interface, any class that implements the interface has direct access to the constants, just as if the class had inherited them.

You need to remember one key rule for interface constants. They must always be
public static final

Since the variables declared in an interface are by default public static and final, we need not mention them explicitly. But it is a good practice to do so to ensure that even novice programmers can understand the code you write.

Constructor Declarations:

In Java, objects are constructed. Every time you make a new object, at least one constructor is invoked. Every class has a constructor, although if you don’t create one explicitly, the compiler will build one for you.

Ex:
class Test {
public Test() { } // this is Test’s constructor

public void Test() { } // this is a badly named,
// but legal, method
}

If you see the example above, you would have realized that the constructor looks a lot like methods. Below are the main distinguishing factors between the constructor and normal methods:
1. The Constructor’s name is exactly the same as the name of the class
2. They do not have a return type (Please remember this. A Constructor cannot have a return type as part of the code)
3. Constructors cannot be static, abstract or final

Declaring Variables:

There are two types of variables in Java:
Primitives - A primitive variable can be one of eight types: char, boolean, byte, short, int, long, double, or float. Once a primitive has been declared, its primitive type can never change, although in most cases its value can change.
Reference variables - A reference variable is used to refer to (or access) an object. A reference variable is declared to be of a specific type and that type can never be changed.

We should remember that each of the primitive datatype has a particular range and by assigning values that are bigger than the size it can take would result in errors or loss of value and precision. Below are the data ranges of the primitive datatypes:

Primitive Data Type Ranges in Java
Data Type Bits Used Minimum Value Maximum Value
byte 8 -27 27 - 1
short 16 -215 215 -1
int 32 -231 231 -1
long 64 -263 263 -1
float 32 n/a n/a
double 64 n/a n/a
The range for these floating point numbers is difficult to determine and it is not required from the exam perspective as well. Booleans and char type variables do not have a range. Booleans can be either true or false and chars can be only one character in size Ex: “A” or “B” etc

Declaring Reference Variables:

Reference variables can be declared as static variables, instance variables, method parameters, or local variables. You can declare one or more reference variables, of the same type, in a single line

Variables can be declared in multiple places inside a class which determines what type of variable gets created. They are:

Instance Variables

Instance variables are defined inside the class, but outside of any method, and are only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object.

Ex:
public class Test {
private String name = “Anand”;
private String country = “India”;
}

Here name and country are two instance variables where they would be a part of an object of the class Test. Since each variable is part of the class’s instance (object), they are called instance variables.
For the exam, you need to know that instance variables
• Can use any of the four access levels (which means they can be marked with any of the three access modifiers)
• Can be final
• Can be transient
• Cannot be abstract
• Cannot be synchronized
• Cannot be strictfp
• Cannot be native
• Cannot be static, because then they’d become class variables.

Static Variables or Class Variables:

The static modifier is used to create variables and methods that will exist independently of any instances created for the class. All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.

Things you can mark as static:
• Methods
• Variables
• A class nested within another class, but not within a method (more on this in Chapter 8).
• Initialization blocks

Things you can’t mark as static:
• Constructors (makes no sense; a constructor is used only to create instances)
• Classes (unless they are nested)
• Interfaces
• Method local inner classes
• Inner class methods and instance variables
• Local variables

Method Parameters:

These are variables that are declared as part of a methods declaration. These are arguments that will be used as part of the method.

Ex: public int add(int a, int b) {
return a + b;
}

Here a and be are the method parameters.

Local Variables:

These are variables that are declared inside a method and are used for processing inside the method.

Ex: public int add(int a, int b) {
private int c = 10;
return a + b + c;
}

Here c is the local variable.

Declaring Arrays:

In Java, arrays are objects that store multiple variables of the same type, or variables that are all subclasses of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.

The main thing you need to know about arrays in the exam perspective is how to create an array and how to assign values to the array elements.

Tip: Arrays are very useful and efficient but java has other utility classes like ArrayList or Vector that might be much better in performance than arrays. These collections give us easier access to its objects and also provide utility methods that might help us process these objects


Declaring an Array of Primitives

int[] keys; // Square brackets before name (recommended)
int keys []; // Square brackets after name (legal but less
// readable)

Declaring an Array of Object References

Thread[] processes; // Recommended
Thread processes []; // Legal but less readable

We can also declare multidimensional arrays, which are in fact arrays of arrays. This can be done in the following manner:

String[][] employeeNames;
String[] employeeNames[];

Above we have a 2 dimensional array which can be thought of as an array of arrays. Notice in the second example we have one square bracket before the variable name and one after. This is perfectly legal to the compiler, proving once again that just because it’s legal doesn’t mean it’s right.

Note: We will deal with assigning values to the array in a separate chapter.


Hope this chapter on Declarations was useful. I have intentionally left of declaration of Enumerations as part of this chapter because enums need to be taken up as a separate chapter because of the amount of details involved in enumerations.

Previous Chapter: Chapter 1 - Refreshing Java

Next Chapter: Chapter 3 - Declaring Enumerations (Enums)
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers