What are the types of variables in java
In Java, variables are containers that store data values. There are several types of variables in Java, broadly categorized into primitive types and reference types.
1. Primitive Types:
1. byte: (Size: 8 bits)
byte myByte = 127;
2. short: (Size: 16 bits)
short myShort = 32000;
3. int: (Size: 32 bits)
int myInt = 123456;
4. long: (Size: 64 bits)
long myLong = 123456789L;
5. float: (Size: 32 bits – single-precision)
float myFloat = 3.14f;
6. double: (Size: 64 bits – double-precision)
double myDouble = 3.14159265359;
7. char: (Size: 16 bits)
char myChar = 'A';
8. boolean: (Size: Not precisely defined, typically implementation-dependent)
boolean isTrue = true;
2. Reference Types:
1. Object References:
String myString = "Hello, Java!";
//or
Integer myInteger = 42;
2. Array References:
int[] myArray = {1, 2, 3, 4, 5};
3. Custom Class References:
class MyClass {
// class definition
}
MyClass myObject = new MyClass();
4. Interface References:
interface MyInterface {
// interface definition
}
MyInterface myImplementation = new MyInterface() {
// anonymous implementation
};
These are the basic types of variables in Java. It’s important to choose the appropriate type based on the nature of the data you want to store. Primitive types are used for simple values, while reference types are used for more complex structures and objects.