What is Variable?
Variable is a container which holds a Value
Datatype VariableName = value;
Example: int var = 32
Java is Static typed language - If we define the data type of a variable then it is static typed. Data type tells us what kind of data the variable can store. If we hardcode the data type of variable then it is static typed language.
Java is Strong typed language - If we enforce rules on the data side then it is strong typed language. Example int can store values from certain range and it cannot store beyond that range. It means that there is a restriction. Also it cannot store any string values as the data type is int.
Variable Naming Convention
Variable name is Case-Sensitive
Variable name can be any legal identifier means can contain Unicode letters and Digits
- Unicode - Universal code of characters like all english letters, special characters ..etc.
Variable name can start with "$", "_" and letter.
Variable name cannot be JAVA reserved keywords like "new", "class", "while", "for", "interface", "int", "float" etc.
Variable should be all small if it contains only 1 word else camel case should be followed
- Example: int jaipur = 100; int jaipurCity = 100
For Constant, Variable name should be define in CAPITAL LETTERS.
- Example: static final int JAIPUR = 100;
Types of Variables
Primitive Types (8)
Reference/ Non Primitive Types
Primitive Types
char
2 bytes (16 bits)
Character Representation of ASCII valeus.
Range: 0 to 65535 i.e '\u0000' to '\uffff'
char var = 'a'
System.out.println(var)
//output: a
char var = 65;
System.out.println(var)
//output: A
/*
0 - /u0000
64 - @
65 - A
65 - B
*/
byte
1 byte (8 bits)
Signed 2 compliment
0 _ _ _ _ => Positive Number
1 _ _ _ _ => Negative Number
-3 is obtained by (2's compliment of 3)
(-3)
= 2's(3)
= (3' + 1)
= ((0011)' + 1)
= (1100 + 1)
= 1101
0 0 1 1 => +3
1 1 0 1 => -3
_________
0 0 0 0 => 3 + (-3)
Range: -128 to 127
default value is 0
public class Employee{
byte var1; // class member variable
public void dummyMethod(){
byte localVariable;
System.out.println(var1); // prints 0, member variable default value is 0
System.out.println(localVariable); //Error: local variable doesn't have any default value
}
}
short
2 bytes (16 bits)
Signed 2 compliment
Range: -32768 to 32767
default value is 0
short val = 200;
int
4 bytes (32 bits)
Signed 2 compliement
Range: -2^31 to 2^31 -1
default value is 0
int val = 900;
long
8 bytes (64 bits)
Signed 2's compliment
Range: -2^63 to 2^63 -1
Default value is 0
long val = 5001l
float
- 32 bit IEEE 754 value
float val = 63.20f;
float var1 = 0.3f;
float var2 = 0.1f;
float var3 = var1 - var2;
System.out.println(var3);
//Output: 0.20000002
double
- 64 bit IEEE 754 value
double val = 63.20d;
- Don't use float or double: If we are very much particular about decimal then we should not use float or double we should go with BigInteger.
boolean
1 bit
Value is true/false
Default value is false
boolean flag = true;
Reference/ Non Primitive Type
I. Class
When we create a class using a new key word and assign it to variable. It means that the object is created in the heap memory and this memory reference is assigned the variable.
In java there is only pass by value and no pass by reference (pointers). Also we cannot manipulate the memory addresses or references.
Example
Code
public class Employee {
int empId;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}
public class Main {
public static void main(String[] args) {
Employee employeeObject = new Employee();
employeeObject.empId = 10;
modify(employeeObject);
System.out.println(employeeObject.empId);
}
//pass by value
// employeeObject contains reference and this value is passed to empObj
private static void modify(Employee empObj) {
empObj.empId = 20;
}
}
II. String
Strings are immutable: Strings once created cannot be modified in the memory.
String Literals (Constants): Strings that are created without using the new keyword are called the literals. These are present in string constant pool.
String s1 = "hello"; //Creates a string literal in string constant pool
String s2 = "hello"; //Creates a string literal in string constant pool
String s3 = new String("hello"); //Creates an object outside string constant pool
System.out.println(s1==s2); // true //Check whether they point to same memory
System.out.println(s1.equals(s2)); //true //Check the content in s1 and s2
System.out.println(s1==s3); //false //check the memory address reference
System.out.println(s1.equals(s3)); //true //check the content in s1 and s3
s1 = "hello world";//This will Creates string literal in string constant pool
III. Interface
An interface resembles a class. It serves as a blueprint, devoid of any implemented functionality, requiring all child classes to implement its methods.
Interface can be created using the interface keyword.
Objects cannot be created from an interface.
Child class objects can be assigned to a class or variable of interface type.
Usage
public class Student{
public static void main(String[] args) {
Person softwareEngineer = new Engineer();
Person teacher = new Teacher();
Teacher teacher1 = new Teacher();
Engineer softwareEngineer1 = new Engineer();
}
}
IV. Array
Array stores a collection of elements, typically of the same type, in contiguous memory locations. Arrays allow for efficient storage and retrieval of data elements through indexing.
This is also a reference type; if you change it, the corresponding change will also occur in memory.
// 1D array
int[] arr = new int[5];
int arr[] = new int[5];
int [] arr = new int[5];
int[] arr = {15,18,1,28,20};
arr[0] = 15;
arr[1] = 18;
arr[4] = 20;
//arr[5] doesn't exist 0 based index
// 2D array
int arr[][];
int[][] arr;
int arr[][] = new int[5][5];
/*
Representation
[
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
*/
int arr[][] = new {{1,5,7}, {4,2,3}}
/*
[
[1, 5, 7],
[4, 2, 3],
]
*/
Types of Conversions
1. Widening / Automatic Conversion
From lower data type to higher data type it do automatic conversion
int val1 = 10;
long val2 = val1
2. Downcasting / Explicit Casting
- ```java int integerVar = 10; byte byteVariable = integerVar; // Error
int integerVar = 10; byte byteVariable = (byte)integerVar; System.out.println(byteVariable); // 10
int integerVar = 128; byte byteVariable = (byte)integerVar; System.out.println(byteVariable); // 127
//range of byte: -128 to 127
### 3\. Promoting during Expression
* While adding the numeric data types if it exceeds the range then the addition environment is automatically promoted the next highest data type. For example in byte-byte addition the it is automatically promoted to int (even for short data type). We can define or restrict the environment promotion by explicitly casting.
* ```java
byte val1 = 1;
byte val2 = 127;
byte sum = (byte)(val1 + val2);
System.out.println(sum); // -128
byte val1 = 1;
byte val2 = 127;
int sum = val1 + val2;
System.out.println(sum); // 128
If in an expression if one of the data type is higher then all the other elements are also converted to the higher data type.
int a = 10; double val = 232d; int res = a + val; // Error int a = 10; double val = 232d; double res = a + val; System.out.println(res); // 242d
Kind of Variables
Local Variables
Instance / Member Variable
Class / Static Variable
Method Parameters
Constructor Parameters
public class Employee { int memberVariable; //Member Variable static int staticVariable = 0; //Static Variable Employee(){ } //Constructor Variable Employee(int a){ } public void dummyMethod(){ byte localVariable = 10; //local Variable System.out.println(localVariable); } public int dummyMethod2(int a, int b){ return a+b; } }
IEEE 754 Representation (How float and double values store in memory?)
I. Float: 32 IEEE 754
Example: 4.125f
Step 1: Convert it to Binary
Step 2: Make it in the form of (1.xxx) X 2^exponent
100.001 = 1.00001 x 2^2
Step 3: Add bias to the exponent
for Float bias - 127
exponent = 127 + 2 = 129
Step 4: Get the binary representation and value
- Formula = (-1)^sign x (1+mantissa) x 2^(e - 127)
= (-1)^0 x (1+(1/2)^5) x 2^2
= 1.03125 x 4
= 4.125
Example: 0.7f
Step 1 - Convert it Binary
0.7 x 2 = 1.4 -> 1
0.4 x 2 = 0.8 -> 0
0.8 x 2 = 1.6 -> 1
0.6 x 2 = 1.2 -> 1
0.2 x 2 = 0.4 -> 0
0.4 x 2 = 0.8 -> 0
0.8 x 2 = 1.6 -> 1
0.6 x 2 = 1.2 -> 1
0.2 x 2 = 0.4 -> 0
0.7f = 0.1 0110 0110 0110 0110 0110 0110 0110 ....
Step 2 - Get into the IEEE Format
0.7f = (1. 0110 0110 0110 0110 0110 0110 0110 ....) x 2^(-1)
Step 3 - Add bias to the exponent
exponent = 127 + (-1) = 126
Step 4 - Binary Representation
0 | 0 1 1 1 1 1 1 0 | 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
= (-1)^0 x (1 + 2^(-2) + 2^(-3) + 2^(-6) + 2^(-7) + 2^(-10) + 2^(-11) +
2^(-14) + 2^(-15) + 2^(-18) + 2^(-19) + 2^(-22) + 2^(-23)) x 2^(-1)
= 0.69707031
II. Double: 64 IEEE 754
Sign - 1
Exponent - 11
Mantisa - Remaining 52
Wrapper Class
To get the following features on the primitive data types we use wrapper class.
Reference Capability
All the collections work on objects that is reference data type.
Primitive data types are stored in a stack not in heap.
public class Main {
public static void main(String[] args) {
int a = 10;
System.out.println(a); //prints 10
modify(a);
System.out.println(a); //prints 10
}
private static void modify(int x) {
x = 20;
}
}
Autoboxing and Unboxing
//Auto boxing
int a=10;
Integer x = a;
//Auto unboxing
Integer x = 20;
int a = x;
Constant
Static ensures that there is only a single instance of the variable shared across all objects, while final guarantees that it remains unalterable.
class Employee{
static final int EMP_ID = 10; //constant variable
}