Full Course Java

 

👨‍💻 Step 1: Learn the Basics of Java


🔹 1. Java Syntax

Java is a statically-typed, object-oriented programming language. A basic Java program looks like this:

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

Explanation:

  • public class HelloWorld - defines a class.

  • public static void main - entry point of the program.

  • System.out.println - prints output.


🔹 2. Data Types and Variables

Java has two types of data types:

  • Primitive: int, float, char, boolean, etc.

  • Non-primitive: String, Arrays, Objects, etc.

Example:

java
int age = 25; double price = 99.99; char grade = 'A'; boolean isJavaFun = true; String name = "Rehan";

🔹 3. Operators

Operators perform operations on variables and values:

  • Arithmetic: +, -, *, /, %

  • Relational: ==, !=, >, <, >=, <=

  • Logical: &&, ||, !

Example:

java
int a = 10, b = 5; System.out.println(a + b); // Output: 15 System.out.println(a > b); // Output: true

🔹 4. Control Statements

Used to control flow of execution.

if-else:

java
int age = 18; if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are a minor."); }

switch:

java
int day = 3; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); }

Loops:

  • for loop:

java
for(int i = 0; i < 5; i++) { System.out.println("i = " + i); }
  • while loop:

java
int i = 0; while(i < 5) { System.out.println("i = " + i); i++; }
  • do-while loop:

java
int i = 0; do { System.out.println("i = " + i); i++; } while(i < 5);

🔹 5. Functions / Methods

Methods are blocks of code that perform a task.

java
public class Demo { public static void greet(String name) { System.out.println("Hello, " + name); } public static void main(String[] args) { greet("Rehan"); } }

🔹 6. Arrays

Arrays store multiple values of the same type.

Example:

java
int[] numbers = {10, 20, 30, 40}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }




🧰 Step 2: Object-Oriented Programming (OOP) in Java

Object-Oriented Programming (OOP) is the core of Java. It helps to build reusable, scalable, and well-structured code by organizing it into objects.

🔹 Core OOP Concepts:


🔸 1. Classes and Objects

  • A class is a blueprint for creating objects.

  • An object is an instance of a class.

Example:

java
class Car { String color; void displayColor() { System.out.println("Color: " + color); } } public class Main { public static void main(String[] args) { Car myCar = new Car(); // Object created myCar.color = "Red"; // Accessing field myCar.displayColor(); // Calling method } }

🔸 2. Inheritance

  • Inheritance allows a class to acquire the properties of another class using the extends keyword.

Example:

java
class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.sound(); // Inherited method d.bark(); // Own method } }

🔸 3. Polymorphism

  • It means one name many forms. You can perform the same action in different ways.

a) Compile-time Polymorphism (Method Overloading)

java
class MathOperation { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } }

b) Runtime Polymorphism (Method Overriding)

