What is Java and why learn it?

Java runs your bank's payment servers, millions of Android apps and the big data tools behind every large company. In this lesson you'll learn what Java is, why one Java program runs on every kind of computer, and you'll run your first Java code.

Module 1 · Introduction to Java⏱ 15 minBeginnerNo install needed8 practice problems
1 The story

₹20 at the chai stall

Evening, outside the college gate in Kharghar. Riya scans the QR code at the chai stall and pays ₹20. Before she can put her phone away, the shopkeeper's speaker announces: “₹20 received.”

₹20 Paid via UPI Riya's phone Bank server runs Java code check balance debit ₹20 credit shop “₹20 received” shop's speaker myphatshala.in
Riya

Sir, that took two seconds! My phone, the bank and the shop's speaker are all different machines. Who writes the software that makes them talk?

Arjun Sir

Programmers do. A large share of banking and payment software is written in a language called Java. Its biggest trick is the answer to your question: one Java program can run on very different machines without being rewritten.

Riya

How? My laptop runs Windows, the server probably runs Linux. Don't they need different programs?

Arjun Sir

Normally, yes. Java gets around it with a translator called the JVM that lives on each machine. You write once, and every JVM understands it. Let's see exactly how.

2 Definition

What is Java?

Formal definition (write this in exams)

Java is a high-level, object-oriented, general-purpose programming language. Java programs are compiled into platform-independent bytecode, which runs on any device that has a Java Virtual Machine (JVM).

In simple words

Java is a language for giving instructions to a computer. You write the instructions once. Java turns them into a universal format (bytecode), and a translator called the JVM on each computer runs them. Windows, Mac, Linux, a bank server: the same program works on all of them.

Words you'll hear in every Java lesson

Source code (.java)The text you write, readable by humans.
Compiler (javac)Checks your code for mistakes and converts it to bytecode.
Bytecode (.class)Instructions for the JVM. The same file works on every operating system.
JVMJava Virtual Machine: reads bytecode and runs it on the real computer.
JDKJava Development Kit: everything you install to write and run Java (compiler + JVM + libraries).
WORA“Write Once, Run Anywhere”, Java's famous promise.

Java at a glance

Created byJames Gosling and his team at Sun Microsystems
ReleasedAnnounced in 1995; JDK 1.0 released in January 1996
Original nameOak (renamed Java, after Java coffee)
Owned today byOracle (bought Sun Microsystems in 2010). The open-source version is OpenJDK.
Type of languageHigh-level, object-oriented, statically typed, compiled to bytecode and run by the JVM
File types.java source code · .class bytecode · .jar a package of many class files
Release cycleA new version every 6 months. Long-Term Support (LTS) versions every 2 years: Java 17, 21, 25

Exam tip: Java is called platform independent because its bytecode can run on any platform. The JVM itself is platform dependent: Windows, macOS and Linux each need their own JVM. Examiners love this trick question.

3 Types and ways to use it

The Java family: 4 platforms and 4 types of applications

“Java” is not one product. It's a language plus a set of platforms, each tuned for a different kind of device.

The four Java platforms

Java SE: Standard Edition

The core language and libraries: strings, collections, files, threads. Everything in this course is Java SE.

Start here

Jakarta EE (formerly Java EE)

Java SE plus tools for large web and enterprise systems: web servers, databases, transactions.

Banks, e-commerce

Java ME: Micro Edition

A smaller Java for devices with little memory: old feature phones, set-top boxes, sensors.

Embedded devices

Java Card

A tiny Java that runs inside chips on SIM cards and bank cards to keep secrets safe.

Smart cards

The four types of Java applications

TypeWhat it isExample
Standalone (desktop)Installed and run on one computerIntelliJ IDEA, Eclipse IDE
Web applicationRuns on a server; you use it through a browserOnline booking and shopping sites
Enterprise applicationLarge, distributed, secure systems used by organisationsCore banking, insurance, HR systems
Mobile applicationRuns on phonesAndroid apps (Java or Kotlin)
4 Step by step

From zero to your first running Java program

Here's what happens on your side and what happens inside the computer at each step.

  1. Install a JDK

    Download a free JDK such as Eclipse Temurin or Oracle JDK. Choose an LTS version (21 or 25). In a hurry? Skip this and use the live editor in Part 7.

    The installer copies javac (the compiler), java (the launcher that starts the JVM) and thousands of ready-made library classes onto your disk.
  2. Check it worked

    java -version
    javac -version
    Your operating system searches the folders listed in the PATH setting for programs named java and javac, runs them, and they print their version.
  3. Write the program

    Open any editor (VS Code, IntelliJ IDEA, even Notepad) and save this as Main.java. The file name must match the class name.

    The editor saves plain text characters to your disk. To the computer it's just letters, not yet a program.
  4. Compile it

    javac Main.java
    javac reads the whole file, checks the grammar and the types, and writes a new file Main.class containing bytecode. No message means success.
  5. Run it

    java Main
    Namaste from Java!
    The JVM starts, loads Main.class into memory, checks the bytecode is safe, finds the main method and runs it line by line.

Shortcut: since Java 11 you can run a single file directly with java Main.java. Java compiles it in memory and runs it straight away. It's handy for practice, but real projects still compile first.

5 See it happen

Write once, run anywhere: both views

Press Play or step through with Next. The left side shows what you see on screen. The right side shows what's happening behind it at the same moment.

Riya's program travels to three computers 6 steps
What you see Main.java public class Main { public static void main(..) { System.out.println( "Namaste from Java!"); } } > javac Main.java (no message = no errors) Folder: Main.java Main.class ✨ Windows PC MacBook Linux server The same Main.class is copied to all three > java Main Namaste fromJava! $ java Main Namaste fromJava! $ java Main Namaste fromJava! Compare: a C program built on Windows > hello.exe Hello! Windows ✓ works $ ./hello.exe cannot execute binary file Linux ✗ fails Without a JVM, you must rebuild for each system. Write Once, Run Anywhere myphatshala.in
Behind the screen Main.java plain text on disk What you typed: p u b l i c c l a s s Stored as character codes (hex): 70 75 62 6C 69 63 20 63 6C 61 73 73 Humans can read this. A CPU can't run it. Main.java javac ✓ grammar (syntax) ✓ types Main.class Inside Main.class (bytecode): CA FE BA BE← “magic number”: every .class file starts with it B2 getstaticSystem.out 12 ldc"Namaste from Java!" B6 invokevirtualprintln B1 return These are instructions for the JVM, not for any real CPU. Main.class JVMfor Windows JVMfor macOS JVMfor Linux Same file, byte for byte. Only the JVM is different on each machine. interpreter + JITx86-64 code interpreter + JITARM64 code interpreter + JITx86-64 code CPU CPU CPU hello.c gccon Windows hello.exe Windows file format +x86 machine code Windows ✓understands the format Linux ✗expects a different format Machine code is tied to one OS + CPU. Java avoids this by targeting the JVM instead. Your code (.java), written once ↓ javac (once) Bytecode (.class), the same everywhere ↓ copied to any machine JVM, different for each OS ↓ translates at run time Machine code runs on the CPU myphatshala.in

Java vs C vs Python: how each one runs

CJavaPython
You writehello.cMain.javahello.py
Converted toMachine code for one OS/CPUBytecode for the JVMBytecode for the Python interpreter (done automatically)
Runs on another OS?Only after recompilingYes, the same .class fileYes, if Python is installed
SpeedVery fastFast (JIT compiler)Slower for heavy computation
Types checkedAt compile timeAt compile timeAt run time
6 Real-world use

Where Java runs in your daily life

You use Java-powered systems many times a day without knowing it. Here are seven places, and what Java does in each.

Watch it with an example: one UPI payment

You pay Rs 60 at the college canteen. Follow the payment and see where Java code is doing the work.

Rs 60 from Riya to the canteen 6 steps
Animated example Riya'sphone Bank server Java program on a JVM Canteenphone check PIN, limit Riya 500→440 Canteen +60 ₹60 Paid ✓ Sent ✓ myphatshala.in
₹Java

1. Banking and UPI payments

When you pay by UPI or net banking, your request goes to bank servers. Many core banking and payment platforms are built in Java because it's stable, secure and handles thousands of transactions a second.

Your app→Payment network→Java service: check, debit, credit→Confirmation

2. Android apps

Java was Android's original app language, and millions of apps are written in it. Today Android apps are written in Java or Kotlin, and both share the same Java ecosystem and libraries.

Java/Kotlin code→Android build tools→App on your phone
TICKET

3. Ticket booking and online shopping

When lakhs of people book train tickets at the same minute, or a big sale opens, the servers must not crash or sell one seat twice. Java frameworks such as Spring Boot are widely used for these high-traffic backends.

Search→Java backend locks the seat→Payment→Ticket

