Java Buzzwords
Java was designed with specific goals that make it unique. These goals are described as Java's Buzzwords:
| Buzzword | Meaning |
|---|---|
| Simple | Syntax similar to C/C++ but without complex features like pointers and operator overloading |
| Object-Oriented | Everything in Java is an object; supports all OOP features |
| Platform Independent | Write Once, Run Anywhere (WORA) — bytecode runs on any JVM |
| Secured | No explicit pointers; bytecode verification; security manager |
| Robust | Strong exception handling; no pointer arithmetic; automatic garbage collection |
| Architecture Neutral | Bytecode is not specific to any processor architecture |
| Portable | Platform-independent + architecture-neutral = portable |
| High Performance | JIT (Just-In-Time) compiler converts bytecode to native code at runtime |
| Distributed | Supports networking protocols; RMI; enterprise distribution |
| Multi-threaded | Built-in support for multithreading |
| Dynamic | Classes loaded dynamically at runtime; supports runtime polymorphism |
Data Types
Java is a strongly typed language — every variable must have a declared type.
Primitive Data Types (8 types)
| Type | Size | Range | Default | Example |
|---|---|---|---|---|
| byte | 1 byte (8 bits) | -128 to 127 | 0 | byte b = 10; |
| short | 2 bytes | -32768 to 32767 | 0 | short s = 500; |
| int | 4 bytes | -2^31 to 2^31-1 | 0 | int i = 1000; |
| long | 8 bytes | -2^63 to 2^63-1 | 0L | long l = 100L; |
| float | 4 bytes | ~±3.4×10^38 | 0.0f | float f = 3.14f; |
| double | 8 bytes | ~±1.8×10^308 | 0.0d | double d = 3.14; |
| char | 2 bytes | 0 to 65535 (Unicode) | '\u0000' | char c = 'A'; |
| boolean | 1 bit | true / false | false | boolean flag = true; |
char (2 bytes), unlike C/C++ which uses ASCII (1 byte). This is why Java supports international character sets.Variables
Types of Variables in Java
| Type | Declared Inside | Default Value | Lifetime |
|---|---|---|---|
| Local Variable | Method / Block | No default — must initialize | Until method exits |
| Instance Variable | Class (no static) | Has default (0, null, false) | Until object is GC'd |
| Static Variable | Class (with static) | Has default | Until class is unloaded |
class Example {
static int count = 0; // static variable — shared by all objects
int id; // instance variable — per object
void show() {
int local = 10; // local variable — must be initialized
System.out.println(local);
}
}Operators
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | a + b, a % b |
| Relational | == != < > <= >= | a == b, a < b |
| Logical | && || ! | a&&b, !flag |
| Bitwise | & | ^ ~ << >> >>> | a & b, a << 2 |
| Assignment | = += -= *= /= %= | a += 5 |
| Ternary | ? : | max = (a>b) ? a : b |
| Increment/Decrement | ++ -- | a++, --b |
&&, if the left operand is false, the right side is NOT evaluated. In ||, if left is true, right is skipped.Control Structures
// if-else
if (marks >= 60) {
System.out.println("Pass");
} else if (marks >= 35) {
System.out.println("Compartment");
} else {
System.out.println("Fail");
}
// switch
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other");
}
// for loop
for (int i = 0; i < 5; i++) { System.out.print(i + " "); }
// while
while (n > 0) { sum += n % 10; n /= 10; }
// do-while (executes at least once)
do { System.out.println("Entered"); } while (false);Arrays
An array is a collection of elements of the same type stored in contiguous memory locations.
// 1D Array
int[] marks = new int[5]; // declaration + creation
int[] scores = {85, 92, 78, 95, 88}; // declaration + init
// Enhanced for loop
for (int s : scores) {
System.out.print(s + " ");
}
// 2D Array
int[][] matrix = new int[3][3];
int[][] grid = {{1,2,3}, {4,5,6}, {7,8,9}};array.length gives the size. Array index starts at 0.Console I/O
import java.util.Scanner;
public class ConsoleDemo {
public static void main(String[] args) {
// Input using Scanner
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter age: ");
int age = sc.nextInt();
// Output
System.out.println("Hello, " + name + "! Age: " + age);
System.out.printf("Formatted: %s is %d years old%n", name, age);
sc.close();
}
}
Type Casting
Type casting is converting a value from one data type to another. Java supports two kinds of casting:
1. Widening Conversion (Implicit / Automatic)
The smaller type is automatically promoted to a larger type. No data loss occurs. Java does this automatically.
// Widening: byte → short → int → long → float → double
byte b = 10;
short s = b; // byte to short — automatic
int i = s; // short to int — automatic
long l = i; // int to long — automatic
float f = l; // long to float — automatic
double d = f; // float to double — automatic
System.out.println(d); // Output: 10.0
2. Narrowing Conversion (Explicit / Manual)
The larger type must be explicitly cast to a smaller type. Data loss may occur. You must use the cast operator (type).
// Narrowing: double → float → long → int → short → byte
double d = 9.99;
int i = (int) d; // explicit cast — fractional part lost
System.out.println(i); // Output: 9 (not 10 — truncated, not rounded)
int big = 130;
byte small = (byte) big; // 130 overflows byte range (-128 to 127)
System.out.println(small); // Output: -126 (bit truncation)
3. Type Promotion in Expressions
Java automatically promotes smaller types to int when used in arithmetic expressions.
byte a = 40, b = 50;
byte c = (byte)(a + b); // a+b produces int, so explicit cast needed
char ch = 'A';
int val = ch + 1; // 'A' (65) + 1 = 66 — char promoted to int
System.out.println(val); // Output: 66
System.out.println((char) val); // Output: B
4. Casting Between char and int
char and int are interchangeable via casting — Java stores characters as their Unicode (ASCII) numeric values.
// char → int (widening, automatic)
char ch = 'A';
int code = ch;
System.out.println(code); // Output: 65 (ASCII of 'A')
// int → char (narrowing, explicit)
int n = 66;
char c = (char) n;
System.out.println(c); // Output: B
// Alphabet traversal using int-to-char casting
for (int i = 65; i <= 90; i++) {
System.out.print((char) i + " ");
}
// Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
5. Real-World Example — Grade Calculator
public class GradeCalc {
public static void main(String[] args) {
int totalMarks = 456;
int subjects = 5;
// int division gives int — fractional part lost
int wrongAvg = totalMarks / subjects;
System.out.println("Wrong avg: " + wrongAvg); // 91 (not 91.2)
// Cast one operand to double to get accurate result
double correctAvg = (double) totalMarks / subjects;
System.out.println("Correct avg: " + correctAvg); // 91.2
// Narrow back to int for display (truncates decimal)
int displayAvg = (int) correctAvg;
System.out.println("Display avg: " + displayAvg); // 91
}
}
6. Overflow Behaviour During Narrowing
When a value is too large for the target type, Java wraps around (modulo arithmetic) — it does NOT throw an exception.
int val = 257;
byte b = (byte) val;
System.out.println(b); // Output: 1 (257 % 256 = 1)
int val2 = 300;
byte b2 = (byte) val2;
System.out.println(b2); // Output: 44 (300 - 256 = 44)
double pi = 3.99999;
int i = (int) pi;
System.out.println(i); // Output: 3 (truncated, NOT rounded)
7. Casting in Mixed-Type Arithmetic
int a = 7, b = 2;
// Both int — result is int
System.out.println(a / b); // 3
// Cast numerator — result is double
System.out.println((double) a / b); // 3.5
// Cast denominator — result is double
System.out.println(a / (double) b); // 3.5
// Cast result (wrong!) — division already done as int
System.out.println((double)(a / b)); // 3.0 (NOT 3.5)
(double)(a/b) does NOT give a decimal result — the integer division happens first, then the result is cast. Always cast at least one operand: (double)a / b.byte and short are always promoted to int.| Type | Direction | Cast Required? | Data Loss? |
|---|---|---|---|
| Widening | small → large (e.g. int→long) | No — automatic | No |
| Narrowing | large → small (e.g. double→int) | Yes — explicit (type) | Possible |
Wrapper Classes
Java primitives (int, char, etc.) are not objects. Wrapper classes wrap a primitive value inside an object, making them compatible with Java's object-oriented features (Collections, Generics, etc.).
Primitive vs Wrapper Class
| Primitive | Wrapper Class | Package |
|---|---|---|
| byte | Byte | java.lang |
| short | Short | java.lang |
| int | Integer | java.lang |
| long | Long | java.lang |
| float | Float | java.lang |
| double | Double | java.lang |
| char | Character | java.lang |
| boolean | Boolean | java.lang |
Autoboxing and Unboxing
Autoboxing is the automatic conversion of a primitive to its wrapper object. Unboxing is the reverse — wrapper object to primitive. Java does both automatically (since Java 5).
// Autoboxing — primitive int automatically wrapped into Integer object
int x = 42;
Integer obj = x; // autoboxing: int → Integer
// Unboxing — Integer object automatically unwrapped to int
int y = obj; // unboxing: Integer → int
// Common use: storing primitives in a Collection
java.util.ArrayList<Integer> list = new java.util.ArrayList<>();
list.add(10); // autoboxing happens here automatically
int val = list.get(0); // unboxing happens here automatically
Useful Wrapper Class Methods
// Parsing strings to primitives
int a = Integer.parseInt("123"); // String → int
double d = Double.parseDouble("3.14"); // String → double
boolean b = Boolean.parseBoolean("true");
// Converting primitives to String
String s1 = Integer.toString(42); // int → String
String s2 = String.valueOf(3.14); // any type → String
// Useful constants
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
System.out.println(Integer.toBinaryString(10)); // "1010"
System.out.println(Integer.toHexString(255)); // "ff"
System.out.println(Character.isDigit('5')); // true
System.out.println(Character.isLetter('A')); // true
System.out.println(Character.toUpperCase('a')); // A
ArrayList and HashMap can only store objects, not primitives. Wrapper classes bridge this gap — ArrayList<Integer> works; ArrayList<int> does not.null. Unboxing a null wrapper causes a NullPointerException at runtime. Always check for null before unboxing.Download PDF Notes
Save these notes as a PDF for offline reference