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.
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).
Stringlooks like a primitive in other languages, but in Java it is a class (java.lang.String).- Pick the smallest type that is still safe:
intfor everyday counts,longfor big integers,doublefor science,booleanfor flags,Stringfor text.
Primitive types
- Eight primitives:
byte,short,int,long,float,double,char,boolean. They are not objects and have no methods. - Integer literals are
intby default; useLforlong. Floating literals aredoubleby default; usefforfloat. charis an unsigned 16-bit UTF-16 code unit, not a full Unicode code point (supplementary characters need twochars).booleanis onlytrueorfalse— not0/1like C.voidis not a variable type; it only marks “no return value”.
| Type | Size | Range / notes | Default (fields) |
|---|---|---|---|
byte | 8-bit (1 byte) | -128 to 127 | 0 |
short | 16-bit (2 bytes) | -32,768 to 32,767 | 0 |
int | 32-bit (4 bytes) | ≈ ±2.1 billion; default integer | 0 |
long | 64-bit (8 bytes) | huge integers; suffix L | 0L |
float | 32-bit IEEE (4 bytes) | ≈ 6–7 digits; suffix f | 0.0f |
double | 64-bit IEEE (8 bytes) | ≈ 15 digits; default floating type | 0.0 |
char | 16-bit (2 bytes) | 0 to 65535 (UTF-16 code unit) | '\u0000' |
boolean | JVM-defined | true / false only | false |
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.
- Integers:
byte1,short2,int4,long8 bytes. - Floating:
float(f) anddouble(default). - char / boolean: UTF-16 code unit;
true/falseonly. - 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;nullfor references. - Local variables have no default — you must assign before use or
javacfails. var(Java 10+) infers a local type from the initializer:var name = "Ada";isString. You cannot writevar x;with no initializer, andvaris not allowed for fields.
Console output and Scanner input
System.out.print/println/printfwrite to standard output.printlnadds a line break;printfuses format specifiers (%s,%d,%f,%n).Scannerinjava.utilreads tokens fromSystem.in. Close it only if you own the stream; closingSystem.inis 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.99is9(truncates toward zero). - Integer overflow wraps silently (
Integer.MAX_VALUE + 1isInteger.MIN_VALUE). Floating overflow becomesInfinity. charcan widen toint(its code unit). Casting a largeintback tocharkeeps only 16 bits.
Advanced — Data Types & I/O
Scanner pitfalls and numeric precision
nextInt()does not consume the line ending. MixingnextInt()andnextLine()is a classic bug — callnextLine()to clear the rest of the line.next()reads one token (whitespace-delimited);nextLine()reads the rest of the line.float/doubleare binary floating point —0.1 + 0.2is not exactly0.3. UseBigDecimalfor money.- Never use
==to compare doubles for equality in real code; compare with an epsilon orDouble.compare.
Wrapper classes, boxing, and String
- Each primitive has a wrapper:
Byte,Short,Integer,Long,Float,Double,Character,Boolean. Wrappers are reference types (can benull). - Autoboxing (Java 5+):
Integer n = 10;boxes anint. Unboxing:int x = n;. UnboxingnullthrowsNullPointerException. Stringis immutable.+concatenates and is the only operator overload you get in Java.Integer.parseInt("42")/Double.parseDouble("3.14")convert text. Bad text throwsNumberFormatException.
| Primitive | Wrapper | Useful members |
|---|---|---|
int | Integer | parseInt, MIN_VALUE, MAX_VALUE |
long | Long | parseLong, MAX_VALUE |
double | Double | parseDouble, isNaN |
char | Character | isDigit, isLetter, toUpperCase |
boolean | Boolean | parseBoolean |
Type promotion in expressions
byte,short, andcharare promoted tointin 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. printfspecifiers must match:%dforint,%ffor floating,%sforString,%cforchar,%bforboolean,%nfor newline.
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.
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();
}
} Problem Solving Tricks
- Prefer
intfor whole numbers unless you needlongrange. Preferdoublefor science;BigDecimalfor currency. - After
nextInt()/nextDouble(), callnextLine()before reading a full line. printf("%n")is portable;"\n"is always LF.varonly 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_VALUEbeat magic numbers in range questions. byte a = 1; byte b = 2; byte c = a + b;fails —a + bisint. Cast the result.- Do not close
System.inin a method if later code still needs keyboard input.
Practice Programs List
- Print the min and max of every primitive using
Integer.MIN_VALUE,Byte.MAX_VALUE, and so on. - Read a first name and age, then print a sentence with
printf. - Cast
130tobyteand explain the wrap-around result. - Show that
0.1 + 0.2 == 0.3is false and print both sides. - Write a program that mixes
nextIntandnextLinecorrectly. - Declare one variable of each primitive plus a
Stringand print them withprintf. - Box an
intintoInteger, then unbox it; try unboxingnulland catch the NPE. - Parse
"42"and"3.14"withInteger.parseInt/Double.parseDouble. - Assign
inttodouble(widening) anddoubletointwith a cast (narrowing). - Sketch primitives vs references: what lives in the stack frame vs the heap?