Lecture 1
hitarth's Vault // Exported at - 08:45 PM
Mid sem tak ka to hai us PDF me, uske baad ye karlo :
UserModel.java
wagera meSecurityFilterChain
Class use karna), PasswordEncoder
(Bcrypt wagera), Basics JWT Token Helper class Methods like generateToken
, isTokenExpired
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());
}
}
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.
@Override
is used to override the method defined in an interface through a method defined in a class implementing the interface.Example of tight coupling :
this
keywordabstract
method : https://docs.oracle.com/javase/tutorial/java/IandI/abstract.htmlpackage 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);
}
}
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:
List
interface.List
interface.Set
interface that uses a hash table for storage.SortedSet
interface that uses a self-balancing binary search tree (Red-Black Tree) for storage.Map
interface that stores key-value pairs.Collections.synchronizedMap()
to create a synchronized map.SortedMap
interface that uses a self-balancing binary search tree (Red-Black Tree) for storage.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
/* ------------------------------------------------------ */
}
}
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);
}
}
}
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();
}
}
}
extend
karnahttps://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.
@Override
use karke uska method ko override karna (@Override
use karna is not necessary))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.
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.
Architecture : Microservices and Monolithic.
Monolithic : Client will hit a single server.
Exception Handling : https://www.geeksforgeeks.org/spring-boot-exception-handling/
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
}
}
}
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;
}
}
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