Contents
Java tutorial
A step-by-step Java course from scratch: from your first program to advanced topics.
1.Basics
- Introduction to JavaWhat Java is, where it is used, how to install JDK 25 and run your first program with java Main.java.
- Your first programThe parts of a Java program: the main method, statements, output with IO.println, comments and the classic form with public class Main.
- VariablesDeclaring variables in Java: type and name, assignment, var, final constants and naming rules.
- Primitive typesJava's eight primitive types: int, long, double, float, char, boolean, byte and short, their ranges and overflow.
- OperatorsJava arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.
- StringsThe String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.
- Type conversionAutomatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.
- Keyboard inputHow to read user input in Java: IO.readln, turning input into a number and the Scanner class.
- Wrapper classesInteger, Double, Boolean and Character in Java: autoboxing and unboxing, null instead of a number, the Integer cache and why wrappers must not be compared with ==.
- Math and BigDecimalThe Math class in Java, floating-point imprecision (0.1 + 0.2), BigDecimal for money: creating from a string, setScale, RoundingMode, compareTo vs equals, and BigInteger.
- Bitwise operatorsJava bitwise operators: & | ^ ~, the shifts << >> >>>, binary form with Integer.toBinaryString, flags and masks.
2.Control flow
- ConditionsBranching in Java: if, else, else if, compound conditions and the ternary operator.
- switchThe switch statement in Java: arrow labels, several values per case, switch expressions that return a value, yield and the classic form with break.
- LoopsLoops in Java: while, do-while, for and for-each over an array.
- Loop controlThe break and continue statements in Java, leaving nested loops with labels and loops that exit from the middle.
3.Methods
- MethodsWhat a method is in Java, how to declare one next to main and call it, and why the classic form needs static.
- Parameters and return valuesMethod parameters in Java, the result type, the return statement and passing arguments by value.
- Method overloadingOverloading in Java: several methods with one name and different parameters, how the right version is chosen and default values.
- ScopeWhere a variable is visible in Java: local variables, blocks, loop variables, program fields and shadowing.
- RecursionRecursion in Java: a method that calls itself, the base case, the call stack and StackOverflowError.
- Variable argumentsVarargs in Java: a parameter with an ellipsis, using it as an array, combining it with regular parameters and printf.
4.Arrays and strings
- ArraysArrays in Java: creating them, index access, length, default values, looping over them and printing with Arrays.toString.
- Multidimensional arraysTwo-dimensional arrays in Java: creating a table, access by two indexes, nested loops, jagged arrays and Arrays.deepToString.
- The Arrays classUtilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.
- String methodsThe main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.
- StringBuilderStringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.
- Text blocks and formattingMulti-line text blocks in Java, formatting strings with formatted, String.format and printf, the %s, %d and %f specifiers and field width.
- Regular expressionsRegular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.
5.Object-oriented programming
- Classes and objectsWhat classes and objects are in Java: fields, methods, the new operator, default values and object references.
- ConstructorsConstructors in Java: initial field values, the this keyword, several constructors and calling this(...).
- EncapsulationEncapsulation in Java: the private modifier, getters and setters, data validation and final fields.
- Static fields and methodsThe static keyword in Java: shared class fields, static methods, static final constants and calls through the class name.
- InheritanceClass inheritance in Java: extends, protected, calling super(...), overriding methods and the @Override annotation.
- PolymorphismPolymorphism in Java: a variable of the parent type, choosing a method at run time, shared code for different classes and instanceof.
- Abstract classesAbstract classes and methods in Java: the abstract keyword, shared code for subclasses and why such classes cannot be instantiated.
- InterfacesInterfaces in Java: implements, several interfaces in one class, an interface as a type and default methods.
- Methods of the Object classThe toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.
- RecordsRecords in Java: a short class declaration for data, ready-made equals, hashCode and toString, the compact constructor and methods.
- EnumsEnums in Java: a fixed set of values, values() and valueOf(), switch over an enum, fields and methods.
- Nested classesNested classes in Java: static nested, inner, local and anonymous classes and when to use them.
- Sealed classesSealed classes and interfaces in Java: sealed, permits, final and non-sealed subclasses and a switch without a default branch.
- Packages and access modifiersPackages and import in Java, the public, protected and private modifiers and default access, building and running a multi-file project.
6.Collections
- Lists: List and ArrayListLists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.
- Sets: SetSets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.
- Maps: Map and HashMapMaps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.
- Iterating over collectionsHow to go through a collection in Java: the for-each loop, indexes, forEach with a lambda, iterating a map, Iterator and removeIf.
- Sorting and comparatorsSorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.
- Queues and dequesQueues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.
- Collection helper methodsThe Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.
- Your own IterableHow to make your own class work in a for-each loop: the Iterable and Iterator interfaces, hasNext and next, NoSuchElementException and forEach.
- Collections for enumsEnumMap and EnumSet in Java: a map and a set for enum constants, ranges and complements, values(), valueOf() and why you should not rely on ordinal().
7.Generics and lambdas
- GenericsGeneric types in Java: type parameters, your own generic classes and records, generic methods and why int cannot be used in them.
- Bounded types and wildcardsBounded type parameters in Java: extends on a parameter, several bounds, the ? extends and ? super wildcards.
- Lambda expressionsLambdas in Java: writing a function as a value, syntax forms, passing lambdas to methods and capturing variables.
- Functional interfacesFunctional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.
- Method referencesMethod references in Java: the :: operator, references to static methods, methods of an object, methods of an arbitrary object and constructors.
- OptionalThe Optional class in Java: a value that may be absent, creating it with of and empty, orElse, map, ifPresent and orElseThrow.
- PECS and type erasureThe PECS rule for ? extends and ? super, the unbounded wildcard and type erasure in Java: why there is no new T() and no instanceof List<String>.
8.Streams
- What a stream isThe Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.
- Stream operationsThe main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.
- CollectorsThe collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.
- GroupingGrouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.
- flatMap and numeric streamsflatMap and mapMulti for unfolding nested data, IntStream, LongStream and DoubleStream, switching between streams with boxed and mapToObj, summaryStatistics.
- Parallel streamsparallelStream and parallel in Java: how a stream is split across processor cores, when it speeds things up, ordering and forEachOrdered, and the danger of shared mutable state.
9.Exceptions
- What exceptions areExceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.
- try, catch and finallyHandling exceptions in Java — the try and catch blocks, several catch blocks, multi-catch, finally and throwing exceptions with throw.
- Checked and unchecked exceptionsChecked and unchecked exceptions in Java — what the compiler requires, the throws clause, RuntimeException and wrapping exceptions.
- Custom exceptionsHow to create your own exception class in Java — extending Exception or RuntimeException, the message, the cause and extra fields.
- try-with-resourcesClosing resources automatically in Java — try-with-resources, the AutoCloseable interface, several resources, closing order and suppressed exceptions.
10.Files, dates and time
- Files and pathsWorking with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.
- Reading and writing filesReading and writing text files in Java — Files.writeString, readString, readAllLines, write, appending to the end, Files.lines and buffered streams.
- Dates and timesThe java.time package — LocalDate, LocalTime, LocalDateTime, date arithmetic, Period, Duration, ChronoUnit, time zones and Instant.
- Formatting and parsing datesDateTimeFormatter in Java — patterns like dd.MM.yyyy, month names in the language you need, parsing a string into a date and pattern mistakes.
- HTTP clientMaking requests to web servers from Java — HttpClient, HttpRequest and HttpResponse.BodyHandlers, GET and POST with JSON, status codes and asynchronous sendAsync.
- Arguments, environment and exit codesHow a Java program gets settings from outside — command-line arguments, environment variables with System.getenv, system properties with System.getProperty and -D, and exit codes with System.exit.
11.Pattern matching
- Patterns in instanceofPattern matching for instanceof in Java — a type check and a cast in one line, the scope of a pattern variable and negation.
- Patterns in switchPattern matching in switch in Java — type patterns in case, when guards, case null, exhaustiveness and sealed hierarchies.
- Record patternsRecord patterns in Java — taking a record apart into its components in instanceof and switch, nested patterns, var and the unnamed variable _.
12.Concurrency
- ThreadsThreads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.
- Thread pools and ExecutorServiceExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.
- Virtual threadsVirtual threads in Java 21+ — how they differ from ordinary threads, Thread.ofVirtual, newVirtualThreadPerTaskExecutor, thousands of tasks at once and limiting with a Semaphore.
- CompletableFutureAsynchronous chains in Java — CompletableFuture.supplyAsync, thenApply, thenAccept, thenCombine, allOf, handling errors with exceptionally and join.
- SynchronizationRace conditions in Java and how to avoid them — synchronized methods and blocks, atomic classes like AtomicInteger, ReentrantLock and a shared lock object.
- Concurrent collectionsCollections for multithreaded code in Java — ConcurrentHashMap and merge, CopyOnWriteArrayList, BlockingQueue and the producer-consumer pattern.
- Scoped valuesScopedValue in Java 25 — passing data deep into calls without parameters, ScopedValue.newInstance, where(...).run(...), get, nested binding and why scoped values replace ThreadLocal with virtual threads.
13.Advanced topics
- AnnotationsAnnotations in Java — @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings, declaring your own annotation, @Retention, @Target and reading annotations at run time.
- ReflectionReflection in Java — the Class object, a class's fields and methods, calling a method by name, creating an object, record components and the limits of reflection.
- ImmutabilityImmutable objects in Java — final fields, records, List.of and List.copyOf, defensive copies, unmodifiable views and why final doesn't make a list immutable.
- Equality and hash codesComparing objects in Java — == and equals, the equals and hashCode contract, Objects.equals and Objects.hash, records and the HashSet mistake.
- Testing with JUnitUnit tests in Java with JUnit — adding it with Maven and Gradle, the @Test annotation, assertEquals, assertThrows, @BeforeEach, parameterized tests and running them.
- Modern Java: from 8 to 25What changed in Java from version 8 to 25 — var, records, text blocks, switch expressions, sealed classes, pattern matching, virtual threads, sequenced collections and compact source files.
- ModulesThe Java module system — module-info.java, requires and exports, a two-module project, compiling with javac --module-source-path and running with java --module-path, and the modules of the JDK itself.
- LoggingLogging in Java — why not System.out.println, System.Logger and java.util.logging, message levels, format, parameters and exceptions in the log, SLF4J and Logback in projects.
- Memory and garbage collectionHow Java works with memory — the stack and the heap, references, garbage collection, memory leaks through static collections and listeners, OutOfMemoryError and StackOverflowError, the G1 and ZGC collectors.
14.Databases (JDBC)
- JDBC basicsWorking with a database from Java through JDBC — what a driver is, connecting with DriverManager.getConnection, Statement for SQL commands and reading rows with ResultSet, using SQLite.
- Prepared statementsPreparedStatement in JDBC — ? parameters in queries, protection against SQL injection, inserting, updating and deleting rows with executeUpdate, and getting generated keys.
- TransactionsTransactions in JDBC — auto-commit mode, setAutoCommit(false), commit and rollback, transferring money between accounts and a reliable pattern with try-with-resources.