Skip to content

Welcome to this Java programming tutorial. In this repo, you'll learn everything from Java basics to advanced features like OOP, collections, and multi-threading.

Notifications You must be signed in to change notification settings

sagarv26/JavaTutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Tutorial

Welcome to this Java programming tutorial. In this repo, you'll learn everything from Java basics to advanced features like OOP, collections, and multi-threading.

Learning Java in 2025 is still a great decision - it's one of the most widely used programming languages and forms the backbone of many enterprise and Android applications.

What is Java?

What is Java?

Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems in 1995 (now owned by Oracle Corporation).

How Java Works

Java code goes through a compilation and interpretation process:

  • You write Java code (.java file)
  • Compiler converts it to bytecode (.class file)
  • Java Virtual Machine (JVM) interprets bytecode and runs it on any device

📌 This makes Java platform-independent — the same code runs on Windows, Mac, Linux, etc., as long as there's a JVM.

Example Java Code

public class Hello {
    public static void main(String[] args) {
    	  System.out.println("Hello, Java!");
    }
}

Explanation:

java public class Hello → Defines a class named Hello

java main(String[] args) → Entry point of the program

java System.out.println() → Prints output to the console

Resources

Books:
  • Head First Java by Kathy Sierra
  • Effective Java by Joshua Bloch
Online Platforms:
  • w3schools Java
  • Codecademy
  • LeetCode for Java coding practice

Step-by-Step Guide to Learning Java from Scratch

1. Set Up Your Environment

Before writing any code, you need to set up your development environment.

Install the JDK (Java Development Kit):

Install an IDE (Integrated Development Environment):

2. Understand Java Basics

Start with these core concepts:

Memory Management

Memory Management

Memory management in Java is a critical aspect of the language's runtime system, ensuring efficient use of memory resources and preventing memory leaks. Java memory management involves the automatic allocation and deallocation of objects, which is managed by the Java Virtual Machine (JVM). The JVM handles memory management automatically using its Garbage Collector (GC), which distinguishes it from languages like C or C++ where developers must manually manage memory. The JVM (Java Virtual Machine) memory structure is organized into several key areas that manage the execution of Java programs. Understanding this memory layout is essential for optimizing Java performance and troubleshooting issues like memory leaks or OutOfMemoryError.

Garbage Collection

Garbage Collection

Garbage Collection is the process by which Java automatically removes unused (unreachable) objects from memory (heap), so you don’t have to do it manually.

Java manages memory automatically using the Java Virtual Machine (JVM).

GC primarily manages:

  • Young Generation (Minor GC)
  • Old Generation (Major GC or Full GC)

How GC works:

  • Tracks objects through references.
  • If an object is no longer reachable (no live references), it becomes eligible for GC.

Java Basic Syntax

Java Basic Syntax

Java Main Method

Java Main Method

What is the main() Method in Java? public static void main(String[] args) It is the entry point of any standalone Java application. This is the method where the JVM begins execution of the program.

Variables

Variables

In Java, variables are containers used to store data values. Each variable in Java has a type, which determines what kind of data it can hold.

Types of Variables in Java

  • Local Variables
  • Instance Variables (Non-static fields)
  • Class Variables (Static fields)

Java Data Types A data type is a classification of the type of data that a variable can hold in computer programming.

Data types in Java are classified into two types:

  • Primitive - which include integer, character, boolean, and floating Point type values.
  • Non-primitive - which include Classes, Interfaces, Object type and Array

Scope of Variables in Java

Scope of Variables

The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about Java Scope Variables.

Java Scope Rules can be covered under the following categories.

  • Instance Variables
  • Static Variables
  • Local Variables
  • Parameter Scope
  • Block Scope

Java Operators

Java Operators

In Java, operators are special symbols used to perform operations on variables and values. Java provides a rich set of operators grouped into several categories.

User Input in Java

User Input in Java

In Java, there are multiple ways to get user input, depending on the use case and environment The scanner class can handle input from different places, like as we are typing at the console, reading from a file, or working with data streams. This class was introduced in Java 5. Before that, we used the BufferedReader class (introduced in Java 1.1). As a beginner, it's better to use the Scanner class.

Scanner

  • Import the Scanner class using import java.util.Scanner;
  • Create the Scanner object and connect Scanner with System.in by passing it as an argument i.e., Scanner sc = new Scanner(System.in);
  • When we want to ask the user for input, first print a prompt message so they know what to enter

BufferedReader

Faster than Scanner for large input, but requires exception handling and manual parsing.

Console

Only works in the actual terminal/console, not in most IDEs.

Command Line Arguments

Takes input when the program is run.

3. Control Flow

Control Flow

Conditional Statement

In Java, conditional statements control the flow of execution based on whether a condition is true or false. They allow your program to make decisions. i.e. if a certain condition is true then a block of statements is executed otherwise not. Types of Conditional Statements in Java

  • if Statement
  • if-else Statement
  • if-else if-else Ladder
  • switch Statement
  • Ternary Operator (Shorthand if-else)

