Variables in Java

In Java, you must explicitly declare all variables before using them. This rule is in contrast to some languages — most notably Basic and Visual Basic — which let you use variables that haven’t been automatically declared.
Allowing you to use variables that you haven’t explicitly declared might seem like a good idea at first glance. But it’s a common source of bugs that result from misspelled variable names. Java requires that you explicitly declare variables so that if you misspell a variable name, the compiler can detect your mistake and display a compiler error.

The basic form of a variable declaration is this:
type name;
Here are some examples:
int x;
String lastName;
double radius;

In these examples, variables named x, lastName, and radius, are declared. The x variable holds integer values, the lastName variable holds String values, and the radius variable holds double values. int variables can hold whole numbers (like 5, 1,340, and -34), double variables can hold numbers with fractional parts (like 0.5, 99.97, or 3.1415), and String variables can hold text values (like “Hello, World!” or “Jason P. Finch”).
Notice that variable declarations end with a semicolon. That’s because the variable declaration is itself a type of statement.
In short, a variable name can be any combination of letters and numerals, but must start with a letter. Most programmers prefer to start variable names with lowercase letters, and capitalize the first letter of individual words within the name. For example, firstName and salesTaxRate are typical variable names.

Initializing Variables
In Java, local variables are not given initial default values. The compiler checks to make sure that you have assigned a value before you use a local variable.

Examples of Code
/*******************************************************
Name: HelloWorld.java
Output: Prints out "Hello, world!" to the console
Date: May 3, 2006

*******************************************************/

public class HelloWorld
{
public static void main(String [] args)
{
System.out.println("Hello, World!");
}
}


/*******************************************************

Name: PartsOfProgram.java
Output: Prints out result of adding two numbers.
Demonstrates different parts of a program.
Date: May 8, 2006

*******************************************************/

public class PartsOfProgram //Key words(public, class)
{
public static void main (String [] args)
{
int a,b,result; //Programmer-defined variables(a,b,result)
a = 10;
b = 5;
result = a + b; //Operators (+,=)
System.out.println("The result is : "+result); //Punctuation (;)
}
}

__________________________________________

No comments: