Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 2: Data Types, Variables, Operators & Type Casting

Lesson 3 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

2.1 The Eight Primitive Types

Java is statically and strongly typed: every variable has a compile-time type that cannot silently change.

TypeSizeRangeDefaultWrapper
byte8 bits−128 to 1270Byte
short16 bits−32,768 to 32,7670Short
int32 bits−2³¹ to 2³¹−1 (~±2.14 billion)0Integer
long64 bits−2⁶³ to 2⁶³−10LLong
float32 bits~±3.4×10³⁸ (6-7 digits precision)0.0fFloat
double64 bits~±1.7×10³⁰⁸ (15 digits precision)0.0Double
char16 bits0 to 65,535 (unsigned Unicode)'\u0000'Character
booleanJVM-dependenttrue / falsefalseBoolean

Traps: char is the only unsigned numeric type. Defaults apply only to fields; local variables must be initialized before use or the compiler rejects the code ("variable might not have been initialized").

2.2 Variables & Literals

Three kinds of variables: local (inside methods — stack), instance (per object — heap), static (per class — method area).

Literal niceties examiners test: 0b1010 (binary), 017 (octal — decimal 15, a classic trap!), 0xFF (hex), 1_00_000 (underscores for readability), 10L, 3.14f, 'A', "text". Since Java 10, var infers local-variable types (var list = new ArrayList<String>();) — still statically typed, just inferred.

2.3 Type Casting & Promotion

Widening (implicit, safe): byte → short → int → long → float → double, and char → int. No cast needed.

Narrowing (explicit, lossy): requires a cast and may truncate:

int big = 130;
byte b = (byte) big;      // 130 overflows byte range
System.out.println(b);    // -126  (130 - 256)
double d = 9.99;
int i = (int) d;          // 9 — fraction TRUNCATED, not rounded

Automatic promotion rules (very high-yield):

  1. In any arithmetic, byte, short, char are promoted to int first.
  2. If one operand is long/float/double, the whole expression is promoted to that type.
byte x = 10, y = 20;
// byte z = x + y;        // COMPILE ERROR: x + y is int
byte z = (byte)(x + y);   // OK
char c = 'A';
System.out.println(c + 1);        // 66  (int arithmetic)
System.out.println((char)(c + 1)); // B

2.4 Operators & Precedence

Precedence (high → low)Operators
Postfix / Prefixx++ x-- / ++x --x ! ~
Multiplicative* / %
Additive+ -
Shift<< >> >>>
Relational< <= > >= instanceof
Equality== !=
Bitwise& then ^ then ``
Logical&& then ``
Ternary?:
Assignment= += -= *= /= %=

Traps:

  • 10 / 3 is 3 (integer division); 10 % 3 is 1; -7 % 3 is -1 (sign follows dividend).
  • &&/|| short-circuit (right side may never run); &/| always evaluate both sides.
  • >> keeps the sign bit (arithmetic shift); >>> fills with zeros (-8 >>> 1 is a huge positive number).
  • i = i++; leaves i unchanged — the old value is assigned back. Explain-the-output favourite.
  • 0.1 + 0.2 == 0.3 is false (binary floating point). Use BigDecimal for money.

2.5 Reading Input with Scanner

Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine();                  // consume the leftover newline!
String name = sc.nextLine();

Trap: calling nextLine() right after nextInt() returns an empty string unless you consume the pending newline first — a favourite viva question.

🎯 Exam Focus

  1. List all eight primitive data types with their sizes, ranges and default values.
  2. Distinguish between implicit widening and explicit narrowing conversion with examples. What is the output of casting int 130 to byte?
  3. Explain automatic type promotion in expressions. Why does byte z = x + y; fail to compile when x and y are bytes?
  4. Differentiate && and &, and >> and >>>, with examples.
  5. Predict the output: int i = 5; i = i++ + ++i; — justify each step.
  6. Write a program that reads a temperature in Celsius using Scanner and prints Fahrenheit, demonstrating at least one explicit cast.