Loops

In Java, loops are used to repeat a block of code multiple times based on a condition. They're essential for tasks like iterating through arrays, performing calculations repeatedly, or automating repetitive actions. Types of Loops in Java

  • for loop
  • While loop
  • do-while loop

4. Methods

Methods

In Java, methods are blocks of code that perform a specific task and can be called (invoked) at any point in a program simply by utilizing the method's name. They help in code reuse, modularity, and readability. In Java we call functions as methods, because here the methods can be written only inside class but not outside the class as in C++. Methods are used to tell the behaviour of the object.

Types of Methods

  • Predefined (Built-in): Provided by Java (e.g., System.out.println())
  • User-defined: Created by the programmer
  • Static: Belongs to class, not object (no object needed)
  • Instance: Needs object of the class to be called
  • Void: Returns nothing
  • Return type methods: Returns a value (e.g., int, String)

5. Strings

Strings

A String in Java is a sequence of characters. Strings are immutable (cannot be changed once created), and Java treats them as objects of the String class in java.lang package

Creating Strings

Using String Literals (Recommended)

String name = "SWE";

  • Stored in the String Pool
  • Saves memory by reusing existing objects

Using new Keyword

String city = new String("Mumbai");

  • Stored in Heap memory
  • Creates a new object every time, even if the content is the same

String Memory Allocation

In Java, strings are treated differently in memory based on how they are created. This is crucial for performance and understanding immutability, object reuse, and memory optimization.

Java String Pool (String Constant Pool)

  • Located in the Method Area of JVM memory.
  • Maintains a pool of unique string literals.
  • Saves memory by reusing strings with the same value.

StringBuffer and StringBuilder

StringBuffer and StringBuilder

StringBuffer and StringBuilder are Java classes used to create mutable (changeable) sequences of characters.

Unlike String (which is immutable), you can modify the contents of StringBuffer and StringBuilder objects without creating new objects.

StringBuffer

StringBuffer is a thread-safe, mutable sequence of characters. All methods are synchronized (safe for use by multiple threads).

public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Java");

        sb.append(" Programming");              // Adds text
        sb.insert(4, " Language");              // Inserts at index 4
        sb.replace(0, 4, "Core");               // Replaces "Java" with "Core"
        sb.delete(4, 13);                       // Deletes " Language"

        System.out.println("Result: " + sb);    // Output: CoreProgramming
    }
}

StringBuilder

StringBuilder is not thread-safe, but it is faster. It is ideal when you are working in a single-threaded environment.

public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");

        sb.append(" World");     // Add text at the end
        sb.reverse();            // Reverse the string

        System.out.println("Reversed: " + sb);  // Output: dlroW olleH
    }
}
Tip:
  • Use String when the content does not change.
  • Use StringBuffer in multi-threaded environments where thread safety is needed.
  • Use StringBuilder in single-threaded programs for better performance.

6. Arrays

Arrays

An array in Java is a container object that holds a fixed number of elements of the same data type. It stores elements in a contiguous memory location, and you can access them using index numbers.

7. Java OOPs

OOPs

Java is a purely object-oriented language (except for primitive types) and follows four main principles of OOP:

  • Encapsulation
  • Abstraction
  • Inheritance
  • Polymorphism

Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.

The core idea of OOPs is to bind data and the functions that operate on it, preventing unauthorized access from other parts of the code. Java strictly follows the DRY (Don't Repeat Yourself) Principle, ensuring that common logic is written once (e.g., in parent classes or utility methods) and reused throughout the application.

Inheritance

Inheritance)

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Java. It allows a class (child/subclass) to inherit properties and behaviors (methods) from another class (parent/superclass).

Encapsulation

Encapsulation

Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) principles in Java. It is the process of wrapping data (variables) and the code (methods) that operate on the data into a single unit called a class. Think of it as putting the data and the methods into a capsule (hence the name encapsulation). This allows the internal representation of an object to be hidden from the outside world. Instead of accessing fields directly, other classes interact with them through getter and setter methods.

Polymorphism

Polymorphism

In Java, polymorphism allows a single action (like calling a method) to behave differently based on the object that is performing the action.

Abstraction

Abstraction

Abstraction is the process of hiding internal implementation details and showing only the essential features of an object.

Casting in Java

Casting

Casting is the process of converting a variable from one type to another. Java supports two main types of casting:

  • Primitive Type Casting
  • Reference Type Casting (also called Object Casting)

Object Class

Casting

Object class is the super class of all the classes in java. The Object class reference can be given to any child object or any class object. Every class in the Java system is a descendent (direct or indirect) of the Object class Every class you create in Java automatically extends Object (if no other superclass is specified).

8. Java Collections

Casting

The Java Collection Framework (JCF) is a unified architecture for storing and manipulating groups of objects. It provides ready-to-use classes and interfaces to handle data structures like lists, sets, queues, maps, etc.

  • Package: java.util.*

Why Use Collection Framework?

