Variables, Literals, 8 Primitive Data Types & Overflow/Underflow
1. Topic Introduction
Java is a strongly typed language: every variable must declare its exact data type before use so the compiler can catch mismatched data early and allocate exact memory. Mastering Java's 8 primitive types, variable scopes (local, instance, static), and literals prevents countless bugs in code-tracing exam questions.
Think of variables as labeled boxes in a warehouse. You can't cram a fridge into a jewelry box or waste a shipping container on a coin. Java gives you 8 exact box sizes (byte for tiny integers up to double for huge high-precision decimals, char for a single Unicode symbol, and boolean for a simple true/false light switch). Also, a box placed inside a single room (local variable) must be filled before anyone reads it, whereas boxes built into a house (instance/static fields) start with safe default zeroes!
byte, short, int, long, float, double, char, boolean) and 3 variable categories (local = no default value, instance = per object on Heap, static = 1 shared copy in Method Area).3. Essential Exam Definitions
byte, short, int, long, float, double, char, boolean) whose size and range are fixed across all platforms.100, 0x1F, 012), floating-point (3.14f, 1.2e5), boolean (true, false), character ('A', '\u0064'), string ("KTU"), or null (for references only).Overflow) or drops below the minimum (Underflow) range of an integer type, causing silent two's-complement wrap-around without throwing an exception.4. Detailed Technical Explanation & Syntax
The 8 Primitive Data Types (Exact Sizes, Ranges & Defaults)
Java primitives are divided into Integer types (byte, short, int, long), Floating-point types (float, double), Character (char — 2-byte unsigned Unicode, unlike C's 1-byte ASCII), and Boolean (boolean).
byte(1 byte / 8-bit signed):-128to127, default0. Example:byte b = 123;short(2 bytes / 16-bit signed):-32,768to32,767, default0. Example:short s = 1234;int(4 bytes / 32-bit signed):-2^31to2^31 - 1(-2,147,483,648to2,147,483,647), default0. Default integer literal type.long(8 bytes / 64-bit signed):-2^63to2^63 - 1, default0L. RequiresL/lsuffix (long pop = 8000000000L;).float(4 bytes / 32-bit IEEE 754): ~6–7 decimal digits precision, default0.0f. Must end withforF(float f = 12.5f;), because decimal literals default todouble!double(8 bytes / 64-bit IEEE 754): ~15 decimal digits precision, default0.0d. Default floating-point literal type.char(2 bytes / 16-bit unsigned Unicode):'\u0000'(0) to'\uffff'(65,535), default'\u0000'. Supports arithmetic likec++.boolean(JVM-dependent, logically 1 bit of info): Onlytrueorfalse(cannot use0or1like C!), defaultfalse.
Three Variable Types in Java: Local, Instance & Static
Where you declare a variable determines its lifetime, memory area, and whether Java assigns a default value:
- Local Variable: Declared inside a method, constructor, or block; stored on the JVM Stack; NO default value (reading before initializing triggers a Compile-Time Error!); cannot use
staticor access modifiers (public/private). - Instance Variable: Declared inside a class outside methods, without
static; each object gets its own copy on the Heap; automatically gets default values (0,0.0,false,'\u0000', ornullfor references). - Static (Class) Variable: Declared inside a class with
static; single shared copy stored in Method Area at class load; gets default values; accessed viaClassName.varName.
5. Working Principle: How Integer Rollover (Overflow) & Literal Suffixes Work
- Every decimal point literal (e.g.,
3.14) is treated asdoublebyjavac; assigningfloat x = 3.14;fails compilation unless written3.14f. - Integer literals with leading
0(like012) are Octal (base 8);0xindicates Hexadecimal (base 16);0b(Java 7+) indicates Binary. - If
byte b = 127;executesb++;, the 8-bit two's-complement pattern01111111wraps to10000000(-128) silently.
7. Complete Java Code Examples & Tracing
| 1 | public class PrimitiveTypesDemo { |
| 2 | // Instance variables receive automatic default values |
| 3 | byte defaultByte; |
| 4 | int defaultInt; |
| 5 | double defaultDouble; |
| 6 | boolean defaultFlag; |
| 7 | String defaultRef; |
| 8 | |
| 9 | public static void main(String[] args) { |
| 10 | PrimitiveTypesDemo demo = new PrimitiveTypesDemo(); |
| 11 | System.out.println("Defaults -> byte: " + demo.defaultByte |
| 12 | + ", int: " + demo.defaultInt |
| 13 | + ", double: " + demo.defaultDouble |
| 14 | + ", boolean: " + demo.defaultFlag |
| 15 | + ", String: " + demo.defaultRef); |
| 16 | |
| 17 | // Local variables MUST be initialized before use |
| 18 | char letter = 'A'; |
| 19 | letter++; // char is unsigned 16-bit integer (65 -> 66) |
| 20 | System.out.println("Incremented char: " + letter); |
| 21 | |
| 22 | byte maxByte = 127; |
| 23 | maxByte++; // Overflow wraps 127 -> -128 |
| 24 | System.out.println("Byte overflow (127 + 1): " + maxByte); |
| 25 | |
| 26 | float rate = 7.5f; // 'f' suffix required for float literals |
| 27 | long bigNum = 3_000_000_000L; // 'L' suffix required beyond int range |
| 28 | System.out.println("Float: " + rate + ", Long: " + bigNum); |
| 29 | } |
| 30 | } |
Defaults -> byte: 0, int: 0, double: 0.0, boolean: false, String: null Incremented char: B Byte overflow (127 + 1): -128 Float: 7.5, Long: 3000000000
byteshortintlongfloatdoublecharboolean- Writing
float f = 12.34;withoutf(compile error: possible lossy conversion from double to float). - Using
if (1)orboolean flag = 1;like in C (illegal in Java;booleanaccepts onlytrue/false). - Printing an uninitialized local variable inside
main.
Comparison Tables
| Property | Local Variable | Instance Variable | Static Variable |
|---|---|---|---|
| Declaration | Inside method / block / constructor | Inside class, outside methods | Inside class with static |
| Memory Area | JVM Stack | Heap (per object) | Method Area (1 shared copy) |
| Default Value | None (Compile error if unread) | Yes (0, 0.0, false, null) | Yes (0, 0.0, false, null) |
| Access Modifiers | Not allowed | Allowed (private, public, etc.) | Allowed (private, public, etc.) |
| Lifetime | Duration of method/block call | Until object is garbage collected | Entire class lifetime |
Real-World Applications
- Choosing
byte/shortin embedded telemetry or large numeric arrays saves significant RAM. longtimestamps (System.currentTimeMillis()) prevent year-2038 32-bit overflow.
Important KTU Exam Points
- Remember
charin Java is 2 bytes (16-bit Unicode), NOT 1 byte like in C. - Remember
booleancannot be cast to or fromint. - Always mention that local variables have NO default value while instance/static variables do.
Memory Techniques & Revision
- 8 Primitives = '4 Ints, 2 Floats, 1 Char, 1 Bool' ->
byte(1), short(2), int(4), long(8)|float(4), double(8)|char(2)|boolean(1 bit).
Common Pitfalls to Avoid
- Writing
08or09in code — Java treats numbers starting with0as Octal (digits 0–7 only), causing a compile error! - Forgetting
Lon large integer literals exceeding 2.14 billion.
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
- Integers:
byte(1 byte, 0),short(2 bytes, 0),int(4 bytes, 0),long(8 bytes, 0L). - Floating-point:
float(4 bytes, 0.0f),double(8 bytes, 0.0d). - Character & Logical:
char(2 bytes Unicode,'\u0000'),boolean(logical 1 bit,false).
Quick Understanding Check
1. What happens if you declare int x; inside main() and immediately print x?
2. Why does float price = 99.5; fail to compile in Java?