Table of Contents
ToggleData Types, Keywords and Variables:
Variables are memory locations to store values. When a user creates a variable, a memory space is reserved for that the variable. Based on the type of the variable, the operating system allocatesmemory and decides what can be stored in that reserved space. A user can store integers, decimals, character, etc. by assigning different data types to the variables. Data type is a keyword used to allocate sufficient memory space for the data. Pictorial representation of data types and its classifications are given below:

1. Primitive Data Types
These are the basic, built-in data types in Java. They are not objects and directly store values. There are 8 primitive data types, and these are Byte, Short, int, Long, Float, Double, Char, and boolean:
Integers:
In Java, an integer is a data type used to store whole numbers (numbers without decimal points). It can be positive, negative, or zero. Integers are mainly represented by the primitive data types byte, short, int, and long, depending on the size of the number. Among these, int is the most commonly used data type for integers.
- byte → small integers (–128 to 127)
- short → medium integers (–32,768 to 32,767)
- int → standard integers (–2,147,483,648 to 2,147,483,647)
- long → very large integers (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
Byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from -128 to 127. Variables of type byte are especially useful when you’re working with a stream of data from a network or file. It can be represented as: Byte b, c;
Short
Short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used
Java type. Here are some examples of short variable declarations:
short s;
short t;
Int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647.22 In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.
Long
Long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed
Float Types :
Float is specified as a single-precision value that uses 32 bits of storage. Single precision is faster and takes half as much space as double precision, but it will become imprecise when the values are either very large or very small.Here are some example float variable declarations:
float hightemp, lowtemp;
Double
Double is denoted by the keyword ‘double’, which is used to store a value of 64 bits. It is faster than single precision on modern processors that have been optimised for high-speed mathematical calculations. Some importance of double are All transcendental math functions, such as :
- sin( )
- cos( )
- sqrt( )
Characters
Char in Java is not the same as char in C or C++. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as
- Latin
- Greek
- Arabic
- Cyrillic
- Hebrew
In Java, char is 16 bit and ranges from 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Here is a program that demonstrates char variables: class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.println("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } }
Boolean: In Java, a boolean is a primitive data type that can store only two possible values: true or false
Table summary
| Data Type | Size | Default Value | Example Value | Description |
|---|---|---|---|---|
| byte | 1 byte | 0 | 100 | Stores small integers (–128 to 127). |
| short | 2 bytes | 0 | 30000 | Stores larger integers (–32,768 to 32,767). |
| int | 4 bytes | 0 | 100000 | Stores whole numbers (–2,147,483,648 to 2,147,483,647). |
| long | 8 bytes | 0L | 123456789L | Stores very large integers. |
| float | 4 bytes | 0.0f | 10.5f | Stores decimal values (single precision). |
| double | 8 bytes | 0.0d | 99.99 | Stores decimal values (double precision). |
| char | 2 bytes | ‘\u0000’ | ‘A’ | Stores a single character or Unicode. |
| boolean | 1 bit | false | true/false | Stores logical values (true or false). |
2. Non-Primitive (Reference) Data Types
These are derived from classes and store references (addresses) to objects, not the actual value. Examples include:
- String → Stores sequences of characters.
- Arrays → Stores multiple values of the same type.
- Classes, Objects, Interfaces → User-defined data types.
Example:
public class DataTypesExample { public static void main(String[] args) { // Primitive data types int age = 25; double price = 99.99; char grade = 'A'; boolean isJavaFun = true;// Non-primitive data type String name = "Basant"; System.out.println("Age: " + age); System.out.println("Price: " + price); System.out.println("Grade: " + grade); System.out.println("Is Java Fun? " + isJavaFun); System.out.println("Name: " + name); } } out put: Age: 25 Price: 99.99 Grade: A Is Java Fun? true Name: Basant
Identifiers in Java:
An identifier is the name given to a variable, class, method, or object in a Java program. It is used to identify (recognize) different elements in the code. For example, when you create a variable or method, the name you assign to it is called an identifier.
Rules for Identifiers
- Identifiers can contain letters (A–Z, a–z), digits (0–9), underscore (_), and dollar sign ($).
- The first character cannot be a digit (e.g.,
123abcis invalid. - Identifiers are case-sensitive (
Nameandnameare different. - Java keywords cannot be used as identifiers (e.g.,
class,int,while). - Identifiers should not contain spaces (e.g.,
my variableis invalid.
Examples
Valid Identifiers age studentName _rollNo $salary Invalid Valid Identifiers 123age //cannot start with a digit student name //cannot contain space int //cannot use keyword
Variable in Java:
A variable in Java is a named memory location that stores data. It acts like a container where we can keep values, and the value can change (vary) during program execution. For example:
int age = 20;
Here, age is a variable of type int that stores the value 20.
Types of Variables in Java:
Local Variable: Declared inside a method, constructor, or block. It is created when the method is called and destroyed after it finishes.Example
void show() {
int number = 10; // local variable
System.out.println(number);
}2. Instance Variable – Declared inside a class but outside any method. Each object of the class has its own copy.Example
class Student {
String name; // instance variable
}3. Static Variable – Declared with the keyword Static. It belongs to the class, not to individual objects, and all objects share the same value.Example
class Student {
static String school = "ABC School"; // static variable
}Rules for Naming Variables
- Must start with a letter, underscore (_), or dollar sign ($)
- Cannot start with a digit
- Cannot use Java keywords (like int, class, while)
- Should have a meaningful name (e.g., mark is better than m1)
Example:
public class VariableExample { int rollNo = 101; // instance variable static String college = "XYZ College"; // static variable void display() { String name = "Basant"; // local variable System.out.println(rollNo + " - " + name + " - " + college); } public static void main(String[] args) { VariableExample obj = new VariableExample(); obj.display(); } }
Constant in Java:
A constant in Java is a value that does not change during the execution of the program. Unlike variables, once a constant is assigned a value, it cannot be modified. Constants make programs more reliable and easier to understand.n Java, constants are usually declared using the final keyword.
Example:
final int AGE = 18; // AGE is a constant final double PI = 3.14159; // PI is a constant final String COUNTRY = "Nepal"; // COUNTRY is a constant
Here, the values of AGE, PI, and COUNTRY cannot be changed later in the program. Example program:
public class ConstantExample { public static void main(String[] args) { final double PI = 3.14159; // constant final int DAYS_IN_WEEK = 7; System.out.println("Value of PI: " + PI); System.out.println("Days in a Week: " + DAYS_IN_WEEK); // PI = 3.15; // Error: cannot change the value of a constant } }
Difference Between Variables and Constants in Java
| Variable | Constant |
|---|---|
| A variable is a named memory location whose value can change during program execution. | A constant is a fixed value that cannot be changed once assigned. |
| No special keyword is needed, just the data type. | Declared using the final keyword. |
| Value can be reassigned many times. | Value cannot be reassigned after initialization. |
Usually written in camelCase (e.g., studentAge). | Usually written in UPPERCASE (e.g., MAX_VALUE). |
| Can be assigned and changed at any point. | Must be assigned a value at the time of declaration. |
Example: int age = 20; → later age = 25; | Example: final int AGE = 20; → cannot change later. |
Keywords in Java programming
In Java programming, a keyword is a special reserved word that has a fixed meaning. It is used by Java to perform specific tasks, and we cannot use it as a variable, class, or method name. These words are part of the Java language syntax and are used to perform specific tasks such as defining data types, controlling program flow, declaring classes, methods, and variables.
Example:
- int number =10: → Here, int is a keyword used to declare an integer variable.
- if (number>5)→ Here, if is a keyword used for decision-making.
Access modifiers:
In Java programming, access modifiers are special keywords that define the visibility (scope) of classes, methods, and variables. They control who can access a particular piece of code.
Types of Access Modifiers in Java:
- public:
- Members are accessible from anywhere (inside the class, derived classes, and outside the class).
- Typically used for interface functions (e.g., getters, setters, or other methods meant for external use).
- protected:
- Members are accessible within the class and in derived classes.
- Not accessible from outside the class hierarchy (e.g., by objects or external functions).
- private:
- Members are accessible only within the class where they are defined.
- Not accessible in derived classes or outside the class, unless accessed via public/protected member functions.
Example: Public, Private, and Protected
class Person { private String name = "Basant"; // private protected int age = 25; // protected public String country = "Nepal"; // public private void showName() { System.out.println("Name: " + name); } protected void showAge() { System.out.println("Age: " + age); } public void showCountry() { System.out.println("Country: " + country); } public void displayAll() { showName(); // private accessible inside class showAge(); // protected accessible showCountry();// public accessible } } public class AccessExample { public static void main(String[] args) { Person p = new Person(); // public access p.showCountry(); // private access (not allowed directly) // p.showName(); ❌ Error // protected access (not allowed directly outside class/package) // p.showAge(); ❌ Error // But accessible through public method p.displayAll(); } }
Escape Sequences in Java
In Java programming, an escape sequence is a special character used to perform certain actions in strings, like inserting a new line, tab, or double quote. Escape sequences begin with a backslash \ followed by a character. They are used when you want to include characters that cannot be typed directly or have a special meaning in strings.

Example:
public class EscapeExample {
public static void main(String[] args) {
System.out.println("Hello\nWorld"); // New line
System.out.println("Java\tProgramming"); // Tab space
System.out.println("He said: \"Hello\""); // Double quotes
System.out.println("Path: C:\\Program"); // Backslash
}
}
Output:
Hello
World
Java Programming
He said: "Hello"
Path: C:\Program
Comments in Java
In Java programming, a comment is a note or explanation in the code that is ignored by the compiler. Comments are used to make the code readable and to explain what the code does.
Types of Comments in Java
In Java, there are three main types of comments used to explain the code and improve readability. These comments are ignored by the compiler and do not affect program execution.
1. Single-line Comment : Single-line Comment Starts with // Used for short explanations.
2. Multi-line Comment: Multi-line comments start with /* and end with */3. Documentation Comment: Starts with /** and ends with */ Used to generate Java documentation (Javadoc), and used for longer explanations or multiple lines.
Example: public class CommentExample { public static void main(String[] args) { int a = 10; // This is a single-line comment /* This is a multi-line comment explaining the next line of code */ int b = 20; /** * This is a documentation comment * It describes the addition of two numbers */ int sum = a + b; System.out.println("Sum: " + sum); // Prints the sum } }
Operators in Java:
In Java, operators are special symbols or keywords used to perform operations on variables and values. They are the foundation of any programming language and allow you to manipulate data, perform calculations, compare values, and control program flow.
Types of Operators in Java:

1. Arithmetic operators
In Java programming, arithmetic operators are used to perform basic mathematical calculations on numeric data types. The primary arithmetic operators include addition (+), subtraction (-), multiplication (*), and division (/), along with the modulus operator (%) for obtaining the remainder of the division.
2. Relational Operator:
In Java programming, relational operators are used to compare two values or expressions, returning a boolean result (true or false). The primary relational operators include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). These operators are essential for making decisions and controlling the flow of a program through conditional statements.

3 Logic operators:
In Java programming, logical operators are used to perform logical operations on Boolean values, returning true or false based on the evaluation of the expressions. The primary logical operators include AND (&&), OR (||), and NOT (!). These operators are essential for constructing complex conditional statements and controlling the flow of a program.

4. Assignment Operators :
In Java programming, an assignment operator is used to assign a value to a variable. The most common assignment operator is=, which sets the variable on the left to the value on the right. For example, int a = 5; assigns the value 5 to the variable a.
5. Increment and Decrement Operators:
In java programming, increment and decrement operators are used to increase or decrease the value of a variable by 1. The increment operator is ++ and the decrement operator is --.
- They can be used in prefix form (e.g.,
++a) or postfix form (e.g.,a++). Prefix changes the value before use, while postfix uses the value before changing it.
6. Conditional Operator
In java programming, the conditional operator (also called the ternary operator) is a concise way to perform conditional evaluations. It is the only ternary operator in C, taking three operands, and is often used as a shorthand for simple if-else statements.
Special Operators
Java Language includes several special operators that perform unique operations beyond basic arithmetic and logic. Here are the most important special operators:
Special Operators in Java:
- Comma Operator
( , ) sizeofOperator- Address-of Operator
( & ) - Pointer Dereference Operator
( * ) - Ternary (Conditional) Operator
( ? : ) - Bitwise Operators:
- Bitwise AND
( & ) - Bitwise OR
( | ) - Bitwise XOR
( ^ ) - Bitwise NOT
( ~ ) - Left Shift
( << ) - Right Shift
( >> )
Arithmetic Operators Example
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
out put:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
Relational (Comparison) Operators Example
public class RelationalExample {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("a == b: " + (a == b));
System.out.println("a != b: " + (a != b));
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
}
}
out put:
a == b: false
a != b: true
a > b: false
a < b: true
a >= b: false
a <= b: true
Logical Operators Example
public class LogicalExample {
public static void main(String[] args) {
boolean x = true, y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}
out put:
x && y: false
x || y: true
!x: false
Assignment Operators Example
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
a += 5;
System.out.println("After += : " + a);
a -= 3;
System.out.println("After -= : " + a);
a *= 2;
System.out.println("After *= : " + a);
a /= 4;
System.out.println("After /= : " + a);
a %= 3;
System.out.println("After %= : " + a);
}
}
out put:
After += : 15
After -= : 12
After *= : 24
After /= : 6
After %= : 0
Increment and Decrement operators example
public class UnaryExample {
public static void main(String[] args) {
int a = 5;
System.out.println("Original: " + a);
System.out.println("++a: " + (++a)); // pre-increment
System.out.println("a++: " + (a++)); // post-increment
System.out.println("After post-increment: " + a);
System.out.println("--a: " + (--a)); // pre-decrement
System.out.println("a--: " + (a--)); // post-decrement
System.out.println("After post-decrement: " + a);
}
}
out put:
Original: 5
++a: 6
a++: 6
After post-increment: 7
--a: 6
a--: 6
After post-decrement: 5
Compiled by Er.Basant Kumar Yadav