Let’s say you're building an e-commerce site. You'll need a cart that grows dynamically, a set of unique product categories, and maybe a queue for processing orders. Collections like ArrayList, HashSet, and PriorityQueue make all this easy.

9. Error Handling

Casting

In Java, error handling means catching and responding to problems during your program’s execution - like a file not found, invalid input, or insufficient balance in a bank account.

Understanding error handling in Java is essential for building reliable, robust, and user-friendly applications.

Error handling is the process of responding to unexpected events (errors) that occur during program execution, without crashing the program. Java uses a structured way of doing this using keywords like try, catch, finally, throw, and throws.

Classification

Throwable
├── Error Serious problems (not handled)
│   ├── OutOfMemoryError
│   ├── StackOverflowError
│   └── VirtualMachineError
│
└── Exception Recoverable problems (we handle these)
    ├── Checked (IOException,SQLException) Must be declared or handled
    └── Unchecked (NullPointerException, ArithmeticException) Runtime exceptions

10. Multithreading

Casting

Multithreading is the process of executing multiple threads simultaneously to perform tasks concurrently.

Multithreading allows a program to perform multiple tasks at the same time by running multiple threads in parallel.

Think of a thread as a lightweight process. By using multiple threads, you can make your applications faster, more responsive, and more efficient.

Java provides two ways to create threads:

1. By Extending Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start(); // Starts a new thread
    }
}

2. Implementing Runnable Interface

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
    }
}

Preferred: Implementing Runnable is better because Java supports multiple interfaces but only single inheritance.

Thread Lifecycle

New – Created but not started. Runnable – Ready to run. Running – Currently executing. Blocked/Waiting – Waiting for resources. Terminated – Completed or stopped.

Thread Synchronization

Casting

Thread Synchronization is a mechanism to control the access of multiple threads to shared resources.

When two or more threads try to access a shared resource simultaneously, there can be inconsistent behavior or data corruption. To prevent this, we use synchronization to make sure only one thread can access the critical section at a time.

Thread safety

Casting

Thread safety means that a class or method behaves correctly when accessed by multiple threads simultaneously. A thread-safe component prevents unintended interactions, even if several threads operate on the same data.

Thread safety is crucial in multithreaded Java programs to avoid issues like data corruption, race conditions, and inconsistent behavior.

11. Singleton

Casting

A Singleton is a design pattern that ensures only one instance of a class is created and provides a global access point to that instance.

You use Singleton when you only need one object - like a logger, a database connection pool, or a configuration manager. Imagine having multiple connections trying to manage a single printer - chaos!

12. Lazy Initialization

Casting

Lazy Initialization means delaying the creation (or initialization) of an object or resource until it is actually needed - instead of doing it during program start-up.

13. Wrapper Classes

Casting

In Java, wrapper classes are object representations of primitive data types.

Java has eight primitive types:

  • byte, short, int, long, float, double, char, boolean

14. Regex

Regex (Regular Expression) is a pattern-matching technique used to search, manipulate, and validate strings based on specific patterns.

In Java, regex is provided via the java.util.regex package, In Java, Regex is powered by two core classes: Pattern to define the rules, and Matcher to apply those rules to user input..

15. Java File Handling

File handling is one of the core features in Java that allows you to create, read, update, and delete files from within your program. Java provides robust APIs to handle file operations using streams.

File handling is used in:

  • Logging system outputs
  • Reading configuration files
  • Writing reports or logs
  • Storing persistent user data (e.g., CSV, TXT, JSON)

Stream

A stream in Java represents a sequence of data. It is used to read from or write to files. Streams are of two types:

  • Byte Stream: For binary data (e.g., images, videos) → Classes: FileInputStream, FileOutputStream
  • Character Stream: For textual data (e.g., .txt, .csv) → Classes: FileReader, FileWriter, BufferedReader, BufferedWriter

15. JDBC

JDBC stands for Java Database Connectivity. It is a Java API that allows Java applications to connect to relational databases like MySQL, Oracle, PostgreSQL, etc.

Why is JDBC Used?

  • To establish a connection between a Java application and a database
  • To execute SQL queries
  • To retrieve and process data
  • To update or modify database records

16. LDAP

To perform LDAP (Lightweight Directory Access Protocol) operations using Java, you typically use the JNDI (Java Naming and Directory Interface API. This allows Java applications to interact with directory services such as Active Directory, OpenLDAP, or ApacheDS.

17. Serialization

Serialization is the process of converting a Java object into a byte stream, so it can be easily saved to a file, sent over a network, or stored in memory or a database.

Deserialization is the reverse process - converting the byte stream back into a Java object.

18. Call by Value

When a variable is passed to a method, a copy of the variable's value is made and passed.

  • For primitive types, this means the actual value is copied.
  • For objects, the value of the reference (i.e., the memory address) is copied — not the actual object itself.

About

Welcome to this Java programming tutorial. In this repo, you'll learn everything from Java basics to advanced features like OOP, collections, and multi-threading.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages