Variables in Java

The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a variable

In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java’s atomic types, or the name of a class or interface. (Class and interface types are discussed later in Part I of this book.) The identifier is the name of the variable. You can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable. To declare more than one variable of the specified type, use a comma-separated list.

Here are several examples of variable declarations of various types. Note that some
include an initialization.



int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing // d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.




Dynamic Initialization of Variable

Although the preceding examples have used only constants as initializers, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

For example, here is a short program that computes the length of the hypotenuse of a right triangle given the lengths of its two opposing sides:



// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}


Here, three local variables—a, b,and c—are declared. The first two, a and b, are initialized by constants. However, c is initialized dynamically to the length of the hypotenuse (using the Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ), which is a member of the Math class, to compute the square root of its argument. The key point here is that the initialization expression may use any element valid at the time of the initialization, including calls to methods, other variables, or literals.














Rules that must be followed when naming variables or errors will be generated and your program will not work:



  • No spaces in variable names

  • No special symbols in variable names

  • Variable names can only contain letters, numbers, and the underscore ( _ ) symbol

  • Variable names can not start with numbers, only letters or the underscore ( _ ) symbol (but variable names can contain numbers)


The Scope and Lifetime of Variables

However, Java allows variables to be declared within any block. As explained above, a block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a new block, you are creating a new scope. As you probably know from your previous programming experience, a scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects. Most other computer languages define two general categories of scopes: global
and local. However, these traditional scopes do not fit well with Java’s strict, objectoriented
model. While it is possible to create what amounts to being a global scope, it is by far the exception, not the rule. In Java, the two major scopes are those defined by a class and those defined by a method. Even this distinction is somewhat artificial. However, since the class scope has several unique properties and attributes that do not apply to the scope defined by a method, this distinction makes some sense. The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method’s scope.As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation. Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:


// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}


As the comments indicate, the variable x is declared at the start of main( )’s scope and is accessible to all subsequent code within main( ). Within the if block, y is declared.Since a block defines a scope, y is only visible to other code within its block. This is why outside of its block, the line y = 100; is commented out. If you remove the leading comment symbol, a compile-time error will occur, because y is not visible outside of its block. Within the if block, x can be used because code within a block (that is, a nested scope) has access to variables declared by an enclosing scope. Within a block, variables can be declared at any point, but are valid only after they are declared. Thus, if you define a variable at the start of a method, it is available to all of the code within that method. Conversely, if you declare a variable at the end of a block, it is effectively useless, because no code will have access to it. For example, this fragment is invalid because count cannot be used prior to its declaration:



// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared!
int count;


variables are created when their
scope is entered, and destroyed when their scope is left. This means that a variable
will not hold its value once it has gone out of scope. Therefore, variables declared
within a method will not hold their values between calls to that method. Also, a
variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each time the block in which it is declared is entered



// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) { int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100; System.out.println("y is now: " + y); } } }


The output generated by this program is shown here:


variable-scope-in-java

As you can see, y is always reinitialized to –1 each time the inner for loop is
entered. Even though it is subsequently assigned the value 100, this value is lost.
One last point: Although blocks can be nested, you cannot declare a variable to have
the same name as one in an outer scope. In this regard, Java differs from C and C++.
Here is an example that tries to declare two separate variables with the same name. In Java, this is illegal.


// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Creating First Hello World Application In JAVA

In case of each programming languages like c,c++,php etc we all begin by writing hello world program.So lets begin by writing a hello world program in java.Here i will explain the steps required to write a "Hello World" program in java.



  • Then double click on the eclipse shortcut and now you will get a screen of eclipse editor window opened.On the left side of the editor you can view the project explorer.From the project explore right click and then click add a new project shown below
Create-a-project-halloworld
  • Then you will get a new window where we need to mention the name of the new java project.Once you fill the project name click finish button to create the sample project as shown below
Create-a-javaproject-halloworld
naming-the-project-in-java

  • Now a sample folder structure is formed named Hello world.Now there is a file named helloworld.java.Right click on that file and add new class to it as shown in figure
  • Then you will be navigated to a window to specify the name of the class which you are goin to create as below