4. Big data tools

The tools companies use to handle huge amounts of data, such as Apache Hadoop, Apache Kafka and Elasticsearch, are written mainly in Java, and Apache Spark runs on the JVM. Learning Java helps you understand these tools from the inside (they're in our Big Data track).

Billions of events→Kafka / Hadoop on the JVM→Reports and dashboards

5. Games

Minecraft: Java Edition, one of the best-selling games ever, is written in Java. Its huge modding community exists partly because Java code is easy to extend.

Game written in Java→JVM→Windows, Mac or Linux

6. Developer tools

Popular code editors such as IntelliJ IDEA and Eclipse are themselves Java applications. Programmers use Java to build tools for other programmers.

IDE written in Java→Runs on every desktop OS

7. SIM cards and bank cards

The chip in many SIM cards and debit/credit cards runs Java Card, a tiny version of Java. It stores secret keys and proves the card is genuine when you tap or insert it.

Card tapped→Java Card app in the chip→Payment approved

Examples are simplified to show where Java fits. Each company's exact technology choices vary.

7 Run the code

Your first Java program

Read the program and its line-by-line meaning first, then open the live editor and try each challenge.

public class Main {
    public static void main(String[] args) {
        System.out.println("Namaste from Java!");
    }
}
Namaste from Java!
  • public class MainEvery Java program lives inside a class. Here the class is named Main, so the file must be Main.java.
  • public static void main(String[] args)The entry point: the JVM always starts running from this exact method. Lesson 1.6 explains each word.
  • System.out.println(...)Prints text to the console and then moves to a new line (ln = line).
  • "Namaste from Java!"A string: text inside double quotes.
  • ; and { }Every statement ends with a semicolon. Curly braces group code into blocks.
8 Line by line

What the JVM does at every line

Step through this slightly bigger program. Watch the highlighted line on the left and the memory on the right. The stack holds methods and their small variables, and the heap holds objects such as strings. Both are covered in depth in Module 8.

Worked examples: real problems, solved and traced in memory

Three tiny programs of the kind Java runs every day in shops, banks and phones. Each one uses only what you have seen so far: println, a few variables and arithmetic. Run them, then step through to see each value appear on main's stack.

Example 1Canteen · billing

Print a canteen bill

Problem statement

A college canteen wants its counter computer to print a simple bill: two items with prices, and the total. Write a Java program that stores the prices in variables, adds them, and prints the bill.

Input
Masala dosa Rs 60, Filter coffee Rs 25
Expected output
--- Canteen Bill ---
Masala dosa   Rs 60
Filter coffee Rs 25
Total         Rs 85

Approach

  1. Store each price in an int variable.
  2. Add them into a total variable.
  3. Print each line with System.out.println, joining text and numbers with +.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 2Fitness · steps

How many steps are left today?

Problem statement

A fitness app sets a daily goal of 8,000 steps. The phone has counted 5,340 so far. Print the steps walked, the steps remaining and the percentage completed.

Input
goal 8000, walked 5340
Expected output
Walked: 5340 steps
Remaining: 2660 steps
Done: 66%

Approach

  1. Store the goal and the steps walked.
  2. Remaining = goal − walked.
  3. Percentage = walked × 100 / goal (whole-number division).

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

Example 3Telecom · SMS

How many SMS parts will this message need?

Problem statement

An SMS can carry 160 characters. A bank wants to know how many characters its OTP message has, and how many 160-character parts it needs.

Input
message: "Your OTP for login is 482913. Do not share it with anyone. Valid for 5 minutes."
Expected output
Characters: 79
SMS parts needed: 1

Approach

  1. Store the message in a String.
  2. message.length() gives the number of characters.
  3. Parts = (length + 159) / 160 rounds up using whole-number division.

Solution: run it live

What happens in memory, step by step

Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.

9 Quiz and revision

Check yourself

Quick revision

Lesson 1.1 in one screen

  • Java: a high-level, object-oriented language by James Gosling, Sun Microsystems, 1995. Owned by Oracle; OpenJDK is the open-source version.
  • Flow: .java → javac → .class (bytecode) → JVM → machine code.
  • WORA: bytecode is platform independent. The JVM is platform dependent.
  • 4 platforms: SE (core), Jakarta EE (enterprise), ME (small devices), Java Card (chips).
  • 4 application types: standalone, web, enterprise, mobile.
  • Used in: banking and payments, Android, booking and e-commerce backends, big data (Hadoop, Kafka), games, IDEs, smart cards.
  • Commands: javac Main.java compiles, java Main runs.

Interview and viva questions

Is Java a compiled or an interpreted language?

Both. Java source code is compiled by javac into bytecode. At run time, the JVM interprets the bytecode and its JIT compiler compiles frequently used parts into native machine code for speed. So Java is best described as “compiled to bytecode, then interpreted and JIT-compiled by the JVM”.

Why is Java called platform independent?

Because the compiled bytecode (.class) does not depend on any operating system or CPU. Any machine with a JVM can run it. The JVM itself is platform dependent: there's a different JVM for each OS.

What is the difference between Java and JavaScript?

They are completely different languages that share part of a name for historical marketing reasons. Java is statically typed and runs on the JVM, mainly for backends, Android and big data. JavaScript is dynamically typed and runs mainly in web browsers and on Node.js.

Is Java free to use?

Yes. OpenJDK is free and open source, and free builds such as Eclipse Temurin are widely used. Oracle's own JDK has its own licence terms, so companies check those before using it in production.

Is Java still worth learning in 2026?

Yes. Java is consistently among the most-used languages in industry, especially for banking, enterprise backends (Spring Boot), Android and big data. It also teaches object-oriented thinking that carries over to C#, Kotlin and other languages.

Practice problems

Short programs that use println, variables and arithmetic. Every output is fixed, so you can check yours exactly. The last three are small business tasks.

P1Easy

Print your name and city

Print two lines: your name, then your city.

Input
(none)
Expected output
Name: Riya Sharma
City: Pune
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        System.out.println("Name: Riya Sharma");
        System.out.println("City: Pune");
    }
}
Name: Riya Sharma City: Pune

