Skip to main content

Java Basics

Data Types & I/O

Complete lesson for Data Types & I/O using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Data Types & I/O

Section: Java Basics. Eight primitives, reference types, size and range, casting, and console I/O with System.out and Scanner.

What is a data type?

  • A data type tells the compiler what a variable can store and which operations are legal.
  • Java splits types into primitives (8 built-in value types) and references (classes, arrays, interfaces, enums, records).
  • String looks like a primitive in other languages, but in Java it is a class (java.lang.String).
  • Pick the smallest type that is still safe: int for everyday counts, long for big integers, double for science, boolean for flags, String for text.

Primitive types

  • Eight primitives: byte, short, int, long, float, double, char, boolean. They are not objects and have no methods.
  • Integer literals are int by default; use L for long. Floating literals are double by default; use f for float.
  • char is an unsigned 16-bit UTF-16 code unit, not a full Unicode code point (supplementary characters need two chars).
  • boolean is only true or false — not 0/1 like C. void is not a variable type; it only marks “no return value”.
TypeSizeRange / notesDefault (fields)
byte8-bit (1 byte)-128 to 1270
short16-bit (2 bytes)-32,768 to 32,7670
int32-bit (4 bytes)≈ ±2.1 billion; default integer0
long64-bit (8 bytes)huge integers; suffix L0L
float32-bit IEEE (4 bytes)≈ 6–7 digits; suffix f0.0f
double64-bit IEEE (8 bytes)≈ 15 digits; default floating type0.0
char16-bit (2 bytes)0 to 65535 (UTF-16 code unit)'\u0000'
booleanJVM-definedtrue / false onlyfalse

Java data types overview

Java has eight primitives plus reference types. The poster below groups the integer family, floating types, char, boolean, void (return-only), then String, arrays, and class objects. Remember: String is a class, not a ninth primitive.

Java data types infographic: integer family byte short int long, floating types float and double, char, boolean, void as a method return, String as a reference, arrays, and class objects, with sizes and example declarations.
Java data types — eight primitives, then String, arrays, and objects as references
  • Integers: byte 1, short 2, int 4, long 8 bytes.
  • Floating: float (f) and double (default).
  • char / boolean: UTF-16 code unit; true/false only.
  • References: String, arrays, and class instances live on the heap.

Reference types and local vs field defaults

  • Classes (String, Scanner, your own types), arrays, interfaces, enums, and records are references. The variable holds an address-like handle, not the object bytes.
  • Uninitialized fields get defaults: 0, 0.0, false, and the NUL character for primitives; null for references.
  • Local variables have no default — you must assign before use or javac fails.
  • var (Java 10+) infers a local type from the initializer: var name = "Ada"; is String. You cannot write var x; with no initializer, and var is not allowed for fields.

Console output and Scanner input

  • System.out.print / println / printf write to standard output. println adds a line break; printf uses format specifiers (%s, %d, %f, %n).
  • Scanner in java.util reads tokens from System.in. Close it only if you own the stream; closing System.in is often a mistake in tiny demos.
  • nextInt() / nextDouble() / next() read one token. nextLine() reads the rest of the current line (including spaces).
import java.util.Scanner;

public class IoDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Age: ");
        int age = sc.nextInt();
        sc.nextLine(); // consume leftover newline
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.printf("%s is %d years old%n", name, age);
        sc.close();
    }
}

Widening vs narrowing conversion

  • Widening (byte → short → int → long → float → double) is implicit and safe.
  • Narrowing (double → int, int → byte) needs a cast and may lose data. (int) 9.99 is 9 (truncates toward zero).
  • Integer overflow wraps silently (Integer.MAX_VALUE + 1 is Integer.MIN_VALUE). Floating overflow becomes Infinity.
  • char can widen to int (its code unit). Casting a large int back to char keeps only 16 bits.
L2

Advanced — Data Types & I/O

Scanner pitfalls and numeric precision

  • nextInt() does not consume the line ending. Mixing nextInt() and nextLine() is a classic bug — call nextLine() to clear the rest of the line.
  • next() reads one token (whitespace-delimited); nextLine() reads the rest of the line.
  • float/double are binary floating point — 0.1 + 0.2 is not exactly 0.3. Use BigDecimal for money.
  • Never use == to compare doubles for equality in real code; compare with an epsilon or Double.compare.

Wrapper classes, boxing, and String

  • Each primitive has a wrapper: Byte, Short, Integer, Long, Float, Double, Character, Boolean. Wrappers are reference types (can be null).
  • Autoboxing (Java 5+): Integer n = 10; boxes an int. Unboxing: int x = n;. Unboxing null throws NullPointerException.
  • String is immutable. + concatenates and is the only operator overload you get in Java.
  • Integer.parseInt("42") / Double.parseDouble("3.14") convert text. Bad text throws NumberFormatException.
PrimitiveWrapperUseful members
intIntegerparseInt, MIN_VALUE, MAX_VALUE
longLongparseLong, MAX_VALUE
doubleDoubleparseDouble, isNaN
charCharacterisDigit, isLetter, toUpperCase
booleanBooleanparseBoolean