naming-the-class-for-java
  • Once you mention the class name click finish to create that class.Also you can specify whether class is private,public or protected.Click on the helloworld.Java and view the code.You can see the class you create and add system.out.println("HelloWorld"); to it and save as below.Now we need to run this as a java application.right click on the project and click"Run as a java application" as shown below.
  • Now you will get an output like this as below.
console-output-halloworld

  • So this is our first java program printing hello world.Be happy cheers!!!!!!!!!!!!!!.if you like my article please put comments.

Installing JDK For Eclipse

  • Check the www.oracle.com site to get the link to download jdk as in screencast below
Downloading-jdk-from-eclipse.com
  • Click the button to download jdk as in the screen cast

  • In the next step select the operating system for which you wanted to install.read the agreement and click on the continue button as below
select-os-for-jdkSelected-os-for-jdk

  • Then download begins and save to a location in your hard disc as below
save-the-jdk-to-a-location
  • After the download click the setup file to install jdk
click-the-setup-file-to-install-jdk
  • Then there appears a screen to change the installation directory.This is not mandatory(if you wanted to change you can do it as below)

changing-the-directory-if-needed
  • Then click the finish button.this completed the installation.now we need to verify the installation

  • Just open up a command prompt and move to installation directory and type cd bin and check for java version by giving version-v as below.If the version is shown correctly there is no doubt that its installed perfectly
check-for-installation-of-sdk

  • Also take the command prompt and check for whether the java compiler is installed at the proper path by giving javac command as below
Installation-aborted

  • This is because of missing of some of the settings.That means jdk installation path provided in the advanced system settings is wrong .Inorder to make it working properly just go to location C:\Program Files.
sdk-installation-path-verification
  • In that location there should be a folder named java and inside that java folder there should be a file with jdk version as below(If its not there the installation is a failure one.)

JDK-folder-should-be-present
  • Then go and click jdk folder and go inside the bin folder and rightclick on any of the exe files inside the bin folder and check for properties as shown below
righclick-on-the-any-of-files-in-bin
  • This is where you should tell your java to look for your compiler.So Copy that path as shown below.

Copy-the-jdk-path
  • Then Right click on My Computer and click on properties and then click on Advanced system settings as shown below
Advanced system settings in properties

  • Under Advanced system settings there is a section called environmental variables.Over there create a new variable called path and give the value as jdk path ie where jdk is(copied minits back)
Create-environmental-variable-called-path

  • Then save the settings.
Environmental variable save
  • Now go to command prompt and type javac you will get the result as shown below
Check-for-installation-of-jdk

Installing Eclipse on Windows Linux and mac

  • First Step is go to url www.eclipse.org and check for the for downloading eclipse

  • Then click on the download link as shown in figure.



Installing-Eclipse-on-Windows-Linux-and-mac
  • Once the save dialogue box is opened click the save button to save the zipped file version of eclipse into your hard drive.
Save-the-zipped-eclipse-file


  • Then extract the zip files and save into location C:\Program Files as shown in figure below

  • Once it is extracted we can see a folder directory called eclipse in your computer as below
Extract-the-eclipse-setup-files
  • Then in that folder heirarchy you can see an eclipse.exe file .Create a shortcut of that in your desktop and double click on that icon you can see eclipse opened in a new window
Eclipse-installation-step
  • This pops up with a window which asking me to set up a path where my java projects will be stored.So i put that in MyDocuments/eclipse.ie my workspace
  • saving-the-eclipse-program-pathFor testing purpose create a small project called test and inside that test create a class called


Create-a-new-project-for-testing

For testing purpose create a small project called test and inside that test create a class called test.from the folder hierarchy in eclipse i double click on the test.java file and the code fragment is as below.

Code-view-in-eclipse

To that add System.out.println("testing"); .if the project undergo proper debugging we will get testing in the console.
Console-output-tocheck-eclipse-installation
So finally have a happy programming.If you like my article please post comments.

Template by - Mathew | Mux99