Java Variables, Data Types and Operators Explained Simply (Beginner Guide)
Java Variables, Data Types and Operators Explained Simply
Author: Gursehbaj Singh | Blog: DevMode
To write any useful program in Java, you must understand variables, data types, and operators. These are the building blocks of Java programming. In this post, we will learn them in a very simple and clear way with examples.
What is a Variable?
A variable is a container that stores data in memory. Each variable has a name and a type.
int age = 18;
String name = "Gursehbaj";
Here, age stores a number and name stores text.
Rules for Naming Variables
- Must start with a letter
- Cannot start with a number
- No spaces allowed
- Should be meaningful
Java Data Types
Data types tell Java what kind of data a variable will store.
1. Primitive Data Types
- int – whole numbers
- double – decimal numbers
- char – single character
- boolean – true or false
int marks = 90;
double price = 49.99;
char grade = 'A';
boolean isPassed = true;
2. Non-Primitive Data Types
- String
- Arrays
- Classes
String city = "Delhi";
Types of Variables in Java
1. Local Variable
void show() {
int x = 10;
}
2. Instance Variable
class Student {
int rollNumber;
}
3. Static Variable
class School {
static String name = "DevMode School";
}
Operators in Java
Operators are used to perform operations on variables.
1. Arithmetic Operators
int a = 10;
int b = 5;
int sum = a + b;
int diff = a - b;
int mul = a * b;
int div = a / b;
2. Relational Operators
a > b
a < b
a == b
a != b
3. Logical Operators
boolean result = (a > b) && (b > 0);
4. Assignment Operators
int x = 10;
x += 5;
5. Increment and Decrement
int count = 1;
count++;
count--;
Type Casting in Java
Converting one data type to another is called type casting.
int num = 10;
double result = num;
User Input Example
import java.util.Scanner;
class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int sum = num1 + num2;
System.out.println("Sum is: " + sum);
}
}
Common Mistakes Beginners Make
- Forgetting semicolon
- Using wrong data type
- Confusing = with ==
Conclusion
Variables, data types, and operators are the foundation of Java programming. Once you understand them well, you can easily move to loops, conditions, methods, and object-oriented concepts. Practice these basics daily to build strong programming skills.
Comments
Post a Comment