Java Variables
A variable is a container which holds the value while the Java program is executed. Variable is
a name of memory location. There are two types of data types in Java: primitive and non-
primitive.
Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double.
When a primitive data type is stored, it is the stack that the values will be assigned. When a
variable is copied then another copy of the variable is created and changes made to the
copied variable will not reflect changes in the original variable.
Ex. Demo
Non-Primitive Data Type or Object Data type: such as String, Array, etc.
When the reference variables will be stored, the variable will be stored in the stack and the
original object will be stored in the heap. In Object data type although two copies will be
created they both will point to the same variable in the heap, hence changes made to any
variable will reflect the change in both the variables
Ex. Demo
Example
Type Description Default Size Literals Range of values
boolean true or false false 1 bit true, false true, false
twos-
8
complement 0 (none) -128 to 127
bits
byte integer
‘a’, ‘\u0041’, ‘\ characters representation of
Unicode 16
\u0000 101’, ‘\\’, ‘\’, ‘\ ASCII values
character bits
char n’, ‘β’ 0 to 255
twos-
16
complement 0 (none) -32,768 to 32,767
bits
short integer
twos- -2,147,483,648
32
complement 0 -2,-1,0,1,2 to
bits
int intger 2,147,483,647
long twos- 0 64 -2L,- -
complement bits 1L,0L,1L,2L 9,223,372,036,854,775,808
Example
Type Description Default Size Literals Range of values
to
integer
9,223,372,036,854,775,807
1.23e100f , -
IEEE 754
32 1.23e-
floating 0.0 upto 7 decimal digits
bits 100f , .3f ,3.1
point
float 4F
IEEE 754 1.23456e300d
64
floating 0.0 , -123456e- upto 16 de
bits
double point 300d , 1e1d
Why char uses 2 bytes in java and what is \
u0000?
It is because java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system.
Unicode System
Unicode is a universal international standard character encoding that is capable of representing
most of the world's written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
o ASCII (American Standard Code for Information Interchange) for the United States.
o ISO 8859-1 for Western European Language.
o KOI-8 for Russian.
o GB18030 and BIG-5 for Chinese, etc
Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length. Some common characte
encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in Java
Operator in Java is a symbol that is used to perform operations
Java Operator Precedence
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Properties Primitive data types Objects
Origin Pre-defined data types User-defined data types
Reference variable is stored in
Stored structure Stored in a stack stack and the original object is
stored in heap
Two different variables is
Two reference variable is
created along with different
When copied created but both are pointing to
assignment(only values are
the same object on the heap
same)
When changes are made Change does not reflect in Changes reflected in the
in the copied variable the original ones. original ones.
Primitive datatypes do not The default value for the
Default value
have null as default value reference variable is null
Example byte, short, int, long, float, array, string class, interface
Properties Primitive data types Objects
double, char, boolean etc.
Java Identifiers
In Java, identifiers are used for identification purposes. Java Identifiers can
be a class name, method name, variable name, or label.
Example of Java Identifiers
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5 identifiers namely:
Test: class name.
main: method name.
String: predefined class name.
args: variable name.
a: variable name.
Rules for Defining Java Identifiers
There are certain rules for defining a valid Java identifier. These rules must be followed,
otherwise, we get a compile-time error. These rules are also valid for other languages like C,
and C++.
The only allowed characters for identifiers are all alphanumeric characters([A-Z], [a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid Java identifier
as it contains a ‘@’ a special character.
Identifiers should not start with digits ([0-9]). For example, “123geeks” is not a valid Java
identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example, “int while = 20;” is an invalid
statement as a while is a reserved word. There are 53 reserved words in Java.
Scope of Variables In Java
1.Member Variables (Class Level Scope):
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static. It is called an instance
variable because its value is instance-specific and is not shared among
instances.
2.Local Variables (Method Level Scope)
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists. A local variable cannot be
defined with "static" keyword.
3.Static variable (Application Level Scope)
A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory.
Type Casting in Java
In Java, type casting is a method or process that converts a data type into another
data type in both ways manually and automatically. The automatic conversion is
done by the compiler and manual conversion performed by the programmer.
Types of Type Casting
o Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down. It is done automatically. It is
safe because there is no chance to lose data.
It is safe because there is no chance to lose data. It takes place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.
o byte -> short -> char -> int -> long -> float -> double
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we do
not perform casting, then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
public class NarrowingTypeCastingExample {
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
} }