YuWebdesign



Variables and Datatypes in Java

By YuwebDesign

  1. Variables are containers for storing data values.
  2. A variable is the name given to a memory location. It is
    the basic unit of storage in a program.
  3. The value stored in a variable can be changed during
    program execution. int x = 10; myObj.x = 25;
  4. If you don’t want the ability to override existing
    values, declare the attribute as final. Useful
    when you want a variable to always store the same value, like PI
    (3.14159…). The final keyword is called a “modifier”. final
    int x = 10; myObj.x = 25; // will generate an error: cannot
    assign a value to a final variable
  5. class attributes are variables within a
    class
  6. public variables are also called properties,
    e.g. public String firstName;
  7. private variables are also called fields,
    e.g. String favoriteFood;

  1. All Java variables must be identified with unique names.
  2. These unique names are called identifiers.
  3. Common convention in naming variables is using camelCase.

  1. In Java, all the variables must be declared before use.
  2. To create (declare) a variable, you must specify the
    type.
  3. When you assign a value (or literal) to the variable it
    is initialized.
  4. Value: initial value stored in the variable. Value can be
    changed
  5. The words literal and a value can be used
    interchangeably, e.g. you can say that you assigned a value or a
    literal to the variable.
  1. Declaring and Initializing a variable: datatype
    variableName = value; //Declaring and Initializing a variable
  2. Declaring a variable, assigning the
    value (initialize) later:
    datatype variableName;
    //Declaring a variable variableName = value; //Initializing a
    variable
  3. Declaring more than one variable of the
    same type, using a comma-separated list:
    int x = 5,
    y = 6, z = 50;
  4. Assigning expressions to variables: String
    text = "This is my text" + " :) ";

You can access attributes by:

  1. creating an object of the class MyClass
    myObj = new MyClass();
  2. by using the dot syntax (.) System.out.println(myObj.attributeName);

The println() method is often used to display variables. To combine
both text and a variable(s), use the + character:
public class MyClass { public static void
main(String[] args) { String firstName = "John "; String lastName
= "Doe"; String fullName = firstName + lastName;
System.out.println(fullName); } }

For numeric values, the + character works as a mathematical
operator (notice that integer variables are used here):

public class MyClass { public static void
main(String[] args) { int x = 5; int y = 6; System.out.println(x +
y); // Print the value of x + y = 11 (not 56!) } }

Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038.
Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038.
Sufficient for storing 15 decimal digits
boolean 1 byte Stores true or false values
char 2 bytes Stores a single character/letter

int myNum = 5; float myFloatNum = 5.99f; char myLetter
= 'D'; boolean myBool = true;

  1. String Arrays,
  2. Classes,
  3. Interface

String myText = "Hello";

  1. Widening Casting (automatically/implicitly) – converting a smaller type to a larger type size.
    E.g of Type Promotion: byte -> short -> char -> int -> long -> float -> double
    Java Type Casting Type Promotion

    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double
    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
    
  2. Narrowing Casting (manually/explicitly) – converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

    double myDouble = 9.78;
    int myInt = (int) myDouble; // Manual casting: double to int
    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
    

Primitive Types vs Objects

Java has 8 kinds of primitive data types.
Object (instance of a class, class is the datatype): unlimited object types because of unlimited classes.

Autoboxing in Java

Conversion of primitives to objects is called autoboxing.

int x = 5; //primitive
Integer y = 5; //object 5 is autoboxed)

  1. Local Variables
  2. Instance Variables
  3. Static (or Class or Global) Variables
  4. Parameter
  5. Argument

import java.io.*; 
class Marks 
{    
    //These variables are instance variables. 
    //These variables are in a class and are not inside any function
    //Each object will have its own copies of instance variables 
    int engMarks; 
    int mathsMarks; 
    int phyMarks; 
} 
  
class MarksDemo 
{ 
    public static void main(String args[]) 
    {   //first object 
        Marks obj1 = new Marks(); 
        obj1.engMarks = 50; 
        obj1.mathsMarks = 80; 
        obj1.phyMarks = 90; 
  
        //second object 
        Marks obj2 = new Marks(); 
        obj2.engMarks = 80; 
        obj2.mathsMarks = 60; 
        obj2.phyMarks = 85; 
  
        //displaying marks for first object 
        System.out.println("Marks for first object:"); 
        System.out.println(obj1.engMarks); 
        System.out.println(obj1.mathsMarks); 
        System.out.println(obj1.phyMarks); 
      
        //displaying marks for second object 
        System.out.println("Marks for second object:"); 
        System.out.println(obj2.engMarks); 
        System.out.println(obj2.mathsMarks); 
        System.out.println(obj2.phyMarks); 
    } 
}

Output:

Marks for first object:
50
80
90
Marks for second object:
80
60
85

Local Variable Instance Variable
Declared within defined within a block or method or constructor non-static variable declared inside the class but outside the method, constructor or block.
Created in memory It gets memory at compile time: created when the block is entered or the function is called It gets memory at runtime: bounded to its object itself and created when an object or instance is created.
Destroyed in Memory destroyed after exiting from the block or when the call returns from the function destroyed when the object is destroyed.
Initialization Initialization of Local Variable is Mandatory Initilisation of Instance Variable is not Mandatory. Its default value is 0
Access specifiers Access modifiers can not be used for local variables Access modifiers may be used for instance variables.
Default will be used if no access specifier is defined.
Scope exists only within the scope of a block in which the variable is declared.
Can be accessed only within that block.
If we use local variable outside block/function, the compiler will produce an error.
Instance Variable can be accessed only by creating objects.
Benefits The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable. Every object of that class will create it’s own copy of the variable while using it.
Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.
Example
if(x > 100){
String test = "under 100";
}
class Test {
public String EmpName;
public int empAge;
}

  • declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
  • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
  • created at start of program execution and destroyed automatically when execution ends.
  • Initilisation of Static Variable is not Mandatory. Its default value is 0
  • If we access the static variable like Instance variable (through object), compiler will show the warning message and it wont hault the program. Compiler will replace the object name to class name automatically.
  • If we access the static variable without classname, Compiler will automatically append the class name.
  • To access static variables, we need not to create any object of that class, we can simply access the variable as:

    className.variableName;

import java.io.*;
class Emp {

// static variable salary
public static double salary;
public static String name = "Harsh";
}

public class EmpDemo
{
public static void main(String args[]) {

//accessing static variable without object
Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}

}

Output:

Harsh's average salary:1000.0

Static (or Class) Variables are associated with the class
and are common for all the instances of a class.

E.g., If we create three objects of a class and access this static variable,
it would be common for all,
changes made to the variable using one of the object
would reflect when you access it through other objects:

public class StaticVarExample {
public static String myClassVar="class or static variable";

public static void main(String args[]){
StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();

//All three will display "class or static variable"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);

//changing the value of static variable using obj2
obj2.myClassVar = "Changed Text";

//All three will display "Changed Text"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}

Output:

class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text

As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this:

System.out.println(myClassVar);

Do note that only static variables can be accessed like this. This doesn’t apply for instance and local variables.

Leave a Reply or Comment

Your email address will not be published. Required fields are marked *