Normal view

There are new articles available, click to refresh the page.
Yesterday — 14 April 2025IRC mates

To-Do Application on Spring boot

I am going to create To-do list.

Spring boot dependencies.

  1. spring boot web
  2. jdbc postgreSQl driver
  3. spring- JPA
  4. Thyme-leaf

Entities

I am going to create two entities. They are task and Todo. It has one to many, It means todo has many task. Create the field and getter and setter methods.

TodoList class

It has id, name and List<Task>. Create getter and setter method.

Then we create bidirectional relationship between todo have task. so we create mappedBy the todo object on task. so task can create foreign key for todo list.

@Entity
public class TodoList {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	
	@OneToMany(mappedBy = "todoList", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.EAGER)
	private List<Task> taskList= new ArrayList<>();
	
	@ManyToOne
	@JoinColumn(name = "user_idn")
	private Users users;
	// no-arg constructor and getter and setter
}

Task class

It has id and name and todo object. Then we create getter and setter method.

The foreign key create in this table, because we mapped this todo object is mapped on that class. joinColumn name is the foreign key name.

@Entity
public class Task {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	private boolean status;
//	private Locale locale; // date and time

	@ManyToOne
	@JoinColumn(name = "todo_list_id")
	private TodoList todoList;
}

Repository Interface

Simple that create two interface one for task and todo which can extend the JPARepository.

public interface TaskRepository extends JpaRepository<Task, Long> {
     }

     public interface TaskRepository extends JpaRepository<Task, Long> {
     }

DB and JPA configuations

 spring.datasource.url=jdbc:postgresql://localhost:5432/login
spring.datasource.username=progres
spring.datasource.password=1234
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Controller class with html

We are going to create 7 task with frontend html with thyme leaf. Map the class with “/todos” using @RequestMapping.

Click the arrow or triange (|>) to see full details.

1. show all todo list

It method is used to default page of /todos page. It have List of Todo and newlist which can return to html page.

@GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }
2. create the todo list

Then we press create list button on html. we got newlist from getMapping that List pass through @modelAttribute. That list can save in repository.

  @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }
3. show tasks from todo list

Then we enter into the a list, it have many task. That can be shown by this method. we get the list by id and we pass that list of task and new task to html.

     @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }
4. create the task from todo list

Then we press create task button on html. we got new task from getMapping that task pass through @modelAttribute. That list can save in repository.

  // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
5. Toggle the task or not

Then we press todo checkbox it can be tick. Same find the task by taskId. That task setCompleted and save it again in task. Return redirect://todos/+listId, it redirect to getMapping or this Todo List.

     // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }
6. delete the todo list

Then we press delete button from list on html. we remove from repository. Return the getMapping of current list.

     @PostMapping("/{listId}/delete")
    public String deleteTask(@PathVariable Long listId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }
7. delete the task from task list

Then we press delete button on html. We delete task from task repository. We return and redirect to getmapping of current task list.

  @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }

Controller full code

  @Controller
@RequestMapping("/todos")
public class TodoController {

    @Autowired
    private TodoListRepository todoListRepository;
    
    @Autowired
    private TaskRepository taskRepository;

    // Show all todo lists
    @GetMapping
    public String listTodoLists(Model model) {
        model.addAttribute("todoLists", todoListRepository.findAll());
        model.addAttribute("newTodoList", new TodoList());
        return "todo-lists";
    }

    // Create new todo list
    @PostMapping
    public String createTodoList(@ModelAttribute TodoList todoList) {
        todoListRepository.save(todoList);
        return "redirect:/todos";
    }

