Lecture 1

hitarth's Vault // Exported at - 08:45 PM

Mid sem tak ka to hai us PDF me, uske baad ye karlo :

  • REST API (Get Post Delete) // JPA Repository use karna & MySQL se connect karna, Constraints wagera use karna UserModel.java wagera me
  • For JWT AUTH : Spring project me security configure wagera karna, Filter Chain banana (SecurityFilterChain Class use karna), PasswordEncoder (Bcrypt wagera), Basics JWT Token Helper class Methods like generateToken, isTokenExpired

Stack :

Main.java

package stackexample;

public class Main {
    public static void main(String[] args) {
        Stack stk = new Stack(10);
        stk.push(10);
        stk.push(11);
        stk.push(12);
        stk.pop();
        stk.isEmpty();
        System.out.println(stk.top());
    }
}

Stack.java

package stackexample;

class Stack {
    private int[] store;
    private int top;
    private int max_len;

    public Stack(int size) {
        this.store = new int[size];
        this.max_len = size - 1;
        this.top = -1;
    }

    public void push(int item) {
        if (this.top == this.max_len) {
            System.out.println("Stack Overflow");
        } else {
            this.top++;
            this.store[this.top] = item;
        }
    }

    public void pop() {
        if (this.top == -1) {
            System.out.println("Stack Underflow");
        } else {
            System.out.println("Popped: " + this.store[this.top]);
            this.top--;
        }
    }

    public int top() {
        return this.store[this.top];
    }

    public void isEmpty() {
        if (this.top == -1) {
            System.out.println("Stack is empty");
        } else {
            System.out.println("Stack is not empty");
        }
    }
}

What is instance variable in Java? Instance variables in Java are non-static variables which are defined in a class outside any method, constructor or a block.

  • The interface will be public as we want others to be able to access it.
  • All methods defined in an interface should be implemented in the class implementing the interface.
  • @Override is used to override the method defined in an interface through a method defined in a class implementing the interface.
  • The access specifiers used with classes are private, protected and public. While in Interface only one specifier is used- Public.

Tight Coupling :

  • input will not govern the output
  • Pasted image 20240120094318.png
  • Pasted image 20240120094438.png

Example of tight coupling :

Pasted image 20240222131559.png

Loose Coupling :

Pasted image 20240120120837.png


Variable Arguments - VarArgs :

package collegeWDA.vararguments;

public class VarArgs {

    static void varTest(int ...a) {
        System.out.println("Number of parameters: " + a.length);

        for (int i : a) {
            System.out.print(i + " ");
        }
    }

    public static void main(String[] args) {
        // meth1(a)
        // meth1(a,b)
        // meth1(a,b,c)
        varTest(1,2,3,4,5);
        // or
        VarArgs testing = new VarArgs();
        testing.varTest(8,9,10);
    }
}

Pasted image 20240127101924.png

  • this implements polymorphism

Poplymorphism :

Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.

Types of Java Polymorphism: In Java Polymorphism is mainly divided into two types:

Extended Interface :

Pasted image 20240127124856.png
Pasted image 20240127125203.png
Pasted image 20240127125258.png

Vectors :

  • if old array is filled, then it doubles the size of the old array : 20 size ka filled then it'll create an array of size 40
  • Pasted image 20240127104549.png
  • Pasted image 20240127104922.png
  • Pasted image 20240127105112.png
    • Classes : Non Dotted box
    • Dotted ones are interfaces.
    • Map extends collection, collection se hamne List and Set banaye, List and set further have 2 implementations.
    • Arraylist, linkedList HashSet, TreeSet, HashMap, TreeMap will be used the regularly.
    • Set : HashSet (un sorted) and TreeSet (Sorted)
    • Map : HashMap (at most one null key and many null values) and TreeMap (no null key allowed but may contain null values, sorted by key)

Pasted image 20240203094014.png
Pasted image 20240203094237.png
Pasted image 20240203094436.png

1. ArrayList:

  • ArrayList is a dynamic array implementation of the List interface.
  • It allows elements to be added or removed dynamically, and it automatically resizes itself when needed.
  • Elements can be accessed by their index.
  • It is not synchronized, so it's not thread-safe for concurrent access.
  • Offers fast element retrieval (O(1)) but slower insertion and deletion in the middle (O(n)).