java
class Animal { void sound() { System.out.println("Animal makes sound"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal obj = new Cat(); // Upcasting obj.sound(); // Calls overridden method } }

🔸 4. Abstraction

  • Hides internal implementation and shows only functionality using abstract classes or interfaces.

Example using abstract class:

java
abstract class Shape { abstract void draw(); // abstract method } class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } }

🔸 5. Encapsulation

  • Wrapping data (variables) and code (methods) together using private fields and public methods.

Example:

java
class Person { private String name; public void setName(String n) { name = n; } public String getName() { return name; } }

🔸 6. Constructors

  • Special method that initializes an object. Same name as class and no return type.

java
class Student { String name; Student(String n) { name = n; } void display() { System.out.println("Student Name: " + name); } }

🔸 7. this and super Keywords

  • this refers to the current class instance.

  • super refers to the parent class.

Example with this:

java
class Car { String color; Car(String color) { this.color = color; // refers to the class variable } void display() { System.out.println("Color: " + color); } }

Example with super:

java
class Vehicle { void start() { System.out.println("Vehicle Started"); } } class Bike extends Vehicle { void start() { super.start(); // calling parent method System.out.println("Bike Started"); } }




🗂️ Step 3: Core Java APIs

Java provides a powerful set of built-in libraries known as APIs (Application Programming Interfaces) that help developers write efficient and scalable applications. These APIs cover everything from data structures to I/O, threading, and more.


🔹 1. java.lang Package

This is automatically imported in every Java program and includes classes for basic language features.

Key Classes:

  • Object

  • String

  • Math

  • System

  • Integer, Double, etc.

Example: Using Math and String

java
public class LangExample { public static void main(String[] args) { String name = "Java"; System.out.println("Length: " + name.length()); int result = Math.max(10, 20); System.out.println("Max: " + result); } }

🔹 2. java.util Package – Collections Framework

It includes data structures like:

  • List, ArrayList, LinkedList

  • Set, HashSet

  • Map, HashMap

Example: Using ArrayList and HashMap

java
import java.util.*; public class UtilExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Rehan"); names.add("Khan"); Map<String, Integer> scores = new HashMap<>(); scores.put("Math", 90); scores.put("Science", 85); System.out.println(names); System.out.println(scores); } }

🔹 3. java.io Package – Input/Output

Used for reading and writing data to files or other sources.

Example: Writing and reading from a file

java
import java.io.*; public class FileExample { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("example.txt"); writer.write("Hello, Java File IO!"); writer.close(); BufferedReader reader = new BufferedReader(new FileReader("example.txt")); String line = reader.readLine(); System.out.println("File says: " + line); reader.close(); } }

🔹 4. Exception Handling

Ensures program continues running even when errors occur.

Example: Try-Catch Block

java
public class ExceptionExample { public static void main(String[] args) { try { int x = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } } }

🔹 5. Multithreadingjava.lang.Thread

Allows concurrent execution of code (parallel tasks).

Example: Simple Thread

java
class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } public static void main(String[] args) { MyThread t = new MyThread(); t.start(); } }

🔹 6. String Manipulation

String is a class used heavily in Java.

Example:

java
public class StringExample { public static void main(String[] args) { String str = "Hello Java!"; System.out.println(str.toUpperCase()); System.out.println(str.replace("Java", "World")); } }

✅ Summary:

TopicKey Classes/Uses
java.langCore classes like String, Object
java.utilCollections like List, Map
java.ioFile read/write operations
Exception Handlingtry, catch, finally
MultithreadingThread, Runnable
String Manipulation




🌐 Step 4: JDBC and Database

🔹 What is JDBC?

JDBC (Java Database Connectivity) is a Java API that allows Java programs to connect and interact with relational databases such as MySQL, Oracle, PostgreSQL, etc.


🔹 Key Concepts to Learn:

✅ 1. Connecting Java to MySQL/Oracle

To connect Java to a database, you'll need:

  • A JDBC driver (e.g., MySQL Connector/J for MySQL)

  • A connection URL

  • Username and password

🔸 Example:

java
import java.sql.*; public class DBConnectionExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/testdb"; String user = "root"; String password = "password"; try { Connection conn = DriverManager.getConnection(url, user, password); System.out.println("Connected to database!"); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }

✅ 2. CRUD Operations

CRUD = Create, Read, Update, Delete

🔸 Example (Insert Data):

java
String sql = "INSERT INTO students (name, age) VALUES (?, ?)"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, "John"); stmt.setInt(2, 22); stmt.executeUpdate();

🔸 Example (Read Data):

java
String sql = "SELECT * FROM students"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("name") + " - " + rs.getInt("age")); }

✅ 3. PreparedStatement

PreparedStatement prevents SQL injection and allows you to safely use input values.

🔸 Example:

java
String sql = "UPDATE students SET age = ? WHERE name = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, 23); stmt.setString(2, "John"); stmt.executeUpdate();

✅ 4. Transactions

Transactions ensure that a group of operations either all succeed or all fail.

🔸 Example:

java
try { conn.setAutoCommit(false); PreparedStatement stmt1 = conn.prepareStatement("UPDATE accounts SET balance = balance - 500 WHERE id = 1"); stmt1.executeUpdate(); PreparedStatement stmt2 = conn.prepareStatement("UPDATE accounts SET balance = balance + 500 WHERE id = 2"); stmt2.executeUpdate(); conn.commit(); // If both succeed } catch (SQLException e) { conn.rollback(); // If any fails e.printStackTrace(); }

🧠 Summary:

  • JDBC helps connect Java to databases.

  • You should be comfortable with executing SQL from Java using Connection, Statement, and PreparedStatement.

  • Use transactions for complex operations to maintain data integrity.




🔌 Step 5: Java Collections Framework

The Java Collections Framework (JCF) is a set of classes and interfaces that implement commonly reusable data structures like lists, sets, queues, and maps.


🔹 Important Interfaces and Their Implementations:


✅ 1. List Interface

  • Ordered collection (insertion order is maintained)

  • Allows duplicates

Common Implementations:
  • ArrayList: Resizable array, fast for reading, slow for insert/delete in between.

  • LinkedList: Doubly-linked list, faster insert/delete, slower random access.

🔸 Example:
java
List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob"); System.out.println(names); // [Alice, Bob]

✅ 2. Set Interface

  • Unordered collection

  • No duplicate elements

Common Implementations:
  • HashSet: No order, fast access

  • TreeSet: Sorted in natural order

🔸 Example:
java
Set<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(10); // Duplicate, ignored System.out.println(numbers); // [10, 20]

✅ 3. Map Interface

  • Key-value pairs

  • Keys must be unique

Common Implementations:
  • HashMap: Unordered

  • TreeMap: Sorted by keys

🔸 Example:
java
Map<String, Integer> marks = new HashMap<>(); marks.put("Math", 95); marks.put("Science", 90); System.out.println(marks.get("Math")); // 95

✅ 4. Queue Interface

  • Used for First In First Out (FIFO) operations

  • Common classes: LinkedList, PriorityQueue

🔸 Example:
java
Queue<String> queue = new LinkedList<>(); queue.add("Task1"); queue.add("Task2"); System.out.println(queue.poll()); // Task1

✅ 5. Stack Class

  • Last In First Out (LIFO) data structure

  • Not part of java.util.Queue interface but often grouped in collections

🔸 Example:
java
Stack<Integer> stack = new Stack<>(); stack.push(1); stack.push(2); System.out.println(stack.pop()); // 2


⚠️ Step 6: Java Exception Handling

Exception Handling in Java helps you manage runtime errors gracefully without crashing your program. It improves code reliability and debugging.


🔹 Types of Exceptions:

✅ 1. Checked Exceptions

  • Checked at compile-time

  • Must be handled using try-catch or declared using throws

  • Example: IOException, SQLException

✅ 2. Unchecked Exceptions

  • Occur at runtime

  • Not required to handle explicitly

  • Example: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException


🔹 Keywords in Exception Handling:

try

  • Contains code that may throw an exception

catch

  • Handles the exception thrown in try block

finally

  • Always executed (whether exception occurs or not), used to close resources

throw

  • Used to explicitly throw an exception

throws

  • Declares an exception that might be thrown


🔸 Example 1: try-catch-finally

java
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero: " + e.getMessage()); } finally { System.out.println("This block always executes."); }

🔸 Example 2: throw and throws

java
public void checkAge(int age) throws Exception { if (age < 18) { throw new Exception("Underage - Not eligible"); } System.out.println("Eligible to vote."); }

🧠 Best Practices:

  • Catch specific exceptions instead of using a generic Exception

  • Use finally to close resources (like DB connections, files)

  • Avoid catching Exception unless absolutely necessary

  • Don’t suppress exceptions silently

🌍 Step 6: Web Development with Java

Java is widely used in web development to build dynamic, secure, and scalable web applications. In this step, you'll learn how to build server-side Java applications using Servlets, JSP, and follow the MVC pattern.


🔹 Technologies to Learn:


✅ 1. Servlets

  • Java classes that handle HTTP requests and responses

  • Runs on a servlet container like Apache Tomcat

  • Lifecycle methods: init(), service(), destroy()

🧑‍💻 Example: HelloServlet.java

java
@WebServlet("/hello") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().println("Hello, Java Web!"); } }

✅ 2. JSP (JavaServer Pages)