    // Show tasks from todo list
    @GetMapping("/{listId}")
    public String viewTodoList(@PathVariable Long listId, Model model) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        model.addAttribute("todoList", todoList);
        model.addAttribute("newTask", new Task());
        return "tasks";
    }

    // Add task to a todo list
    @PostMapping("/{listId}/tasks")
    public String addTask(@PathVariable Long listId, @ModelAttribute Task task) {
        TodoList todoList = todoListRepository.findById(listId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid list id"));
        
        task.setTodoList(todoList);
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Toggle task completion status
    @PostMapping("/{listId}/tasks/{taskId}/toggle")
    public String toggleTask(@PathVariable Long listId, @PathVariable Long taskId) {
        Task task = taskRepository.findById(taskId)
            .orElseThrow(() -> new IllegalArgumentException("Invalid task id"));
        
        task.setCompleted(!task.isCompleted());
        taskRepository.save(task);
        return "redirect:/todos/" + listId;
    }

    // Delete a task
    @PostMapping("/{listId}/tasks/{taskId}/delete")
    public String deleteTask(@PathVariable Long listId, @PathVariable Long taskId) {
        taskRepository.deleteById(taskId);
        return "redirect:/todos/" + listId;
    }

    // Delete a todo list
    @PostMapping("/{listId}/delete")
    public String deleteTodoList(@PathVariable Long listId) {
        todoListRepository.deleteById(listId);
        return "redirect:/todos";
    }
}

Html code

Html has two page one for todo list and another for task list.

Todo list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Todo Lists</title>
	<link rel="icon" type="image/x-icon" href="/aaeranLogo.ico" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>My Todo Lists</h1>
	    <!-- Form to create new todo list -->
    <form th:action="@{/todos}" th:object="${newTodoList}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New list name" required>
            <button type="submit" class="btn btn-primary">Create List</button>
        </div>
    </form>

	<!-- display the todo list -->
    <div th:each="todoList : ${todoLists}" class="card mb-3">
        <div class="card-body">
			
		   <h2 class="card-title">
                <a th:href="@{/todos/{id}(id=${todoList.id})}" th:text="${todoList.name}">List Name</a>
                <span class="badge bg-secondary" th:text="${todoList.taskList.size()}">0</span>
            </h2>
            
            <form th:action="@{/todos/{id}/delete(id=${todoList.id})}" method="post" class="d-inline">
                <button type="submit" class="btn btn-sm btn-danger">Delete List</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Task.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Tasks</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <h1>Tasks for <span th:text="${todoList.name}">List Name</span></h1>
    <a href="/todos" class="btn btn-secondary mb-3">Back to Lists</a>
    
    <!-- Form to add new task -->
    <form th:action="@{/todos/{id}/tasks(id=${todoList.id})}" th:object="${newTask}" method="post" class="mb-4">
        <div class="input-group">
            <input type="text" th:field="*{name}" class="form-control" placeholder="New task description" required>
            <button type="submit" class="btn btn-primary">Add Task</button>
        </div>
    </form>
    
    <div th:each="task : ${todoList.taskList}" class="card mb-2">
        <div class="card-body d-flex align-items-center">
            <form th:action="@{/todos/{listId}/tasks/{taskId}/toggle(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="me-3">
                <input type="checkbox" 
                       th:checked="${task.status}" 
                       onChange="this.form.submit()"
                       class="form-check-input" 
                       style="transform: scale(1.5);">
            </form>
            
            <span th:class="${task.status} ? 'text-decoration-line-through text-muted' : ''" 
                  th:text="${task.name}" 
                  class="flex-grow-1">Task description</span>
            
            <form th:action="@{/todos/{listId}/tasks/{taskId}/delete(listId=${todoList.id}, taskId=${task.id})}" 
                  method="post" class="ms-2">
                <button type="submit" class="btn btn-sm btn-danger">Delete</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Reference :

Deploy our Spring boot application for free.

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

Place button on wiki Page.

I got a task, that to add a cody in wiktionary side. For do this we have knowledge of Wiki Gadget.

Create an Account on wiki page:

  • If we want to change in wiki page. First we want to create account in wiki.
  • Then we create a own javascript page for make change.
  • The changes can be seen in our page only.
  • If we want to change globally, i have a knowledge of Gadget_kitchen in wiki.

Find the place that have to change

  • Go to wiktionary site and seach any word it.
  • open F12 to view inspect and find the place heading usi.
  • I found in
    • body -> div(mw-page-container) -> div(mw-page-container-inner) -> div(mw-content-container) ->main -> header.
    • header contains nav, h1, div(title-shortlink-container), div(vector-dropdown.
    • h1 must be copy and button place near to h1 or div(title-shortlink-container).

Create common.js page and paste the code

Code:
const observer = new MutationObserver(() => {
    const heading = document.querySelector(".title-shortlink-container");
    if (heading) {
        // Create the button element
        const button = document.createElement("button");
        button.textContent = "Copy Text";
        button.style.marginLeft = "10px"; // Add some spacing from the container

        // Insert the button next to the .title-shortlink-container
        heading.insertAdjacentElement("afterend", button);

        // Add an event listener to copy the text
        button.addEventListener("click", () => {
            const textToCopy = heading.textContent.trim(); // Get only the container's text
            navigator.clipboard.writeText(textToCopy).then(() => {
                alert("Text copied: " + textToCopy);
            }).catch(err => {
                console.error("Failed to copy text: ", err);
            });
        });

        observer.disconnect(); // Stop observing once the element is found
    }
});

// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });

Code Explanation :

  1. Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
  2. If the Heading is not null. Then we create the button and styles.
  3. The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
  4. Button action create a function in addEventListener.
  5. Get the link by heading.textContent and store in textToCopy
  6. For copy the text use navigator.clipboard.writeText(textToCopy)
  7. Then pop alert for the event.
  8. if error catch throw error message.
Problem faced (dynamically loaded content)
  1. First i use DOMContentLoaded. It cannot work in wiki.
  2. Then i use Polling (Setintervel for a Certain time). It works partcially.
  3. Then i use MutationObserver. I works perfectly to all pages.

Reference:

https://ta.wikipedia.org/wiki/Special:MyPage/common.js

https://stackoverflow.com/questions/24344022/how-to-use-mutationobserver

https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript

136. Single Number

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.
package ArrayExecise;
/* 
 * 	result=1            => 0001
 *  result=2			=> 0010 ^ 0001 = 0011
 *  result=2            => 0011 ^ 0010 = 0001
 *  result=3            => 0001 ^
 * */

public class SingleElement {

	public static void main(String[] args) {
		int nums[]= {1,2,2,3,3,4,4,5,5};
		int result=0;
	    for(int i=0; i<nums.length; i++) {
	         result = result^nums[i];
	    }
	  System.out.println(result);
	}

}

Table and List

HTML table tag is used to display data in tabular form (row * column). There can be many columns in a row.

We can create a table to display data in tabular form, using <table> element, with the help of <tr> , <td>, and <th> elements.

In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table data is defined by <td> tags.

TagDescription
<table>It defines a table.
<tr>It defines a row in a table.
<th>It defines a header cell in a table.
<td>It defines a cell in a table.
<caption>It defines the table caption.
<colgroup>It specifies a group of one or more columns in a table for formatting.
<col>It is used with <colgroup> element to specify column properties for each column.
<tbody>It is used to group the body content in a table.
<thead>It is used to group the header content in a table.
<tfooter>It is used to group the footer content in a table.
Table tags

Update data on table

UPDATE statement allows you to update data in one or more columns of one or more rows in a table.

UPDATE table_name
SET column1 = value1,
    column2 = value2,
    ...
WHERE condition;

In this syntax:

  • First, specify the name of the table that you want to update data after the UPDATE keyword.
  • Second, specify columns and their new values after SET keyword. The columns that do not appear in the SET clause retain their original values.
  • Third, determine which rows to update in the condition of the WHERE clause
Code:
UPDATE company SET salary = salary * 2
WHERE salary = 150000;

The WHERE clause is optional. If you omit the WHERE clause, the UPDATE statement will update all the column values in the table.

Code:
UPDATE company SET salary = salary * 2

Summary :
  • Use the UPDATE statement to update data in one or more columns of a table.
  • Specify a condition in a WHERE clause to determine which rows to update data.
  • Use the RETURNING clause to return the updated rows from the UPDATE statement

Reference :

Insert data on table

INSERT statement to insert a new row into a table.

INSERT INTO table1(column1, column2, …)
           VALUES (value1, value2, …);

In this syntax:

  • First, specify the name of the table (table1) that you want to insert data after the INSERT INTO keywords and a list of comma-separated columns (colum1, column2, ....).
  • Second, supply a list of comma-separated values in parentheses (value1, value2, ...) after the VALUES keyword. The column and value lists must be in the same order.

RETURNING clause

  • The INSERT statement has an optional RETURNING clause
  • returns the information of the inserted row.
INSERT INTO table1(column1, column2, …)
VALUES (value1, value2, …)
RETURNING *;

It return the inside table

We can return by any parameters.

Summary

  • Use PostgreSQL INSERT statement to insert a new row into a table.
  • Use the RETURNING clause to get the inserted rows.

Reference:

how to install PGAdmin in Linux-mint

Use jammy ubuntu version, for install the PGAdmin on linux-mint.

1) Install the public key for the repository (if not done previously):

sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add

2) Create the repository configuration file: (jammy is important)

sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/jammy pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update

3) Install pgAdmin

sudo apt install pgadmin4

4) Install for desktop mode only

sudo apt install pgadmin4-desktop

5) If you need, also install for web mode only:

sudo apt install pgadmin4-web 

6) After install pgadmin4. Configure the webserver, (if you installed pgadmin4-web)

sudo /usr/pgadmin4/bin/setup-web.sh

Reference :

67. Add Binary

This problem is like add String number in String.

Description :

Given two binary strings a and b, return their sum as a binary string.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Algorithm:

  1. Add numbers from end to start so, initials i =a.length() -1 and j=a.length()-1.
  2. Intialize the carry =0 as the remaining number.
  3. use Stringbuffer for the mutable property in string.
  4. Now Add the continuously,
    • carry += num1.charAt(i) and i– upto i>=0.
    • carry += num2.charAt(j) and j– upto j>=0.
    • stringBuffer. append(carry%10).
    • carry /= 10.
  5. then reverse the stringBuffer by st.reverse().

Code :

int carry =0,i=a.length()-1,j=b.length()-1;
        StringBuffer sb =new StringBuffer();
        while(i>=0 || j>=0 || carry > 0)
        {
        	if(i>=0)
        		carry += a.charAt(i--)-'0';
        	if(j>=0)
        		carry += b.charAt(j--)-'0';
        	
        	sb.append(carry%2);
        	carry /=2;
        	
        }
        return sb.reverse().toString();