2. LinkedList:

  • LinkedList is a doubly linked list implementation of the List interface.
  • It consists of nodes where each node contains a data element and references to the next and previous nodes.
  • Allows for fast insertion and deletion at any position by simply updating references.
  • Elements can be accessed sequentially or by index, but random access is slower compared to ArrayList.
  • Not synchronized, so not thread-safe for concurrent access.

3. HashSet:

  • HashSet is an implementation of the Set interface that uses a hash table for storage.
  • It does not allow duplicate elements, and it does not guarantee the order of elements.
  • Offers constant-time performance for basic operations (add, remove, contains) on average.
  • Not synchronized, so not thread-safe for concurrent access.
  • The iteration order is not guaranteed and may change over time.

4. TreeSet:

  • TreeSet is an implementation of the SortedSet interface that uses a self-balancing binary search tree (Red-Black Tree) for storage.
  • Elements are stored in sorted order (natural ordering or by a specified comparator).
  • Does not allow duplicate elements.
  • Offers guaranteed log(n) time cost for basic operations (add, remove, contains).
  • Not synchronized, so not thread-safe for concurrent access.

5. HashMap:

  • HashMap is an implementation of the Map interface that stores key-value pairs.
  • It uses a hash table for storage and allows null keys and values (except in concurrent environments).
  • Offers constant-time performance for basic operations (put, get, remove) on average.
  • Not synchronized, so not thread-safe for concurrent access, but you can use Collections.synchronizedMap() to create a synchronized map.
  • Iteration order is not guaranteed and may change over time.

6. TreeMap:

  • TreeMap is an implementation of the SortedMap interface that uses a self-balancing binary search tree (Red-Black Tree) for storage.
  • Elements are stored in sorted order based on their keys.
  • Does not allow duplicate keys.
  • Offers guaranteed log(n) time cost for basic operations (put, get, remove).
  • Not synchronized, so not thread-safe for concurrent access.
package collegeWDA.Collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<String>();
        List<Integer> intList = new ArrayList<>(); // don't use <int>

        System.out.println(stringList.size());
        System.out.println(stringList);
        stringList.add("Hello");
        stringList.add("World");
        stringList.add(1, "in Between");
        System.out.println(stringList); // → [Hello, in Between, World]
        stringList.remove(1);
        System.out.println(stringList.indexOf("World")); // → 1
        System.out.println(stringList.contains("Hello")); // → true
        stringList.add("bruh");
        stringList.add("dawg");
        // list now contains: [Hello, World, bruh, dawg]

        List<String> subList = stringList.subList(1, 2);
        System.out.println(subList); // → [World]

        // labmda function
        // s is an iterator here
        stringList.forEach((s) -> {
            if (s.endsWith("g"))
                System.out.println(s); // → dawg
        });

        /* ------------------------------------------------------ */

        // converting ArrayList to Array, (array is much faster than a list)
        List<Integer> aLi = new ArrayList<>();
        aLi.add(1);
        aLi.add(2);
        aLi.add(3);

        Integer[] arr = new Integer[aLi.size()];
        arr = aLi.toArray(arr); // converting ArrayList to Array
        System.out.println(Arrays.toString(arr)); // → [1, 2, 3]

        /* ------------------------------------------------------ */
        // we can convert an array to a list as well

        List<Integer> convertedList = new ArrayList<>(); // or // List<Integer> convertedList;
        convertedList = Arrays.asList(arr);
        System.out.println(convertedList); // → [1, 2, 3]

        /* ------------------------------------------------------ */
        // another variant of a for loop

        for(int it: convertedList) {
            System.out.println(it); // it denotes the element and not the index of the element
        }
    }
}
package com.hitarth.IIITL2024;

import java.util.*;

// Binary Search
public class temp {