  • Helps embed Java code in HTML using special tags

  • Easier than writing full Servlets for dynamic pages

🧑‍💻 Example: hello.jsp

jsp
<%@ page language="java" %> <html> <body> <h2>Hello, JSP!</h2> Current time: <%= new java.util.Date() %> </body> </html>

✅ 3. JSTL (JSP Standard Tag Library)

  • Provides tags for common tasks like loops, conditions, and formatting

  • Makes JSP code cleaner and more readable

🧑‍💻 Example: Using JSTL Loop

jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <ul> <c:forEach var="item" items="${itemList}"> <li>${item}</li> </c:forEach> </ul>

🔄 MVC Design Pattern

MVC (Model-View-Controller) is a design pattern that separates concerns in a web application.

ComponentRole
ModelBusiness logic and data (Java Beans or DB layer)
ViewUser interface (JSP)
ControllerHandles user input and routes (Servlets)

📌 Example Flow:

  1. User requests a page → Servlet (Controller)

  2. Servlet processes logic → Java Bean (Model)

  3. Servlet forwards to JSP (View) → Display data


✅ Summary:

TechnologyPurpose
ServletJava class to process HTTP requests
JSPHTML + Java for UI rendering
JSTLJSTL tags to simplify JSP
MVC




🔒 Step 7: Spring & Hibernate (Advanced Java)

As your Java skills mature, mastering Spring Framework and Hibernate will enable you to build enterprise-grade, scalable, and secure applications.


✅ Spring Framework Modules

Spring is a powerful and flexible framework for building Java applications with dependency injection, web MVC support, security, and more.


1. Spring Core