How it works: each println prints its text and moves to a new line.

P2Easy

Add two numbers

Store 45 and 30 in two variables and print their sum.

Input
45, 30
Expected output
Sum = 75
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int a = 45;
        int b = 30;
        System.out.println("Sum = " + (a + b));
    }
}
Sum = 75

How it works: the brackets make Java add the numbers first. Without them, "Sum = " + a + b would print Sum = 4530.

P3Easy

Hours in a week

Print how many hours there are in a week.

Input
7 days × 24 hours
Expected output
Hours in a week: 168
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int days = 7;
        int hoursPerDay = 24;
        System.out.println("Hours in a week: " + days * hoursPerDay);
    }
}
Hours in a week: 168

How it works: * runs before +, so the multiplication happens first.

P4Medium

Minutes to hours and minutes

A movie is 155 minutes long. Print it as hours and minutes.

Input
155
Expected output
2 h 35 min
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int total = 155;
        System.out.println(total / 60 + " h " + total % 60 + " min");
    }
}
2 h 35 min

How it works: / between ints gives the whole part (2); % gives the remainder (35).

P5Medium

Average of three marks

Print the average of 78, 85 and 92 with decimals.

Input
78, 85, 92
Expected output
Average: 85.0
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int sum = 78 + 85 + 92;
        double avg = sum / 3.0;
        System.out.println("Average: " + avg);
    }
}
Average: 85.0

How it works: dividing by 3.0 (a decimal) keeps the fraction; dividing by 3 would give 85.

P6Business problem

Auto-rickshaw fare

Fare is Rs 26 for the first 1.5 km and Rs 17 per km after that. Print the fare for a 6 km ride (4.5 extra km).

Input
6 km
Expected output
Fare: Rs 102.5
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        double extraKm = 6 - 1.5;
        double fare = 26 + extraKm * 17;
        System.out.println("Fare: Rs " + fare);
    }
}
Fare: Rs 102.5

How it works: real fare meters do exactly this: a base fare plus a per-km rate. (Illustrative rates.)

P7Business problem

Electricity bill

A home used 240 units at Rs 7 per unit plus a fixed charge of Rs 100. Print the bill.

Input
240 units
Expected output
Units: 240
Bill: Rs 1780
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int units = 240;
        int bill = units * 7 + 100;
        System.out.println("Units: " + units);
        System.out.println("Bill: Rs " + bill);
    }
}
Units: 240 Bill: Rs 1780

How it works: variables make the rule easy to change later when the rate changes. (Illustrative tariff.)

P8Business problem

Split a dinner bill

Four friends share a bill of Rs 1,450. Print each person's share and what's left over if each pays a whole number of rupees.

