Variables


Variables

Both C and Java define a variety of data types. The types each language supports are shown in Table 3.1.

Some of the types supported by C are not supported by Java and vice versa. Java does not support signed or unsigned types. All Java integral types (including char ) are signed. Java does not use the long double or void type. Java does not support pointers, so there are no pointer or function pointer types in Java. The same can be said of struct and union types.

Java does provide some useful data types that are not provided by C. The boolean type has a true or false value. Using a boolean variable is more convenient than using 0 for false and 1 for true as in C. Java provides the byte type that represents a single byte of data. Because Java is object oriented, you can declare variables that are references to class instances (objects).

When a C variable is declared outside of any function definition it is a global variable and is available anywhere inside a C program. Java does not support global variables. A Java class variable is one that is declared outside of any method definitions and is available anywhere inside the class in which it is declared. Both C and Java support local variables. A local variable is declared inside a method, a for statement, or other block of code and exists only inside the block in which it is defined.

Table 3.1. C and Java Types

T YPE

C

J AVA

boolean

No

Yes

byte

No

Yes

char

Yes

Yes

signed char, unsigned char

Yes

No

short, int, long

Yes

Yes

unsigned short, unsigned int, unsigned long

Yes

No

float, double

Yes

Yes

long double

Yes

No

void

Yes

No

pointer, function pointer

Yes

No

struct, union

Yes

No

reference

No

Yes

In both languages, variables must be declared before they are used. Variable declaration statements in C must be placed before any other executable statements in the block of code in which the variable is defined. A Java variable can be declared anywhere in the program as long as it is declared before it is used. The syntax for declaring C or Java variables is the same: the type, the variable name , and a semicolon.

 type variable_name; 

The variable can be initialized when it is declared or later in the program. Java and C are similar in that variables only have scope inside the block of code in which they are declared. A C variable can be declared to be static or extern . Java variables can be declared to be static , final , public , private , protected , final , transient , and volatile



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net