  • The foundation of the Spring Framework

  • Provides Dependency Injection (DI) and Inversion of Control (IoC)

🧠 Example: Injecting a bean

java
@Component public class UserService { public void registerUser() { System.out.println("User registered!"); } }

2. Spring MVC

  • Helps build web applications using the MVC design pattern

  • Manages HTTP requests and routes them to controllers

🧠 Example: Basic Controller

java
@Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; // home.jsp or home.html } }

3. Spring Boot

  • Simplifies Spring configuration and setup

  • Provides embedded servers (like Tomcat) and auto-configuration

🧠 Example: Spring Boot Application

java
@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

4. Spring Security

  • Adds authentication and authorization to your app

  • Easily integrates with Spring Boot

🧠 Features:

  • User login/logout

  • Role-based access

  • JWT support


✅ Hibernate ORM (Object Relational Mapping)

Hibernate is used to map Java objects to database tables and simplify database operations.


1. ORM Concepts

  • Maps Java classes to DB tables

  • Reduces boilerplate SQL code


2. Annotations

  • Define how Java fields map to database columns

🧠 Example:

java
@Entity public class Employee { @Id @GeneratedValue private int id; @Column(name = "name") private String name; }

3. HQL (Hibernate Query Language)

  • Hibernate’s object-oriented query language

🧠 Example:

java
Query query = session.createQuery("FROM Employee WHERE name = :name"); query.setParameter("name", "John"); List<Employee> result = query.list();

4. Transactions

  • Ensures data integrity and consistency during DB operations

🧠 Example:

java
Transaction tx = session.beginTransaction(); session.save(employee); tx.commit();

🔄 Summary

FrameworkFeatures
Spring CoreDependency Injection
Spring MVCWeb MVC Architecture
Spring BootRapid development and auto-config
Spring SecuritySecure login and access control
Hibernate





🧪 Step 8: Unit Testing

Testing ensures that your code works correctly, is maintainable, and helps prevent bugs during development and after deployment. In Java, JUnit and Mockito are two powerful tools for writing unit tests.


🔹 Tools for Unit Testing


✅ 1. JUnit (Java Unit Testing Framework)

  • Most widely used framework for unit testing in Java

  • Allows you to test methods independently

  • Supports annotations like @Test, @BeforeEach, @AfterEach

🧠 Example: Basic JUnit Test

java
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test void testAddition() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }

✅ 2. Mockito (Mocking Framework)

  • Allows you to mock dependencies for testing in isolation

  • Great for testing service and controller layers

🧠 Example: Mocking a Repository

java
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class UserServiceTest { @Mock UserRepository userRepository; @InjectMocks UserService userService; @Test void testFindUserById() { MockitoAnnotations.openMocks(this); when(userRepository.findById(1)).thenReturn(new User(1, "Rehan")); User result = userService.getUserById(1); assertEquals("Rehan", result.getName()); } }

📚 Key Annotations

AnnotationDescription
@TestMarks a method as a test method
@BeforeEachRuns before each test method
@AfterEachRuns after each test method
@MockCreates a mock instance
@InjectMocksInjects mock fields into object

🎯 Best Practices

  • Write tests for every method you write.

  • Use meaningful test method names.

  • Keep your tests isolated, independent, and fast.

  • Test edge cases and error conditions.

  • Automate tests as part of CI/CD pipeline.



⚙️ Step 9: Build Tools and Version Control

These tools help you automate builds, manage project dependencies, and collaborate efficiently with teams.


