Interview question
What are variables and data types in Java? Java में variables और data types क्या हैं?
Answer
Variables are named memory locations that store values. Data types define the type of data a variable can hold.
| Data Type | Size | Range | Example |
|---|---|---|---|
| byte | 1 byte | -128 to 127 | byte b = 10; |
| short | 2 bytes | -32,768 to 32,767 | short s = 1000; |
| int | 4 bytes | -2^31 to 2^31-1 | int i = 100000; |
| long | 8 bytes | -2^63 to 2^63-1 | long l = 10000000000L; |
| float | 4 bytes | Single precision | float f = 3.14f; |
| double | 8 bytes | Double precision | double d = 3.14; |
| char | 2 bytes | Unicode (0 to 65,535) | char c = 'A'; |
| boolean | 1 bit | true or false | boolean flag = true; |
// Primitive Data Types
public class DataTypes {
public static void main(String[] args) {
// Numeric types
byte age = 25;
short distance = 5000;
int salary = 50000;
long population = 1000000000L;
// Decimal types
float price = 19.99f;
double pi = 3.14159265;
// Character type
char gender = 'M';
// Boolean type
boolean isActive = true;
// Reference Types (Non-primitive)
String name = 'John';
int[] numbers = {1, 2, 3, 4, 5};
}
}
// Type Casting
int a = 10;
long b = (long) a; // Implicit casting (widening)
double x = 10.5;
int y = (int) x; // Explicit casting (narrowing)Variables memory locations हैं। Data types define करते हैं कि variable कितना data store कर सकता है।
Was this answer clear?