Posts
60
Comments
36
Trackbacks
18
Java Variable Declaration

When declaring variables in Java, there are certain pointers you will want to remember.  It may be natural to declare same type variables on the same line.  This is not proper programming technique as it decreases readability.  So what are Java variables?  Variables are a type or instance of an Object in Java.  For the easiest examples we can use int, String, char, double, etc as examples.  So here is how we do it:
Declaring an integer in Java (int):

int i;

Which is the same as:

int i = 0;

Breaking this down, the "int" means that this variable is an integer (a number without decimal). "i" is the variable name.  When using this variable later, we will refer to it as "i".  The default value is 0 for all integers which means you do not have to declare this (optional).  The "= 0" is the initial value of "i".  Again, if you want the default value, leaving off "=0" is acceptable for Integers.  Generally this rule is not appropriate with double, String or char.

Declaring a double in Java (double):

double x = 0.0;

Note that if you do not declare an initial value, doubles act more like integers.  If that is the intended behavior, an integer should be used.

Declaring a String in Java (String):

String text = "";

String text = new String(); //Produces the same result as above

This declares the initial string as a blank string. Please note that you can not use this variable until you have made it something other than a null object, so the '=""' would be the absolute minimum for a Java String value.

Notice the similarity between the second in this line

String and ObjectName (later in the post).  String is an Object in Java, a collection of chars.

Declaring a char in Java (char):

char letter = 'a';

If you are having issues declaring characters in Java, please note the single tics around the character in the reference.  Characters in Java do not use double quotes,  so watch out for this.

Declaring other Objects in Java (Objects):

ObjectName obj = new ObjectName();

I will go into this in a later post as well, but this is a basic object instance.  The new ObjectName() is calling the default cunstructor, i.e. public ObjectName() {...}.

For today, we have gone over variable declaration in minor form.  I see this error often while teaching introduction courses and feel that this may help some of those with issues surrounding the basics of declaring basic variables in Java.

Technorati Tags:
posted on Tuesday, December 30, 2008 12:11 PM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 8 and 8 and type the answer here:
News
My Developer Notebook! This also happens to be my opinion place. Thanks for coming by.