🔹 1. Maven or Gradle (Build Tools)

These tools help manage your project's lifecycle — compile, test, package, and deploy.


Apache Maven

  • XML-based configuration (pom.xml)

  • Strong convention over configuration

  • Easy integration with popular tools and frameworks

🧠 Example pom.xml Snippet:

xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>

Gradle

  • Uses Groovy or Kotlin DSL

  • Faster than Maven with incremental builds

  • More flexible and powerful for complex projects

🧠 Example build.gradle:

groovy
dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' }

🆚 Maven vs Gradle:

FeatureMavenGradle
LanguageXMLGroovy/Kotlin DSL
SpeedSlowerFaster
FlexibilityLess FlexibleHighly Flexible

🔹 2. Git & GitHub (Version Control)

Git is a distributed version control system. GitHub is a cloud platform for hosting Git repositories.

🔧 Git Basics:

CommandPurpose
git initInitialize a Git repo
git clone <url>Clone a repo from GitHub
git add .Stage all changes
git commit -m "message"Commit changes
git push origin mainPush to GitHub
git pull origin mainPull latest changes

🧠 Use Branching:

  • main branch for production

  • dev for development

  • Feature branches: feature/login, bugfix/ui-crash, etc.


🔹 3. CI/CD Basics

CI/CD = Continuous Integration / Continuous Deployment

  • Automates testing, building, and deploying your code.

  • Tools: GitHub Actions, Jenkins, GitLab CI, CircleCI

🧠 Typical CI/CD Workflow:

  1. Code pushed to GitHub

  2. CI pipeline runs tests and builds

  3. CD pipeline deploys to staging or production


📌 Why This Step Is Important

  • Efficient team collaboration with Git/GitHub

  • Clean and automated builds with Maven/Gradle

  • Faster releases and fewer bugs with CI/CD


🚀 Step 10: Deployment and DevOps (Optional but Powerful)

This step is about making your application production-ready, scalable, and automated.


🔹 1. Docker (Containerization)

Docker lets you package your Java application and its dependencies into a lightweight container that runs anywhere.

Why Docker?

  • Consistent environment (dev = prod)

  • Easy to scale and ship

  • Works great with CI/CD and cloud

🧠 Sample Dockerfile for Java App

Dockerfile
FROM openjdk:17 COPY target/myapp.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]

Basic Commands

bash
docker build -t myapp . docker run -p 8080:8080 myapp

🔹 2. Jenkins (for CI/CD)

Jenkins is a popular tool to automate building, testing, and deploying your Java app.

Key Jenkins Features

  • Job scheduling (daily builds, triggers)

  • Integration with GitHub, Docker, Maven/Gradle

  • Web interface to track builds

🧠 Sample Jenkins Pipeline (Groovy)

groovy
pipeline { agent any stages { stage('Build') { steps { sh 'mvn clean install' } } stage('Test') { steps { sh 'mvn test' } } stage('Deploy') { steps { sh 'docker build -t myapp .' sh 'docker run -d -p 8080:8080 myapp' } } } }

🔹 3. AWS or Cloud Platforms

Deploy and scale your app using cloud services like:

AWS

  • EC2 (VM hosting)

  • S3 (Storage)

  • RDS (Databases)

  • Elastic Beanstalk (App deployment)

Alternatives

  • Microsoft Azure

  • Google Cloud Platform (GCP)

  • Heroku (beginner-friendly)

🧠 Simple EC2 Deployment Steps

  1. Launch EC2 instance

  2. SSH into the server

  3. Install Java & upload your JAR file

  4. Run: java -jar myapp.jar


📌 Why Learn DevOps?

BenefitDescription
🏗 Automated DeploymentPush code → Deploy instantly
🚀 Faster ReleasesCI/CD cuts manual steps
🌍 Scalable & ReliableCloud services handle the load
📦 Environment ConsistencyDocker avoids "works on my machine"

✅ Summary of Step 10 Tools

ToolPurpose
DockerContainerize Java apps
JenkinsAutomate build & deployment
AWS/GCPCloud hosting and scaling
ORM, Annotations, Transactions, HQL







Clean architecture and maintainability





toUpperCase(), substring(), etc.






Comments

Popular posts from this blog

Git And GitHub Collaborators and teams

How to create React JS application

📱 Top 50 Android Developer Interview Questions and Answers