Java · Programming Basics
Basics of Java Programming You Must Know
Quick summary — basics of Java programming
Java is one of the most widely used programming languages, powering Android apps, enterprise backends, and large-scale systems. Learning its basics means understanding variables, data types, control flow, methods, classes, objects, exceptions, and collections — the foundation of everything you'll build.
In this guide you will learn:
- Core syntax — variables, data types, operators, control flow.
- Methods & arrays — organising and storing data.
- Object-oriented programming — classes, objects, inheritance, polymorphism.
- Exceptions — handling errors gracefully.
- Collections — lists, sets, maps for real programs.
SECTION 01Overview — why Java still matters
Java has been around for decades and remains one of the most in-demand languages. Here's why it's still worth learning:
| Reason | What It Means | Career Impact |
|---|---|---|
| Enterprise standard | Banking, insurance, and large systems run on Java | Huge job market in India and globally |
| Android development | The traditional official language for Android | Mobile dev opportunities |
| Strongly typed | Catches errors at compile time | Better code quality, easier debugging |
| Mature ecosystem | Spring Boot, Hibernate, JUnit, and more | Stable, well-documented tooling |
| Cross-platform | "Write once, run anywhere" via the JVM | Deploy the same code on any OS |
SECTION 02Core syntax — variables, data types, control flow
Every Java program starts with these fundamentals:
| Topic | What You Learn | Example |
|---|---|---|
| Hello World | Structure of a Java program | public class Main { ... } |
| Variables | Declaring and using values | int age = 30; |
| Data types | Primitive and reference types | int, double, boolean, String |
| Operators | Arithmetic, comparison, logical | +, -, ==, && |
| If / else | Conditional logic | if (x > 0) { ... } |
| Switch | Multiple-choice branching | switch (day) { case 1: ... } |
| Loops | Repeating code: for, while, do-while | for (int i = 0; i < 10; i++) |
// Hello World + variables in Java
public class Main {
public static void main(String[] args) {
// Primitive data types
int age = 30;
double price = 199.99;
boolean isActive = true;
char grade = 'A';
// Reference type
String name = "Ada";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Active:" + isActive);
System.out.println("Grade: " + grade);
}
}
// Control flow in Java
public class ControlFlow {
public static void main(String[] args) {
int score = 78;
// if / else if / else
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
// switch
int day = 3;
switch (day) {
case 1: System.out.println("Mon"); break;
case 2: System.out.println("Tue"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("Other");
}
// for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// while loop
int n = 3;
while (n > 0) {
System.out.println("n = " + n);
n--;
}
}
}
SECTION 03Methods & arrays
Methods organise logic, and arrays store multiple values of the same type:
| Concept | What You Learn | Example |
|---|---|---|
| Method declaration | Defining reusable blocks of code | static int add(int a, int b) |
| Return values | Methods can return a value | return a + b; |
| Parameters | Methods accept inputs | add(2, 3) |
| Arrays | Fixed-size collections of values | int[] nums = {1, 2, 3}; |
| Looping over arrays | Traversing array elements | for (int n : nums) { ... } |
| Multi-dimensional arrays | Grids and matrices | int[][] grid = new int[3][3]; |
// Methods in Java
public class Methods {
// Static method with parameters and return value
static int add(int a, int b) {
return a + b;
}
// Void method with no return value
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with a loop and condition
static int sumEven(int[] nums) {
int total = 0;
for (int n : nums) {
if (n % 2 == 0) total += n;
}
return total;
}
public static void main(String[] args) {
System.out.println(add(2, 3)); // 5
greet("Ada"); // Hello, Ada!
System.out.println(sumEven(
new int[]{1, 2, 3, 4})); // 6
}
}
// Arrays in Java
public class ArraysDemo {
public static void main(String[] args) {
// Declare and initialise
int[] scores = {90, 85, 78, 92};
String[] names = {"Ada", "Linus", "Grace"};
// Indexing (0-based)
System.out.println(scores[0]); // 90
System.out.println(names[1]); // Linus
// Length
System.out.println(scores.length); // 4
// Loop with index
for (int i = 0; i < scores.length; i++) {
System.out.println(i + ": " + scores[i]);
}
// Enhanced for loop
for (int s : scores) {
System.out.println("Score: " + s);
}
// 2D array
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
};
System.out.println(grid[1][2]); // 6
}
}
SECTION 04Object-oriented programming — the four pillars
Java is an OOP language. Understanding these four concepts is essential:
| Pillar | What It Means | Java Example |
|---|---|---|
| Encapsulation | Hide internal details, expose a clean API | Private fields with getters/setters |
| Inheritance | Reuse common code across related classes | class Dog extends Animal |
| Polymorphism | Same method, different behaviour | Method overriding, interfaces |
| Abstraction | Focus on what, not how | Abstract classes and interfaces |
// Classes and objects in Java
public class Person {
// Encapsulation — private fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Public methods (the API)
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void greet() {
System.out.println("Hi, I'm " + name);
}
}
class Main {
public static void main(String[] args) {
Person p = new Person("Ada", 30);
p.greet(); // Hi, I'm Ada
System.out.println(p.getAge()); // 30
}
}
// Inheritance in Java
class Animal {
protected String name;
Animal(String name) {
this.name = name;
}
void speak() {
System.out.println(name + " makes a sound");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
// Method overriding (polymorphism)
@Override
void speak() {
System.out.println(name + " barks");
}
}
class Main {
public static void main(String[] args) {
Animal a = new Dog("Bruno");
a.speak(); // Bruno barks
}
}
// Interfaces in Java
interface Shape {
double area();
}
class Circle implements Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
class Square implements Shape {
private double side;
Square(double side) {
this.side = side;
}
@Override
public double area() {
return side * side;
}
}
class Main {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(2),
new Square(3),
};
for (Shape s : shapes) {
System.out.printf("Area: %.2f%n", s.area());
}
}
}
Shape interface
with Circle and Square implementations is a
classic, memorable choice.
SECTION 05Exceptions — handling errors
Java uses exceptions to handle errors instead of crashing. Here's what you need to know:
| Concept | What It Means | Example |
|---|---|---|
| try / catch | Run code, handle errors | try { ... } catch (Exception e) { ... } |
| finally | Runs whether an exception occurs or not | Closing resources |
| Checked exceptions | Must be caught or declared | IOException |
| Unchecked exceptions | Runtime exceptions, optional to catch | NullPointerException |
| Custom exceptions | Define your own error types | class MyException extends Exception { } |
| throw / throws | Signal an error, declare it in method signature | throws IOException |
// try / catch / finally in Java
public class ExceptionsDemo {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
try {
int result = 10 / 0; // ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} finally {
System.out.println("This always runs.");
}
// Safe index access
try {
System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds.");
}
}
}
// Custom exception + checked exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String msg) {
super(msg);
}
}
public class CustomExceptionDemo {
static void registerUser(String name, int age)
throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException(
"Age must be 18 or older: " + age
);
}
System.out.println("Registered: " + name);
}
public static void main(String[] args) {
try {
registerUser("Ada", 17);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
SECTION 06Collections — lists, sets, maps
Arrays are fixed-size. Java's collections framework gives you flexible, powerful data structures:
| Interface | What It Does | Common Implementation |
|---|---|---|
| List | Ordered collection, allows duplicates | ArrayList, LinkedList |
| Set | Unordered collection, no duplicates | HashSet, TreeSet |
| Map | Key-value pairs | HashMap, TreeMap |
| Queue | FIFO ordering | ArrayDeque, PriorityQueue |
| Iterator | Traverse any collection uniformly | Iterator<T> |
| Streams (basics) | Functional style on collections | list.stream().filter(...) |
// List and Set in Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListSetDemo {
public static void main(String[] args) {
// List — ordered, duplicates allowed
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Linus");
names.add("Ada"); // duplicate OK
System.out.println(names); // [Ada, Linus, Ada]
System.out.println(names.get(1)); // Linus
// Set — unordered, no duplicates
Set<String> unique = new HashSet<>();
unique.add("Ada");
unique.add("Linus");
unique.add("Ada"); // ignored
System.out.println(unique); // [Ada, Linus]
System.out.println(unique.contains("Ada")); // true
}
}
// Map in Java — key-value pairs
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 30);
ages.put("Linus", 25);
ages.put("Grace", 35);
// Access
System.out.println(ages.get("Ada")); // 30
// Update
ages.put("Ada", 31);
// Check
System.out.println(ages.containsKey("Linus")); // true
// Iterate
for (Map.Entry<String, Integer> e : ages.entrySet()) {
System.out.println(e.getKey() + " → " + e.getValue());
}
// Default value
int val = ages.getOrDefault("Nobody", -1);
System.out.println(val); // -1
}
}
// Streams — a taste of functional Java
import java.util.List;
public class StreamsDemo {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
// Filter even numbers, square them, sum
int total = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println(total); // 4 + 16 + 36 = 56
// Print each element
nums.stream()
.filter(n -> n > 3)
.forEach(System.out::println);
}
}
List when order matters and
duplicates are fine. Use Set when you need uniqueness.
Use Map when you need fast lookups by key. Master these
three and you'll cover 90% of real-world collection needs.
SECTION 07Test yourself — Java basics quiz
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 08Frequently asked questions
Is Java hard to learn for beginners?
Java has a moderate learning curve. Its strict typing and boilerplate feel heavy at first, but they teach good discipline. Once you understand the structure of a Java program and the four OOP pillars, the language becomes much easier.
What's the difference between JDK, JRE, and JVM?
JVM (Java Virtual Machine) runs Java bytecode. JRE (Java Runtime
Environment) includes the JVM plus libraries needed to run Java
apps. JDK (Java Development Kit) includes the JRE plus tools like
javac to compile Java code. To write Java, install
the JDK.
Should I learn Java or Python first?
Both are excellent first languages. Python is easier to start with, while Java teaches strong typing and structure that transfer well. Choose based on your goal: Android, enterprise, or backend → Java; data science, scripting, or AI → Python.
What is the difference between an array and an ArrayList?
Arrays are fixed-size — you choose the length at creation and
can't grow them. ArrayList is dynamic — you can add
and remove elements freely. Use arrays for fixed-size numeric
data and ArrayList when the collection size changes.
Do I need to learn OOP to use Java?
Yes — Java is an object-oriented language, and every program is built from classes and objects. You can write simple programs without deep OOP knowledge, but real projects and interviews expect you to understand encapsulation, inheritance, polymorphism, and abstraction.
SECTION 09Related reads
Classroom & online · Noida
Learn Java from the ground up
Our Java Training Course covers core syntax, OOP, exceptions, collections, and Spring Boot — with real projects and interview preparation.
₹18,000 · full programme- Java core + OOP + Collections
- Real projects & Spring Boot basics
- Mock interviews
- Weekday & weekend batches