JAVA
Variable
What is a Variable in Java?
A variable is like a container or a box that stores some data
Or
It is a memory used to store the data
A variable is assigned with a data type.
Syntax to create a variable
datatype variableName = data;
Example
int mobileNumber = 1234;
Why Do We Use Variables?
Imagine if we want to store our name or age in a program. we don’t want to keep typing it again and
again. So we use a variable to store the value once and use it anytime when we want.
Variable Declaration : the process of creating memory is known as variable declaration
Datatype variableName;
Ex: Public static void sayHello() {
Int a;
}
Variable initialization : The process of assigning value to variable
Variable = data;
Datatype variableName = data;
Public static void sayHello() {
Int a;
a=50;
String name=“java”;
}
Variable Re-initialization : The process of removing old data from the variable and updating with new
data is known as re- initialization.
Ex: Public static void sayHello() {
Int a = 10;
a=20;
}
Variable Re-Declaration : Re-Declaration of variables is not possible in java
Ex: Public static void sayHello() {
Int a = 10;
Types of Variables in Java
There are 3 main types:
1. Local Variable
2. Instance Variable
3. static variable
1. Local Variable
• 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.
Local variable with initialization
public class Test {
public void pupAge() {
int age = 0; // without initialize we may get Compile time error.
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
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:
public class Employee {
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();
}
}
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 name ClassName.VariableName.
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);
}
}
Data Types In java
What are Data Types in Java?
Data types in Java refers to tell the computer what kind of data we
are storing in a variable.
Java has two categories of data types:
1. Primitive Data Types
2. Non-Primitive Data Types
What is a Primitive Data Type?
A primitive data type is the most basic type of
data in Java.
They are already built into the language.
What is a Non-Primitive Data Type?
A non-primitive data type is not built-in,
They store references (addresses) to the actual
data, not the data
itself.
Primitive data Types:
Int , double , float , Boolean , char
Non-primitive Data Types: String
Boolean: A Boolean datatype can store only two
values
true , false
It is used when we want to make decisions or check
conditions in
our program.
Primitive data type
1. Integers
Java defines four integer types: byte, short, int, and long. All of these
are signed, positive and negative values. Java does not support
unsigned, positive-only integers.
i. Byte
The byte data type is an example of primitive data type.
It isan 8-bit signed two’s complement integer.
Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127.
default value is 0.
The byte data type is used to save memory in large arrays where the
memory savings is most required.
It saves space because a byte is 4 times smaller than an integer.
EX:
byte a = 10; byte b = -20;
ii. Short
The short data type is a 16-bit signed two’s complement integer.
.
Its minimum value is -32,768 and maximum value is 32,767.
Default value is 0.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000
iii. int
The int data type is a 32-bit signed two’s complement integer.
Its minimum value is – 2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
iv. Long
The long data type is a 64-bit two’s complement integer
Its minimum value is – 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided
by int.
2. Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
i. Float
The float data type is a single-precision 32-bit IEEE 754 floating point
Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
Example:
1. float f1 = 234.5f
ii. Double
The double data type is a double-precision 64-bit IEEE 754 floating point.
Its value range is unlimited. The double data type is generally used for decimal
values just like float.
The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.
Example:
1. double d1 = 12.3
3. Characters
i. Char
The char data type is a single 16-bit Unicode character. Its value-
range lies between ‘u0000’ (or 0) to ‘uffff’ (or 65,535 inclusive).The
char data type is used to store characters.
Always it should be enclosed b/w single quotes (‘’).
Ex: char letterA = ’A’;
Why char uses 2 byte in JAVA and What is u0000 ?
In Java, a char data type uses 2 bytes because it represents a
Unicode character, and Unicode characters are typically encoded in
16 bits, which corresponds to 2 bytes. This allows Java to support a
wide range of characters from different languages and character sets.
The u0000 is a Unicode escape sequence in Java. It represents the
null character, which has a Unicode value of 0. This escape sequence
allows you to represent Unicode characters in your Java code using
their hexadecimal Unicode values. For example, u0041 represents the
uppercase letter ‘A’, and u03B1 represents the Greek letter alpha.
Non-Primitive Data Types
Non-primitive data types or reference data types refer to instances or
objects.
It cannot store the value of a variable directly in memory. They store
a memory address of the variable.
Unlike primitive data types we define by Java, non-primitive data
types are user-defined.
Programmers create them and can be assigned with null. All non-
primitive data types are of equal size.
Non-Primitive Data Types
1. Arrays:
A collection of similar types of data. For example, int[] arr = new int[5];.
2. Classes:
User-defined data types. For example, String, ArrayList, etc.
3. Interfaces:
Like classes but only contain method signatures. For example, Comparable, Serializable, etc.
4. String :
In Java, a string is a sequence of characters. It’s a data type used to represent text rather than
numeric data. Strings in Java are immutable, meaning once a string object is created, its contents
cannot be changed.
// Declare String without using new operator
String s = "Welcome to Echobrains !";
// Declare String using new operator
String s1 = new String("Welcome to echobrains !");
5. Enum:
An enum is a special data type used to define a collection of constants.
It allows you to create a set of named constants that represent a finite set of possibilities, typically related to
some specific type or category.
Enums are declared using the enum keyword.
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
Note:
Primitive data types are passed by value, meaning the actual value is passed to methods. Reference data types, on
the other hand, are passed by reference, meaning a reference (memory address) to the object is passed to methods.
Identifiers
Identifiers are the names we give to :
• Variables
• Methods
• Classes
• Objects
Key Words
Keywords are special reserved words in Java that have a fixed
meaning.
we cannot use them as names (identifiers) for variables, classes, etc.
In java all the keywords are in lower case.
Common Java Keywords: int , class , public , static , void , if , else ,final , this , true
, false
Rules for Naming Identifiers
Can include letters (A–Z, a–z), digits (0–9), underscore _, and dollar sign $.
Identifier Cannot be a Java keyword
Ex: Public static void sayHello() {
String int(it’s a keyword) = "Hello";
System.out.println(int);
}
Identifier Cannot start with a digit or number
Public static void sayHello() {
String 1name(compilation error) = "Hello"; // Local variable
System.out.println(1name);
}
Identifier cannot be a special character Except $(dollar) and _(underscore).
Can be of any length.
Case-sensitive — Name and name are different identifiers.
Type Casting
Type Casting means converting one data type into another data type.
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.
There are Two Types of Type Casting in Java:
1. Widening (Implicit) Casting
2. Narrowing (Explicit) Casting
Widening :
Widening type casting, also known as implicit type casting or
widening conversion, occurs when you convert a value from a smaller
data type to a larger data type.
In Java, widening conversions are performed automatically by the
compiler because they do not involve any loss of data.
byte → short →int →long →float →double
• Syntax : int variableName = varNameToBeTypeCasted;
Public static void sayHello() {
int num = 100;
double bigNum = num; // Automatically converted to double
System.out.println(bigNum); // Output: 100.0
}
Narrowing :
Narrowing type casting, also known as explicit type casting or narrowing conversion,
occurs when you convert a value from a larger data type to a smaller data type.
In Java, narrowing conversions may lead to loss of data and therefore require explicit
casting.
double → float →long →int →short →byte
• Narrowing must be done explicitly by our own.
• There is possible data loss while converting if data is too Big.
Syntax : targetDataType variableName = (targetDataType) valueOfLargerDataType ;
Public static void sayHello() {
double price = 99.99;
int roundedPrice = (int) price; // Manual casting
System.out.println(roundedPrice); // Output: 99
}
From Type To Type Syntax Example Result
double float float f = (float) 12.34d; 12.34
double long long l = (long) 123.456d; 123 (fractional part lost)
double int int i = (int) 99.99d; 99
double short short s = (short) 1000.50d; 1000
double byte byte b = (byte) 130.45d; -126 (overflow occurs)
float long long l = (long) 89.56f; 89
float int int i = (int) 78.9f; 78
float short short s = (short) 32000.9f; -33536 (overflow)
float byte byte b = (byte) 150.5f; -106 (overflow)
long int int i = (int) 2147483648L; -2147483648 (overflow)
long short short s = (short) 32768L; -32768 (overflow)
long byte byte b = (byte) 128L; -128 (overflow)
int short short s = (short) 40000; -25536 (overflow)
int byte byte b = (byte) 256; 0 (overflow)
short byte byte b = (byte) 150; -106 (overflow)
Type conversion from int to
String
class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);
// converts int to string type
String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}
Output:
The integer value is: 10
The string value is: 10
Type conversion from String to int
class Main {
public static void main(String[] args) {
// create string type variable
String data = "10";
System.out.println("The string value is: " + data);
// convert string variable to int
int num = Integer.parseInt(data);
System.out.println("The integer value is: " + num);
}
}
output:
The string value is: 10
The integer value is: 10