Reference :

  1. https://leetcode.com/problems/add-binary/description/

415. Add Strings

LeetCode number 415, String.

This problem is like add binary number in String.

Description:

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Input / Ouput :

Example 1:

Input: num1 = "11", num2 = "123"
Output: "134"

Example 2:

Input: num1 = "456", num2 = "77"
Output: "533"

Example 3:

Input: num1 = "0", num2 = "0"
Output: "0"

Algorithm:

  1. Add numbers from end to start so, initials i =num1.length() -1 and j=num2.length()-1.
  2. Intialize the carry =0 as the remaining number.
  3. use Stringbuffer for the mutable property in string.
  4. Now Add the continuously,
    • carry += num1.charAt(i) and i– upto i>=0.
    • carry += num2.charAt(j) and j– upto j>=0.
    • stringBuffer. append(carry%10).
    • carry /= 10.
  5. then reverse the stringBuffer by st.reverse().

code :

  int i=num1.length()-1, j=num2.length()-1, carry=0;
        StringBuffer sb = new StringBuffer();
        while(i>=0 || j>=0 || carry > 0)
        {
        	// condtion for string out of boundary i.e means i should less then 0
        	if(i>=0)
        		carry += num1.charAt(i--) - '0';
        	
        	if(j>=0)
        		carry += num2.charAt(j--) - '0';
        	sb.append(carry%10);
        	carry /= 10;
        }
        
		return sb.reverse().toString();

Reference :

https://leetcode.com/problems/add-strings

Before yesterdayIRC mates
❌
❌