    public static <HashMapD> void main(String[] args) {
        /* ------------------------------------------------------ */
        // ArrayList
        List<String> aL = new ArrayList<>();

        System.out.println("The size of list aL: " + aL.size()); // → 0

        aL.add("asd");
        aL.add("ASD");
//        aL.add(2, "123"); // is also possible
        aL.add("123");

        for (String item : aL) {
            System.out.print(item + " ");
        }
        System.out.println("The size of list aL: " + aL.size()); // → 3
        aL.remove(1);
        System.out.println("updated list aL: " + aL); // → [asd, 123]
        System.out.println(" Index of d: " + aL.indexOf("123")); // → 1

        List<String> subLst = aL.subList(0, 1); // .subList(fromIndex, toIndex) → [fromIndex, toIndex)
        System.out.println("Sublist: " + subLst); // → [asd]

        aL.forEach(item -> System.out.print(item + " ")); // → asd 123

        aL.forEach(item -> {
            if (item.endsWith("3")) {
                System.out.println(" " + item + " "); // → 123
            }
        });
        /* ------------------------------------------------------ */
//ArrayList to Array (faster operations)

        List<Integer> aL1 = new ArrayList<>();
        aL1.add(1);
        aL1.add(2);
        aL1.add(3);
        aL1.add(4);

        Integer[] arr = new Integer[aL1.size()];
        arr = aL1.toArray(arr);

        for (int it : arr) {
            System.out.print(it + " "); // → 1 2 3 4
        }

        /* ------------------------------------------------------ */
//Array to ArrayList
        List<Integer> cL = new ArrayList<>();
        cL = Arrays.asList(arr);

        /* ------------------------------------------------------ */
//Set
        Set<String> names = new HashSet<>();
        names.add("bruh");
        names.add("bruh");
        names.add("dawg");
        names.add("lmao");

        System.out.println(names); // → [lmao, bruh, dawg]
        names.forEach(name -> System.out.print(name + " ")); // → lmao bruh dawg
        /* ------------------------------------------------------ */
//Map
        Map<String, Integer> tm = new TreeMap<>();
        tm.put("Alice1", 1);
        tm.put("Alice2", 2);
        tm.put("Alice3", 3);
        System.out.println(tm); // → {Alice1=1, Alice2=2, Alice3=3}
        tm.replace("Alice1", 4);
        System.out.println(tm); // → {Alice1=4, Alice2=2, Alice3=3}
        System.out.println(tm.get("Alice1")); // → 4

        /* ------------------------------------------------------ */
    }
}

Pasted image 20240217021041.png
Pasted image 20240217021032.png

package tempPackage;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8};
        twoSUm(arr, 10);
    }

    public static void twoSUm(int[] arr, int x)
    {
        Map<Integer, Integer> h = new HashMap<>();
        for(int i=0; i< arr.length; i++)
        {
            int complement = x-arr[i];
            if(h.containsKey(complement))
            {
                System.out.println(arr[i] + " + " + complement + " = " + x);
                System.out.println("Indexes = " + i + " & " + h.get(complement));
            }
            h.put(arr[i], i);
        }
    }
}

Sorting :

Insertion Sort : https://www.geeksforgeeks.org/insertion-sort/


  • Study : Jagged stair/diagonal array
package collegeWDA;

// jagged diagonal array take row length from user
public class Array2 {
    public static void main(String[] args) {

        java.util.Scanner sc = new java.util.Scanner(System.in);
        int row = sc.nextInt();

        int[][] arr = new int[row][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[i + 1];
        }

        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = count++;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Binary Searching :

  • recursive bhi padh lena BS ko
  • Merge, Quick, Heap

OBS Studio Video for JAVA Collections and spring rest API (starts)

Java Concepts :

Pasted image 20240216232825.png

Inheritance :

  • Basically classes ko extend karna

Polymorphism :

https://www.geeksforgeeks.org/difference-between-compile-time-and-run-time-polymorphism-in-java/
Function having same name, but it performs different operations.
For example : If we use print operation then, method for printing an image and document will be different.

  • It is of two types : Compile Time Polymorphism and Runtime Polymorphism :
    • Compile Time : Method Overloading
    • Runtime : Method Overriding (Class extend karke parent class ke method ko @Override use karke uska method ko override karna (@Override use karna is not necessary))

Encapsulation :

It refers to the bundling of data (attributes or variables) and methods (functions or procedures) that operate on the data into a single unit known as a class. Encapsulation helps in hiding the internal implementation details of an object and protecting its state from external interference.

In Java, encapsulation is achieved by declaring the fields of a class as private and providing public getter and setter methods to access and modify the values of these fields.

Abstraction :

In this lecture we will learn:
- What is Abstraction?
- Abstract method in Java
- Abstract class in Java
- Abstract vs Concrete classes

#1
Abstraction is a process of hiding the implementation details and showing only functionality to the user.

#2
Abstract method:-
- Instead of defining the method, we can declare the method.
- If we put a semicolon at the end of a method, it means that you only declare the method like:
 public void drive();
- This method does not contain any features and you will not be able to create an object of it.
- You need to add an abstract keyword to only declare a method.

#3
Abstract class:-
- Abstract methods can only be defined in an abstract class.
- We need to add an abstract keyword before a class to make it an abstract class.
- Objects of an abstract class can not be created.
- If you are extending an abstract class, then it is compulsory to define all abstract methods.
- It is not necessary that an abstract class should have an abstract method.
- Abstract class can have an abstract or a normal method or both.
- An abstract class can have more than one abstract method.

#4
Concrete class: A class other than an abstract class is known as a concrete class.
- An object of a concrete class can be created.

  • Interface can also be used for defining abstract methods.

Spring Boot


Architecture : Microservices and Monolithic.
Monolithic : Client will hit a single server.

  • Vectors
package com.hitarth.IIITL2024;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

// selection sort program

public class temp {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        Vector<Integer> v = new Vector<>(3, 2);
        System.out.println("Capacity: " + v.capacity()); // → 3 // initial capacity // means it can accommodate 3 elements
        System.out.println("Size: " + v.size()); // → 0 // as zero elements are added

        v.add(1);
        v.add(2);
        v.add(3);
        v.add(4);

        System.out.println(Arrays.toString(v.toArray())); // → [1, 2, 3]
        System.out.println("Capacity: " + v.capacity()); // → 5 // size has been increased by 2. // 3+2 = 5
        System.out.println("Size: " + v.size()); // → 4

        Iterator<Integer> it = v.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " "); // → 1 2 3 4
        }
    }
}

