Saturday, 15th October 2011
Follow WikiJava on twitter now. @Wikijava

Variables made easy

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


The very first introduction to the Java variables. Simplest as should be.

Contents

the article

We could write the following simple code:

public class Interest1 { 
 
    public static void main (String[] args) {
 
        System.out.print("Interest after a year is:");
        System.out.println( 1234 * 0.025 );
    }
}

but no one could spot the meaning of that "magic numbers" 1234 and 0.025. A common way to improve the comprehension of the source is using the variables:

public class Interest2 { 
 
    public static void main (String[] args) {
 
        double interest;
        double capital;
        double tax = 0.025;
 
        capital = 1234;
        interest = capital * tax;
 
        System.out.print("Interest after a year is:");
        System.out.println(interest);
    }
}

'interest', 'capital' and 'tax' are all variables of type 'double'.

The Java syntax about variables:

<type> <name>;  // simple declaration
<type> <name1>, <name2>, ...;  // multiple declaration
 
// declaration with initialization
<type> <name> = <expression>;
<type> <name1> = <exp1>, <name2> = <exp2>, ...;

<type> could be a primitive type, a classe, an array type, ...

A primitive type could be:

  • byte: integers between -128 and 127 (8 bit)
  • short: integers between -32768 and 32767 (16 bit)
  • int: integers between -2147483648 and 2147483647 (32 bit)
  • long: integers (64 bit)
  • float: floating point numbers (32 bit)
  • double: floating point numbers (64 bit)
  • char: characters (UNICODE standard, 16 bit)
  • boolean: just two values: true or false


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

syntaxes to avoid

I'd like to point that the syntaxes:

<type> <name1>, <name2>, ...; 
<type> <name1> = <exp1>, <name2> = <exp2>, ...;

for defining multiple variables with a single command, should not be used because they make the code less legible. One variable per line is always to prefer.

Interesting though, thanks for sharing,

--DonGiulio 04:54, 21 June 2008 (PDT)


Comments on wikijava are disabled now, cause excessive spam.