Java Tutorial for Beginners
Learn Java programming step by step, from your first program to OOP, collections, streams, testing and data structures, with Java examples, exercises and quizzes.
Browse all 127 lessons by stage
- Lessons
- 127
- Code examples
- 385
- Exercises
- 329
- Quiz questions
- 333
Java course at a glance
Who it's for
Complete beginners, computer science students, interview candidates and developers moving to Java from Python or JavaScript.
Prerequisites
None. Basic computer skills and a willingness to use a terminal are enough; the maths is school level.
What you need
A JDK, version 21 or 25 recommended, such as Eclipse Temurin, and an editor such as IntelliJ IDEA or VS Code.
How long it takes
Two to three months for Beginner and Intermediate at five hours a week, and the same again for the rest.
Java roadmap: beginner to advanced
Work through the core stages in order, because each one builds on the last, then choose the optional tracks that match your goals. Every lesson has worked examples, exercises and a quiz.
Beginner
Your first program, variables, operators, input, strings, formatting, if, switch and loops.
- 1IntroductionWhat Java is, how to install the JDK, and how a Hello World program is built and run.
- 2Syntax and StatementsJava syntax is the set of rules that tells the compiler how to read your program.
- 3Output: print() vs. println()Java uses System.out to write ordinary console output.
- 4Comments and Code StructureJava comments explain source code without becoming executable instructions.
- 5Variables & Data TypesDeclare variables with types such as int, double, boolean, char and String, and convert between them.
- 6Variables, Identifiers and ConstantsA Java variable gives a name and a type to a value your program needs.
Show all 30 lessonsShow fewer
- 7Primitive Data TypesJava has eight primitive data types: byte, short, int, long, float, double, char and boolean.
- 8Type Casting and varJava type casting converts a value to another compatible type.
- 9Boolean ExpressionsA Java boolean expression evaluates to true or false.
- 10Operators & MathCalculate in Java with arithmetic operators, integer division and remainder, increment and compound assignment, casting, and the Math class.
- 11Operators and PrecedenceJava operators perform calculations, compare values, combine conditions and assign results.
- 12User Input (Scanner)Read text and numbers typed by the user with the Scanner class, and avoid the classic nextLine() trap.
- 13User Input with ScannerJava Scanner reads text and can interpret it as tokens such as words, integers or decimal numbers.
- 14Command-Line ArgumentsJava command-line arguments are the text values supplied after the class name when you launch a program.
- 15StringsWork with text in Java: length, charAt, substring, indexOf, replace, split, comparing strings and building text with StringBuilder.
- 16Strings, Concatenation and EscapesA Java String represents a sequence of text.
- 17Formatting & StringBuilderProduce neat output with printf and String.format, build long strings efficiently with StringBuilder, and write multi-line text with text blocks.
- 18if / elseMake decisions with comparison operators, if, else if, else, logical operators and switch.
- 19if, else if and Nested ConditionsJava if selects a statement or block when a boolean condition is true.
- 20switch & Switch ExpressionsChoose between many options with switch: the classic statement with break, modern arrow cases, multiple labels, switch expressions that return values, and yield.
- 21switch Expressions and StatementsJava switch selects behavior using one value.
- 22LoopsRepeat code with for, while, do-while and the enhanced for loop, and control loops with break and continue.
- 23for, while and do-while LoopsJava loops repeat instructions while a rule permits another iteration.
- 24Nested and Enhanced for LoopsA nested loop places one loop inside another.
- 25break and continueJava break stops a loop immediately.
- 26MethodsOrganise code into reusable methods with parameters, return types, void and overloading.
- 27Methods and ParametersA Java method names a reusable operation.
- 28Return Values and Method OverloadingA return statement ends the current method call and, for a non-void method, supplies a result to its caller.
- 29Variable ScopeVariable scope describes where a name can be used in source code.
- 30Recursion: Base Cases and CallsRecursion occurs when a method calls itself, directly or indirectly, to solve a smaller version of a problem.
Intermediate
Arrays, methods, classes, collections, inheritance and interfaces: organising code and data.
- 31ArraysStore fixed-size lists of values in arrays, loop through them, use the Arrays helper class and build 2D grids.
- 32Single and Multidimensional ArraysJava arrays have a fixed length and hold elements of one declared type.
- 33Array Operations and SortingJava's Arrays utilities support copying, searching and sorting arrays.
- 34Classes & ObjectsCreate your own types with classes, fields, constructors and methods, then make objects with new.
- 35Classes and Objects ExplainedJava classes describe a type; objects are individual values created from that type.
- 36Fields, Attributes and MethodsJava fields store an object's state, while methods describe operations that read or change that state.
Show all 33 lessonsShow fewer
- 37Constructors and Constructor OverloadingA Java constructor establishes the starting state of a new object.
- 38this KeywordUse this to access the current object's fields and methods, delegate constructors, and pass the current object to another method.
- 39Access and Non-Access ModifiersJava modifiers answer two questions: who may access a member, and what special rules govern its behavior? Access modifiers control visibility.
- 40Encapsulation and ValidationEncapsulation keeps a Java object's rules together with its state.
- 41Inner and Anonymous ClassesA Java inner class is a non-static nested class associated with an enclosing object.
- 42Packages and ImportsJava packages give classes qualified names and group related types.
- 43String Methods ReferenceJava String methods help inspect, compare and transform text, but strings remain immutable.
- 44StringBuilder and StringBufferStringBuilder builds text through mutable operations such as append, insert and delete.
- 45Wrapper Classes and AutoboxingWrapper classes represent primitive values as objects.
- 46ArrayListUse ArrayList for lists that grow and shrink: add, get, set, remove, search, sort and loop through items.
- 47List, ArrayList and LinkedListArrayList and LinkedList both implement Java's List interface, but their storage differs.
- 48HashMap & HashSetLook values up by key with HashMap, keep unique items with HashSet, and choose the right collection.
- 49HashMap, TreeMap and LinkedHashMapA Java Map associates each key with at most one value.
- 50CollectionsChoose the right collection: lists, sets, queues, stacks and sorted maps, plus Comparator sorting and the Collections helper class.
- 51Collections Framework ExplainedThe Java Collections Framework provides interfaces for groups of objects and implementations with different performance and ordering rules.
- 52HashSet, TreeSet and LinkedHashSetJava sets store unique elements.
- 53Iterators and the Iterable InterfaceIterable describes a Java object that can supply an iterator.
- 54Collections Sorting and ComparatorsJava comparators define ordering separately from the objects being sorted.
- 55InheritanceBuild subclasses with extends, reuse constructors with super, override methods and use polymorphism.
- 56Inheritance and the super KeywordJava inheritance lets a subclass reuse and specialize an accessible superclass contract.
- 57Polymorphism and Method OverridingJava polymorphism allows one declared reference type to represent different implementations.
- 58Interfaces & AbstractDefine contracts with interfaces and partial blueprints with abstract classes, and learn when to use each.
- 59Abstraction and InterfacesAbstraction describes what an object promises to do while leaving selected implementation details to concrete types.
- 60EnumsRepresent a fixed set of values such as sizes, statuses or directions with enums, and give them fields, constructors and methods.
- 61Enums and Enum ConstructorsJava enums define a fixed set of named instances, such as shipping speeds or workflow states.
- 62GenericsWrite classes and methods that work with any type safely, using type parameters, generic methods, bounded types and wildcards.
- 63Generics and Generic ClassesJava generics let a class or method express the type of values it accepts and returns.
Files and I/O
Exception contracts, resource management, text and binary streams, file operations, paths, serialization and JSON.
- 64ExceptionsHandle errors with try, catch and finally, understand checked and unchecked exceptions, and throw your own.
- 65Exception Types and HierarchyJava represents thrown failures as objects belonging to the Throwable hierarchy.
- 66try, catch, finally, throw and throwsJava exception control flow separates the code that can fail, matching recovery code, and cleanup.
- 67Custom Exceptions and Multi-CatchCustom exceptions express a failure in the vocabulary of your application.
- 68Try-with-ResourcesTry-with-resources closes eligible resources when control leaves a try block.
- 69File Handling: Create, Read, Write, DeleteJava file handling includes creating entries, reading content, writing or appending content, and deleting entries when their lifecycle is complete.
Show all 13 lessonsShow fewer
- 70Path and Files APIsPath describes filesystem locations in a platform-aware way, and Files performs operations such as copying, moving, listing, and inspecting those locations.
- 71Byte Streams and Character StreamsChoose InputStream and OutputStream for binary data, Reader and Writer for text, and an explicit charset when converting between them.
- 72FileInputStream and FileOutputStreamRead and write file bytes, choose overwrite or append deliberately, and copy only the bytes returned by each read.
- 73BufferedReader and BufferedWriterRead text one line at a time, write deliberate line boundaries, and handle blank lines, charsets, flushes and parsing errors.
- 74Serialization and DeserializationSerialize controlled object state, understand transient fields and version compatibility, and restrict deserialization with an explicit filter.
- 75JSON Processing in JavaParse JSON trees, serialize Java records and validate field types while separating malformed JSON from invalid application data.
- 76Files & I/ORead and write text files with java.nio.file: Path, Files.readString, readAllLines, writeString, appending, streaming large files and handling IOException.
Advanced
Enums, records, generics, exceptions, files, dates, streams and JUnit: the tools of professional Java.
- 77Dates & TimesWork with dates and times using java.time: LocalDate, LocalTime and LocalDateTime, formatting and parsing, adding periods, measuring gaps and time zones.
- 78Date and Time API: java.timeJava's java.time package separates calendar dates, local clock times, time-zone-aware values, and timeline instants.
- 79Lambdas & StreamsWrite short functions with lambdas and process collections with streams: filter, map, sorted, reduce and collect.
- 80Lambda ExpressionsA Java lambda expression supplies the implementation of a functional interface without declaring a separate implementation class.
- 81Functional InterfacesA functional interface is a Java interface with exactly one abstract method after inherited methods and special Object-method rules are considered.
- 82Method ReferencesA Java method reference names an existing method or constructor where a functional interface is expected.
Show all 16 lessonsShow fewer
- 83Stream API: map, filter and reduceThe Java Stream API processes a sequence of elements through a pipeline.
- 84Optional: Handling Missing ValuesOptional<T> represents either one non-null value or no value.
- 85Regular ExpressionsA regular expression describes a text pattern.
- 86Annotations ExplainedA Java annotation attaches structured metadata to a declaration, type use, or other supported program location.
- 87Reflection APIReflection lets a Java program inspect classes, constructors, methods, and fields while it runs.
- 88Multithreading and Thread LifecycleA Java thread is an independent path of execution within a process.
- 89Synchronization and Race ConditionsA race condition occurs when a program's result depends on an uncontrolled order of competing operations.
- 90ExecutorService and Thread PoolsExecutorService accepts tasks and manages their execution through workers.
- 91Concurrency UtilitiesThe java.util.concurrent package supplies tools for coordinating tasks and safely sharing selected data structures.
- 92Debugging and Logging BasicsDebugging investigates why a Java program behaves differently from its requirement.
Developer Tools
JDK setup, compilation, classpath, Maven, testing, debugging, Git, modern language features and modules.
- 93RecordsReplace boilerplate data classes with records, which generate constructors, accessors, equals, hashCode and toString for you.
- 94Unit Testing (JUnit)Test Java code automatically with JUnit 5: @Test methods, assertions, testing exceptions, parameterized tests, setup with @BeforeEach, and running tests with Maven or Gradle.
- 95JDK, JRE and JVM ExplainedJDK, JRE, and JVM describe different parts of the Java toolchain.
- 96Installing Java and Setting Up the JDKTo develop Java applications, install a Java Development Kit and verify both its compiler and launcher.
- 97Compiling and Running Java ProgramsA traditional Java workflow has two distinct steps: javac compiles a source file into bytecode, and java launches a class containing a suitable main method.
- 98Classpath and Package LayoutA Java package gives a class a qualified name, while the classpath tells the compiler or runtime where to find class roots and libraries.
Show all 12 lessonsShow fewer
- 99Maven and Gradle BasicsA build tool makes compilation, testing, packaging, and dependency resolution repeatable.
- 100Unit Testing with JUnitJUnit lets you express expected Java behavior as executable tests.
- 101Debugging Java Applications Step by StepA debugger pauses a running Java application so you can inspect its state and follow execution.
- 102Git Basics for Java ProjectsGit records changes to the authored files of a Java project.
- 103Modern Java: Records, Sealed Classes and PatternsModern Java adds features that reduce boilerplate while keeping type contracts explicit.
- 104Modules and module-info.javaA Java module groups packages and declares which other modules it reads and which packages it exposes.
Java DSA
Complexity, searching, sorting, stacks, queues, linked lists, hashing, trees, heaps, graphs, backtracking and dynamic programming.
- 105Time and Space ComplexityTime complexity describes how an algorithm's work grows as its input grows.
- 106Linear Search and Binary SearchLinear search checks candidates in sequence until it finds a match or exhausts the input.
- 107Sorting Algorithms ExplainedSorting arranges elements according to a comparison rule.
- 108Stacks and Queues with ArrayDequeStacks and queues define which stored element is removed next.
- 109Linked Lists: Nodes and LinksA linked list stores values in nodes connected by references.
- 110Hashing and Hash TablesA hash table uses a key's hash to help locate a stored value.
Show all 11 lessonsShow fewer
- 111Trees and Binary Search TreesBuild a binary search tree, insert keys, find values and traverse nodes while understanding the limits of an unbalanced tree.
- 112Heaps and Priority QueuesUse Java PriorityQueue to retrieve the next item by priority, reverse its ordering and understand how binary heaps support queue operations.
- 113Graphs, BFS and DFSRepresent a graph with adjacency lists and implement breadth-first and depth-first traversal with cycle protection.
- 114Recursion and BacktrackingExplore subsets and permutations with recursive choices, restore mutable state correctly, and prune branches that cannot produce a valid solution.
- 115Dynamic Programming BasicsDefine reusable subproblems, compare memoization with tabulation, and solve staircase counting and minimum-coin problems in Java.
Practice and Projects
Examples, topic exercises, chapter quizzes, coding challenges, API references, error guides, interview preparation and three project levels.
- 116Examples Library for BeginnersThis Java examples library groups short, complete programs by the skill they demonstrate.
- 117Exercises by TopicThese Java exercises move from arithmetic into array processing and map-based grouping.
- 118Quizzes by ChapterA useful Java quiz checks whether you can predict behavior and explain its cause.
- 119Coding Challenges with Test CasesJava coding challenges are most useful when they specify a contract and require you to justify a solution.
- 120Keywords Reference and GlossaryJava keywords have language-defined roles and cannot be used like arbitrary names.
- 121String, Math and Collections MethodsThis Java methods reference summarizes common operations on String, Math, ArrayList, HashMap, and Collections.
Show all 12 lessonsShow fewer
- 122Common Java Errors and SolutionsJava errors become easier to fix when you identify the phase and contract involved.
- 123Interview Questions and AnswersGood Java interview answers explain a contract, give a small example, and acknowledge meaningful limits.
- 124Beginner Java Projects with Practice StepsA useful beginner Java project combines a few familiar concepts into a small application with clear behavior.
- 125Intermediate Java Projects: Collections and FilesIntermediate Java projects connect collections, files, structured classes, and tests into an application that preserves useful state.
- 126Advanced Java Projects: Testing and ConcurrencyAn advanced Java project demonstrates explicit decisions about concurrency, failure, architecture, and testing.
- 127Learning Roadmap and Study PlanA Java learning roadmap should connect study topics to observable skills.
What is Java?
Java is one of the most popular programming languages in the world. It runs banking systems, online shops, Android apps, games like Minecraft and the back ends of huge websites. Its slogan, "write once, run anywhere", comes from the fact that compiled Java programs run on any computer that has a Java runtime.
Java is statically typed: you say what type of data each variable holds, and the compiler checks your code before it runs. That makes beginners write a little more, but it catches many mistakes early and makes large programs easier to maintain, which is why so many companies rely on it.
How the course is organised
- Beginner: your first program, syntax and output, variables and primitive types, operators, input with
Scanner, strings and formatting,ifandswitch, loops, methods, scope and recursion. - Intermediate: arrays, classes and objects, constructors, encapsulation, inheritance, polymorphism, interfaces, enums, and the collections you'll use every day:
ArrayList,HashMap, sets, queues, iterators and comparators. - Files and I/O: exceptions, try-with-resources, reading and writing files, streams of bytes and characters, serialization and JSON.
- Advanced: records, generics, lambdas, functional interfaces, the Stream API,
Optional, regular expressions,java.time, annotations, reflection and concurrency. - Developer tools: installing the JDK, compiling and running, the classpath, Maven and Gradle, JUnit, debugging, Git, modern Java features and modules.
- Java DSA: complexity, searching, sorting, stacks and queues, linked lists, hash tables, trees, heaps, graphs, backtracking and dynamic programming.
- Practice and projects: an examples library, topic exercises, chapter quizzes, coding challenges, reference pages, common errors, interview questions and three project levels.
How to follow this course
Work through Beginner and Intermediate in order, because each lesson relies on the ones before it. After that, Files and I/O, Advanced and Developer tools can be studied in the order your projects need them, and Java DSA is ideal preparation for interviews. Every lesson has worked examples with their output, common mistakes, exercises, a quiz and frequently asked questions; type the examples yourself and run them with java FileName.java.
Check your progress with the Java exercises, the course quiz and the chapter quizzes, and follow the Java learning roadmap for a week-by-week plan. Build a beginner, an intermediate and an advanced project as you go: finished, tested projects are the best evidence of what you can do.
No previous programming is needed. If you already know Python or JavaScript, you'll recognise the ideas and mostly need to learn Java's types and syntax. For backend work, pair this course with SQL, since most Java applications store their data in a relational database.
What you will learn
10 practical skills, built one lesson at a time
- Install the JDK, then write, compile and run Java programs
- Calculate with operators, read keyboard input and format output neatly
- Make decisions with if and switch, and repeat work with loops
- Organise code into methods, classes and objects
- Choose the right collection: lists, sets, maps, queues and stacks
- Reuse code with inheritance, interfaces and abstract classes
- Model data with enums, records and generic types
- Handle errors, read and write files, and work with dates and times
- Process collections with lambdas and streams
- Test your code automatically with JUnit
Practise Java your way
Learning sticks when you use it. Pick a mode.
Java Exercises
Fill in blanks, predict output and fix broken code with instant feedback.
329 exercisesJava Quiz
5, 10 or 20 questions with a timer and explanations after every answer.
333 questionsJava Cheat Sheet
Every important piece of syntax on one printable page.
Open cheat sheetLearning Paths
See where Java fits in a complete roadmap, and what to learn next.
View learning pathsJava FAQ
Is Java hard for beginners?
Java needs a little more typing than Python because you declare types and write every program inside a class. The trade-off is that the compiler explains many mistakes before your program even runs. With short lessons like these, most beginners write useful programs within a few weeks.
What do I need to install to run Java?
You need the JDK (Java Development Kit). Open-source builds such as Eclipse Temurin are available from adoptium.net. An editor like IntelliJ IDEA Community, VS Code or Eclipse makes writing Java easier. The first lesson walks you through it.
Are Java and JavaScript related?
No. Despite the similar names, they're different languages with different uses. JavaScript runs in web browsers and makes pages interactive; Java is mostly used for apps, Android and servers. The name was a marketing choice in the 1990s.
How long does it take to learn Java?
With about five hours a week, most learners finish the Beginner and Intermediate stages in two to three months, and the remaining stages and projects in another two to three months. Writing small projects, such as a quiz game, a library manager or a to-do app, is what turns the lessons into real skill.
What can I build with Java?
Android apps, desktop programs, web services with frameworks like Spring, games, and large business systems. Java is also widely taught in universities and used in coding interviews.
In what order should I study the Java course?
Work through the Beginner and Intermediate stages in order first, because later lessons rely on them. Then study Files and I/O, Advanced and Developer tools in the order your projects need them, and Java DSA when you're preparing for interviews. The Java learning roadmap suggests a week-by-week plan.
Is this Java course free?
Yes. All 127 lessons, the exercises, quizzes and the cheat sheet are free to use, with no account or sign-up needed.
Which Java version does the course use?
The examples are written for Java 17 and later and are tested on a current long-term support release; Java 21 or 25 is the best choice for new learners. A few lessons point out features that need a newer version, such as record patterns in Java 21.
Should I learn Java or Python first?
Both are excellent first languages. Python is quicker to start with and popular for data and automation; Java's types and compiler teach structure that helps in large programs, and it dominates Android and enterprise backends. If a course, job or project points to one of them, start there; the concepts carry over.
Does this course prepare me for Java interviews?
It covers what junior interviews usually ask: object-oriented design, collections, exceptions, strings, streams and data structures and algorithms. Use the interview questions and coding challenges lessons to practise explaining your answers aloud.
More tutorials
Python
A friendly first programming language for scripts, data and automation.
Start PythonKotlin
The modern language for Android apps, servers and multiplatform code.
Start KotlinSwift
Apple's fast, safe language for iPhone, iPad, Mac and SwiftUI apps.
Start SwiftC#
Microsoft's versatile language for web APIs, games with Unity and desktop apps.
Start C#C++
A fast, powerful language for games, apps and systems software.
Start C++PHP
The server-side language behind WordPress and millions of websites.
Start PHP