Full Course Java
- Get link
- X
- Other Apps
๐จ๐ป 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:
javapublic 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:
javaint 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:
javaint 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:
javaint age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
switch:
javaint 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:
javafor(int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
-
while loop:
javaint i = 0;
while(i < 5) {
System.out.println("i = " + i);
i++;
}
-
do-while loop:
javaint i = 0;
do {
System.out.println("i = " + i);
i++;
} while(i < 5);
๐น 5. Functions / Methods
Methods are blocks of code that perform a task.
javapublic 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:
javaint[] 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:
javaclass 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:
javaclass 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)
javaclass MathOperation {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
b) Runtime Polymorphism (Method Overriding)
javaclass 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:
javaabstract 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:
javaclass 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.
javaclass 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:
javaclass Car {
String color;
Car(String color) {
this.color = color; // refers to the class variable
}
void display() {
System.out.println("Color: " + color);
}
}
Example with super:
javaclass 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
javapublic 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
javaimport 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
javaimport 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
javapublic class ExceptionExample {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
๐น 5. Multithreading – java.lang.Thread
Allows concurrent execution of code (parallel tasks).
✅ Example: Simple Thread
javaclass 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:
javapublic 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:
Topic Key Classes/Uses java.langCore classes like String, Object java.utilCollections like List, Map java.ioFile read/write operations Exception Handling try, catch, finallyMultithreading Thread, RunnableString 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:
javaimport 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):
javaString 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):
javaString 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:
javaString 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:
javatry {
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:
javaList<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:
javaSet<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:
javaMap<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:
javaQueue<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:
javaStack<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
javatry {
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
javapublic 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.
Component Role Model Business logic and data (Java Beans or DB layer) View User interface (JSP) Controller Handles user input and routes (Servlets)
๐ Example Flow:
-
User requests a page → Servlet (Controller)
-
Servlet processes logic → Java Bean (Model)
-
Servlet forwards to JSP (View) → Display data
✅ Summary:
Technology Purpose Servlet Java class to process HTTP requests JSP HTML + Java for UI rendering JSTL JSTL 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:
javaQuery 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:
javaTransaction tx = session.beginTransaction();
session.save(employee);
tx.commit();
๐ Summary
Framework Features Spring Core Dependency Injection Spring MVC Web MVC Architecture Spring Boot Rapid development and auto-config Spring Security Secure 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
javaimport 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
javaimport 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
Annotation Description @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:
groovydependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
๐ Maven vs Gradle:
Feature Maven Gradle Language XML Groovy/Kotlin DSL Speed Slower Faster Flexibility Less Flexible Highly Flexible
๐น 2. Git & GitHub (Version Control)
Git is a distributed version control system. GitHub is a cloud platform for hosting Git repositories.
๐ง Git Basics:
Command Purpose 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:
-
Code pushed to GitHub
-
CI pipeline runs tests and builds
-
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
DockerfileFROM openjdk:17
COPY target/myapp.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
✅ Basic Commands
bashdocker 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)
groovypipeline {
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
-
Launch EC2 instance
-
SSH into the server
-
Install Java & upload your JAR file
-
Run: java -jar myapp.jar
๐ Why Learn DevOps?
Benefit Description ๐ Automated Deployment Push code → Deploy instantly ๐ Faster Releases CI/CD cuts manual steps ๐ Scalable & Reliable Cloud services handle the load ๐ฆ Environment Consistency Docker avoids "works on my machine"
✅ Summary of Step 10 Tools
Tool Purpose Docker Containerize Java apps Jenkins Automate build & deployment AWS/GCP Cloud hosting and scaling
ORM, Annotations, Transactions, HQL
Clean architecture and maintainability
toUpperCase(), substring(), etc.
- Get link
- X
- Other Apps
Comments
Post a Comment