Input
1450, 4 people
Expected output
Each pays: Rs 362
Left over: Rs 2
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int bill = 1450;
        int people = 4;
        System.out.println("Each pays: Rs " + bill / people);
        System.out.println("Left over: Rs " + bill % people);
    }
}
Each pays: Rs 362 Left over: Rs 2

How it works: 1450 / 4 = 362 (whole part) and 1450 % 4 = 2 rupees remaining, which someone has to cover.

Real-world scenario questions (asked in company interviews)

Companies rarely ask “define Java”. They describe a situation from the job and watch how you think. Read each scenario, decide your answer first, then open the model answer.

Fintech backendFresher

“Do we need to rebuild this for Linux?”

You built a small payment-report service on your Windows laptop with JDK 21. The operations team will run it on a Linux server. Your team lead asks: “Do we need to rebuild it for Linux? Anything you'd check before handing over the jar?”

The interviewer is checking: do you understand Write Once, Run Anywhere, and do you also know its practical limits?

Show a strong answer

No rebuild is needed. The .jar contains bytecode, and the JVM on Linux runs it as it is. Before handing it over, I would check four things:

  1. Java version on the server. It must be the same as, or newer than, the version I compiled for. If it's older, I compile with javac --release 17 (or whatever the server has), or ask ops to upgrade.
  2. OS-specific assumptions in my code: hard-coded Windows paths like C:\reports, and file-name letter case (Linux treats Report.csv and report.csv as different files).
  3. Native libraries: if any library uses native code, it needs its Linux version.
  4. One trial run on a Linux test machine or container before production.

Avoid saying: “Java runs anywhere, so nothing can go wrong.” Bytecode is portable, but the assumptions in your code may not be.

Product startup · deploymentFresher

The app won't start on the server

Your build works on your laptop, but on the server the app fails at start-up with: UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 65.0), this version of the Java Runtime only recognizes class file versions up to 61.0. What happened, and how do you fix it?

The interviewer is checking: can you read an error message calmly and connect it to how bytecode works?

Show a strong answer

Every .class file records which Java version produced it, called the major version. 65 means Java 21 and 61 means Java 17. So I compiled with JDK 21 but the server runs Java 17, and an older JVM refuses newer bytecode.

  • Fix 1: upgrade the server's Java runtime to 21.
  • Fix 2: if I don't need Java 21 features, compile for the older version with javac --release 17 (or set the release version in Maven or Gradle).
  • I can confirm the version with javap -v Main.class and look for major version.
  • Long term, the team should keep laptops, the CI build and the servers on the same Java version.

Avoid: reinstalling Java at random or trying different jar files until something works. Explain the cause first.

IT services · client meeting1–3 years

“Java is slow. Let's rewrite it in C++.”

A client's order-tracking system feels slow. In a meeting, someone says the fix is to rewrite it in C++. Your manager turns to you: “What do you think?”

The interviewer is checking: do you make decisions with measurements instead of myths, and can you say so politely to a client?

Show a strong answer

I'd suggest we measure where the time goes before changing the language:

  • Most business applications spend most of their time waiting for databases, network calls and disk, not computing. A rewrite won't fix a slow SQL query or a missing index.
  • Java's JIT compiler turns frequently used code into native machine code, so after warm-up Java is usually fast enough for this kind of work.
  • Tools such as Java Flight Recorder, a profiler, or timing logs around each step will show the real bottleneck.
  • A rewrite costs months of work and testing, and C++ brings back memory-safety risks. I'd only recommend it if the data shows the language itself is the problem.

Avoid: defending Java emotionally (“Java is the best!”) without offering a way to measure.

Any company · team setupFresher

Which JDK should the new team install?

You're setting up laptops for a new three-year project. The options someone found are Oracle JDK 25, the newest non-LTS OpenJDK release, and Eclipse Temurin 21. Your lead asks you to recommend one.

The interviewer is checking: do you know about LTS versions, licences, and keeping the whole team consistent?

Show a strong answer
  • Pick an LTS version (21 or 25). Non-LTS releases get updates for only about six months, which is too short for a three-year project.
  • Match what production and the CI build will run, so everyone uses the same major version.
  • Free OpenJDK builds such as Eclipse Temurin are widely used. For Oracle JDK, check Oracle's current licence terms with the company before using it in production.
  • Write the version in the build file and README so new joiners install the right one.

My recommendation: Temurin 21 or 25, whichever production supports.

Avoid saying: “Always install the newest version.” The newest version isn't always the best supported one.