Pasted image 20240216085124.png

package org.example.rest.webservices.userapi.user;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.util.Date;

@Entity
@Table(name = "Users")
public class UserModel {

    @Id // Primary Key
//    @GeneratedValue(strategy = GenerationType.UUID) // UUID is a 128-bit number used to identify information in computer systems
    @GeneratedValue(strategy = GenerationType.SEQUENCE) // SEQUENCE is a database object that generates numbers // One Drawback is that a sequence can be guessed by an attacker
    private long userId;

    @NotBlank(message = "first name can't be null") // Validation for not null and not empty
    @Column(unique = true, nullable = false, updatable = false) // Unique constraint; it can't be null; it is not updatable
    private String userName;

    private String firstName;

    private String middleName;

    private String lastName;

    @NotBlank(message = "password can't be null")
    @Size(min = 8, max = 12,message = "password should have atleast 8 characters")
    private String password;

    private String email;

    private String phoneNo;

    @CreationTimestamp // Automatically sets the value of the field to the current timestamp when the entity is persisted
    @Column(nullable = false, updatable = false)
    private Date createdDate;

    @UpdateTimestamp // Automatically updates the value of the field to the current timestamp every time the entity is updated
    @Column(nullable = false, updatable = true)
    @Temporal(TemporalType.DATE) // To store only date / precision of the date
    private Date modifiedDate;


    private long createdBy; // To store the user id of the user who created the record

    private long modifiedBy; // To store the user id of the user who modified the record


//    public UserModel() {
//        super();
//        // TODO Auto-generated constructor stub
//    }


    public UserModel(long userId, String userName, String firstName, String middleName, String lastName, String password, String email, String phoneNo, Date createdDate, Date modifiedDate, long createdBy, long modifiedBy) {
        this.userId = userId;
        this.userName = userName;
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.password = password;
        this.email = email;
        this.phoneNo = phoneNo;
        this.createdDate = createdDate;
        this.modifiedDate = modifiedDate;
        this.createdBy = createdBy;
        this.modifiedBy = modifiedBy;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Date getModifiedDate() {
        return modifiedDate;
    }

    public void setModifiedDate(Date modifiedDate) {
        this.modifiedDate = modifiedDate;
    }

    public long getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(long createdBy) {
        this.createdBy = createdBy;
    }

    public long getModifiedBy() {
        return modifiedBy;
    }

    public void setModifiedBy(long modifiedBy) {
        this.modifiedBy = modifiedBy;
    }
}
  • CreationTimeStamp : might come in exam
  • created by, modified by, createdDate, modifiedDate, status (to maintain the status of a data, we do not want to actually delete the data but make the status false, so the places where that data is going to be accessed will throw a not found error)

MidSem : JAVA + Get API, constraints, ARC / Postman

PAGING padh lena