Java Variables and Data Types

13:55:00

              
Variable Declaration Rules in Java
Variable is an identifier which holds data or another one variable is an identifier whose value can be changed at the execution time of program. Variable is an identifier which can be used to identify input data in a program.




You must declare all variables before they can be used. Following is the basic form of a variable declaration −
data type variable [ = value][, variable [ = value] ...] ;

Here data type is one of Java's data types and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c;         // Declares three ints, a, b, and c.
int a = 10, b = 10;  // Example of initialization
byte B = 22;         // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a';        // the char variable a iis initialized with value 'a'
This chapter will explain various variable types available in Java Language. There are three kinds of variables in Java −
  • Local variables
  • Instance variables
  • Class/Static variables
1. Local Variables
·        Local variables are declared in methods, constructors, or blocks.
·        Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
·        Access modifiers cannot be used for local variables.
·        Local variables are visible only within the declared method, constructor, or block.
·        Local variables are implemented at stack level internally.
·        There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.
public class Test {
   public void pupAge() {
      int age = 0;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
This will produce the following result −
Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the time of compilation.
public class Test {
   public void pupAge() {
      int age;
      age = age + 7;
      System.out.println("Puppy age is : " + age);
   }

   public static void main(String args[]) {
      Test test = new Test();
      test.pupAge();
   }
}
This will produce the following error while compiling it −
Output
Test.java:4:variable number might not have been initialized
age = age + 7;
         ^
1 error


2. Instance Variables
·        Instance variables are declared in a class, but outside a method, constructor or any block.
·        When a space is allocated for an object in the heap, a slot for each instance variable value is created.
·        Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
·        Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
·        Instance variables can be declared in class level before or after use.
·        Access modifiers can be given for instance variables.
·        The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
·        Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
·        Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Example
import java.io.*;
public class Employee {

   // this instance variable is visible for any child class.
   public String name;

   // salary  variable is visible in Employee class only.
   private double salary;

   // The name variable is assigned in the constructor.
   public Employee (String empName) {
      name = empName;
   }

   // The salary variable is assigned a value.
   public void setSalary(double empSal) {
      salary = empSal;
   }

   // This method prints the employee details.
   public void printEmp() {
      System.out.println("name  : " + name );
      System.out.println("salary :" + salary);
   }

   public static void main(String args[]) {
      Employee empOne = new Employee("Ransika");
      empOne.setSalary(1000);
      empOne.printEmp();
   }
}

This will produce the following result −
Output
name  : Ransika
salary :1000.0

3. Class/Static Variables
·        Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
·        There would only be one copy of each class variable per class, regardless of how many objects are created from it.
·        Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
·        Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
·        Static variables are created when the program starts and destroyed when the program stops.
·        Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
·        Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
·        Static variables can be accessed by calling with the class nameClassName.VariableName.
·        When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
Example
import java.io.*;
public class Employee {

   // salary  variable is a private static variable
   private static double salary;

   // DEPARTMENT is a constant
   public static final String DEPARTMENT = "Development ";

   public static void main(String args[]) {
      salary = 1000;
      System.out.println(DEPARTMENT + "average salary:" + salary);
   }
}
This will produce the following result −
Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT


Java Data Types: 



Data Type in Java
Data type is a special keyword used to allocate sufficient memory space for the each data, in other words Data type is used for representing the data in main memory (RAM) of the computer.
In general every programming language is containing three categories of data types. They are
·         Fundamental or primitive data types
·         Derived data types

·         User defined data types.


Primitive data types
Primitive data types are those whose variables allows us to store only one value but they never allows us to store multiple values of same type. This is a data type whose variable can hold maximum one value at a time.

Example:

int a;  // valid
a=10// valid
a=10, 20, 30// invalid

Here "a" store only one value at a time because it is primitive type variable.
Derived data types
Derived data types are those whose variables allow us to store multiple values of same type. But they never allows to store multiple values of different types. These are the data type whose variable can hold more than one value of similar type. In general derived data type can be achieve using array.

Example

int  a[] = {10,20,30};  // valid
int b[] = {100, 'A', "ABC"};   //  invalid
Here derived data type store only same type of data at a time not store integer, character and string at same time.
User defined data types
User defined data types are those which are developed by programmers by making use of appropriate features of the language.
User defined data types related variables allows us to store multiple values either of same type or different type or both. This is a data type whose variable can hold more than one value of dissimilar type, in java it is achieved using class concept.
Note: In java both derived and user defined data type combined name as reference data type.
In C language, user defined data types can be developed by using struct, union, enum etc. In java programming user defined datatype can be developed by using the features of classes and interfaces.
Example

Student  s = new  Student();
In java we have eight data type which are organized in four groups. They are
·         Integer category data types
·         Character category data types
·         Float category data types
·         Boolean category data types
Integer category data types
These category data types are used for storing integer data in the main memory of computer by allocating sufficient amount of memory space.
Integer category data types are divided into four types which are given in following table
Data Type
Size
Range
1
Byte
1
+ 127 to -128
2
Short
2
+ 32767 to -32768
3
Int
4
+ x to - (x+1)
4
Long
8
+ y to - (y+1)
Character category data types
A character is an identifier which is enclosed within single quotes. In java to represent character data, we use a data type called char. This data type takes two byte since it follows Unicode character set.

Data Type
Size(Byte)
Range
Char
2
232767 to -32768
Why Java take 2 byte of memory for store character ?
Java support more than 18 international languages so java take 2 byte for characters, because for 18 international language 1 byte of memory is not sufficient for storing all characters and symbols present in 18 languages. Java supports Unicode but c support ascii code. In ascii code only English language are present, so for storing all English latter and symbols 1 byte is sufficient. Unicode character set is one which contains all the characters which are available in 18 international languages and it contains 65536 characters
Float category data types
Float category data type are used for representing float values. This category contains two data types, they are in the given table

Data Type
Size
Range
Number of decimal places
Float
4
+2147483647 to -2147483648
8
Double
8
+ 9.223*1018
16
Boolean category data types
Boolean category data type is used for representing or storing logical values is true or false. In java programming to represent Boolean values or logical values, we use a data type called Boolean.
Why Boolean data types take zero byte of memory ?
Boolean data type takes zero bytes of main memory space because Boolean data type of java implemented by Sun Micro System with a concept of flip - flop. A flip - flop is a general purpose register which stores one bit of information (one true and zero false).





Note: In C, C++ (Turbo) Boolean data type is not available for representing true false values but a true value can be treated as non-zero value and false values can be represented by zero
Data Type
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
0
1 byte
short
0
2 byte
int
0
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte



You Might Also Like

0 comments

Popular Posts

Like us on Facebook