22 July 2010

A Note about variable declaration and initialization in C vs Java

Al Salamo Alaykom,

I want to talk today about variable declarations in Java vs C.

First in Java:

We have two types of variables, method local variables and class member variables.

Class member variables (either instance or class variables):
are automatically initialized to default values which are for reference types is null and for primitive types (int, short, byte, float, double, char) is 0 (for boolean is false).
Note that, static member variables are initialized once the class get loaded by the class loader.

method local variables:
local variables in java doesn't have the concept of being static, it is always automatic variables.
It is not initialized automatically, however you cannot use it before you do the initialization yourself.
example, the following code spinet will generate compile-time error:
public static char getCh() {
char ch;
return ch; // compile error: The local variable ch may not have been initialized
}


Second in C:
In C, we have two types of variables, Global variables and local variables.

Global variables:
Global variables are automatically initialized to default values, 0 for primitives, and NULL pointer for pointers.

local variables:
C has the concept of static local variables that automatically initialized to default values once the program get executed. it uses the same defaults as global variables.

for automatic local variables, it doesn't initialized automatically, but as opposite to java, it can be used without initialization, although it will hold garbage data! although, some compilers may generate warning messages.
Post a Comment