Type promotion in expressions

  • byte, short, and char are promoted to int in arithmetic. byte a = 1; byte b = 2; byte c = (byte)(a + b); — the cast is required.
  • If either operand is long/float/double, the other is widened to that type.
  • printf specifiers must match: %d for int, %f for floating, %s for String, %c for char, %b for boolean, %n for newline.
L3

Tricky Interview Points

Q1) How many primitive types does Java have?

Answer Eight: byte, short, int, long, float, double, char, boolean. String is a class, not a primitive. void is not a variable type.

Q2) What is the default value of a local int?

Answer There is none. Locals must be assigned before use. Fields of type int default to 0.

Q3) Why do we write 10L and 1.5f?

Answer Integer literals are int; 10L is long. Floating literals are double; 1.5f is float so it can be assigned to a float variable without a cast.

Q4) Is char signed?

Answer No. char is an unsigned 16-bit UTF-16 code unit (0 to 65535).

Q5) What is the difference between a primitive and a reference?

Answer A primitive holds the value itself (int x = 5). A reference holds a handle to an object on the heap (String s = "hi"). References can be null; primitives cannot.

Q6) What is the difference between print and println?

Answer println appends a newline (the system line separator). print does not. printf uses format specifiers and %n for a portable newline.

Q7) Why does nextLine() return empty after nextInt()?

Answer nextInt() leaves the newline in the buffer. The following nextLine() consumes that empty remainder. Call an extra nextLine() to clear it.

Q8) What is autoboxing?

Answer Automatic conversion between a primitive and its wrapper, for example int to Integer. Unboxing a null wrapper throws NullPointerException.

Q9) Why is (byte)130 not 130?

Answer byte range is -128 to 127. Casting 130 keeps only 8 bits and wraps (typically to -126). Narrowing can silently lose magnitude.

Q10) Why is 0.1 + 0.2 not equal to 0.3?

Answer float and double are binary IEEE values; many decimals have no exact representation. Use BigDecimal for money and an epsilon for scientific compares.

Q11) Can you declare var x; without an initializer?

Answer No. var needs an initializer so the compiler can infer the type. It also cannot be used for fields or method parameters.

Q12) Is String a primitive?

Answer No. String is a class in java.lang. It is a reference type, immutable, and supports + for concatenation.

L4

Simple Programs

Primitives, cast, and formatted output

public class TypesDemo {
    public static void main(String[] args) {
        int whole = 10;
        double widened = whole;      // implicit
        int truncated = (int) 9.99;  // 9
        long big = 3_000_000_000L;
        System.out.println(widened);
        System.out.println(truncated);
        System.out.println(big);
    }
}

Read two numbers and print the sum

import java.util.Scanner;

public class SumInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println("sum = " + (a + b));
        sc.close();
    }
}

Print primitive ranges

public class TypeRanges {
    public static void main(String[] args) {
        System.out.println("byte  " + Byte.MIN_VALUE + " .. " + Byte.MAX_VALUE);
        System.out.println("int   " + Integer.MIN_VALUE + " .. " + Integer.MAX_VALUE);
        System.out.println("long  " + Long.MIN_VALUE + " .. " + Long.MAX_VALUE);
        System.out.println("char  0 .. " + (int) Character.MAX_VALUE);
    }
}

Scanner: number then a full name

import java.util.Scanner;

public class NameAge {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Age: ");
        int age = sc.nextInt();
        sc.nextLine();
        System.out.print("Full name: ");
        String name = sc.nextLine();
        System.out.printf("%s, age %d%n", name, age);
        sc.close();
    }
}
L5

Problem Solving Tricks

  • Prefer int for whole numbers unless you need long range. Prefer double for science; BigDecimal for currency.
  • After nextInt() / nextDouble(), call nextLine() before reading a full line.
  • printf("%n") is portable; "\n" is always LF.
  • var only works for locals with initializers — not for fields or method parameters.
  • Memorise the eight primitives; then add “String is a class” — that pair is a very common MCQ.
  • Wrapper constants such as Integer.MAX_VALUE beat magic numbers in range questions.
  • byte a = 1; byte b = 2; byte c = a + b; fails — a + b is int. Cast the result.
  • Do not close System.in in a method if later code still needs keyboard input.
L6

Practice Programs List

  1. Print the min and max of every primitive using Integer.MIN_VALUE, Byte.MAX_VALUE, and so on.
  2. Read a first name and age, then print a sentence with printf.
  3. Cast 130 to byte and explain the wrap-around result.
  4. Show that 0.1 + 0.2 == 0.3 is false and print both sides.
  5. Write a program that mixes nextInt and nextLine correctly.
  6. Declare one variable of each primitive plus a String and print them with printf.
  7. Box an int into Integer, then unbox it; try unboxing null and catch the NPE.
  8. Parse "42" and "3.14" with Integer.parseInt / Double.parseDouble.
  9. Assign int to double (widening) and double to int with a cast (narrowing).
  10. Sketch primitives vs references: what lives in the stack frame vs the heap?