Wednesday, December 10, 2025

Profit & Loss Calculator Android Studio Project

 


🚀 1. ANDROID APP VERSION (JAVA)

📱 Profit & Loss Calculator — Android Studio Project

Step 1: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://
schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    android:gravity="center"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etCP"
        android:hint="Enter Cost Price"
        android:inputType="numberDecimal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etSP"
        android:hint="Enter Selling Price"
        android:inputType="numberDecimal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>

    <Button
        android:id="@+id/btnCalc"
        android:text="Calculate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"/>

    <TextView
        android:id="@+id/tvResult"
        android:text=""
        android:textSize="18sp"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Step 2: MainActivity.java

package com.example.profitloss;

import androidx.appcompat.
app.AppCompatActivity;
import android.os.Bundle;
import android.widget.*;

public class MainActivity
 extends AppCompatActivity {

    EditText etCP, etSP;
    Button btnCalc;
    TextView tvResult;

    @Override
    protected void onCreate
(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etCP = findViewById(R.id.etCP);
        etSP = findViewById(R.id.etSP);
        btnCalc = findViewById(R.id.btnCalc);
        tvResult = findViewById(R.id.tvResult);

        btnCalc.setOnClickListener(v -> {
            double cp = Double.
parseDouble(etCP.getText().toString());
            double sp = Double.
parseDouble(etSP.getText().toString());

            if (sp > cp) {
                double profit = sp - cp;
                double pp = profit / cp * 100;
                tvResult.setText("Profit:
 " + profit + "\nProfit %: " + pp);
            } else if (cp > sp) {
                double loss = cp - sp;
                double lp = loss / cp * 100;
                tvResult.setText("Loss: 
" + loss + "\nLoss %: " + lp);
            } else {
                tvResult.setText(
"No Profit No Loss");
            }
        });
    }
}

🎨 2. JavaFX GUI VERSION

Step 1: Main Application (Main.java)

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {
        TextField cpField = new TextField();
        cpField.setPromptText(
"Enter Cost Price");

        TextField spField = new TextField();
        spField.setPromptText(
"Enter Selling Price");

        Button calcBtn = new Button(
"Calculate");
        Label result = new Label();

        calcBtn.setOnAction(e -> {
            double cp = Double.
parseDouble(cpField.getText());
            double sp = Double.
parseDouble(spField.getText());

            if (sp > cp) {
                double profit = sp - cp;
                double percent =
 (profit / cp) * 100;
                result.setText(
"Profit: " + profit + " | " + percent + "%");
            } else if (cp > sp) {
                double loss = cp - sp;
                double percent = (
loss / cp) * 100;
                result.setText(
"Loss: " + loss + " | " + percent + "%");
            } else {
                result.setText(
"No Profit, No Loss");
            }
        });

        VBox root = new VBox(
10, cpField, spField, calcBtn, result);
        root.setPadding(new Insets(20));

        stage.setScene(new Scene(
root, 300, 250));
        stage.setTitle(
"Profit & Loss Calculator");
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

🌐 3. WEB VERSION (JSP + SERVLET)

Structure:

WebApp/
 ├── index.jsp
 ├── result.jsp
 └── ProfitLossServlet.java

Step 1: index.jsp

<!DOCTYPE html>
<html>
<body>
<h2>Profit & Loss Calculator</h2>

<form action="ProfitLossServlet" 
method="post">
    Cost Price: <input type="text"
 name="cp"><br><br>
    Selling Price: <input type="text" 
name="sp"><br><br>
    <input type="submit" value="Calculate">
</form>

</body>
</html>

Step 2: ProfitLossServlet.java

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;

public class ProfitLossServlet 
extends HttpServlet {

    protected void doPost
(HttpServletRequest request,
 HttpServletResponse response)
            throws ServletException, 
IOException {

        double cp = 
Double.parseDouble(request.getParameter("cp"));
        double sp = 
Double.parseDouble(request.getParameter("sp"));

        String result;

        if (sp > cp) {
            double profit = sp - cp;
            double pp = profit / cp * 100;
            result = "Profit:
 " + profit + " ( " + pp + "% )";
        } else if (cp > sp) {
            double loss = cp - sp;
            double lp = loss / cp * 100;
            result = "Loss: " + loss 
+ " ( " + lp + "% )";
        } else {
            result = "No Profit No Loss";
        }

        request.setAttribute("result", 
result);
        RequestDispatcher rd = 
request.getRequestDispatcher("result.jsp");
        rd.forward(request, response);
    }
}

Step 3: result.jsp

<!DOCTYPE html>
<html>
<body>

<h2>Result</h2>
<p><b>${result}</b></p>

<a href="index.jsp">Go Back</a>

</body>
</html>

Spring Boot web app with MYSQL integration

 

1) Spring Boot (with REST & MySQL JPA)

Project type: Spring Boot (Maven).
Java version: 11+ recommended.

pom.xml (essential deps)

<project ...>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>profitloss-service</artifactId>
  <version>1.0.0</version>

  <properties>
    <java.version>11</java.version>
    <spring.boot.version>3.1.0
</spring.boot.version>
  </properties>

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

    <dependency>
      <groupId>org.springframework.boot
</groupId>
      <artifactId>spring-boot-
starter-data-jpa</artifactId>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-
java</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.
boot</groupId>
      <artifactId>spring-boot-
starter-validation</artifactId>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.
jackson.core</groupId>
      <artifactId>jackson-
databind</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.
boot</groupId>
        <artifactId>spring-boot-
maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

src/main/resources/application.properties

Replace username/password/dbname with your MySQL values.

spring.datasource.url=jdbc:mysql:
//localhost:3306/profitlossdb?useSSL=
false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.
format_sql=true

server.port=8080

Domain: com.example.profitloss.model.Calculation.java

package com.example.profitloss.model;

import jakarta.persistence.*;
import java.time.Instant;

@Entity
public class Calculation {

    @Id
    @GeneratedValue(strategy =
 GenerationType.IDENTITY)
    private Long id;

    private double cp;
    private double sp;
    private double amount; // 
profit or loss magnitude
    private double percent;
    private boolean isProfit;
 // true -> profit, false -> 
loss (if equal, treat as neither)
    private Instant createdAt =
 Instant.now();

    // Constructors, getters, setters
    public Calculation() {}
    public Calculation(double cp,
 double sp, double amount, 
double percent, boolean isProfit) {
        this.cp = cp; this.sp = 
sp; this.amount = amount;
 this.percent = percent; this.isProfit = isProfit;
    }
    // getters and setters
 omitted for brevity (generate in IDE)
    // ...
    public Long getId(){return id;}
    public double getCp(){return cp;}
    public void setCp(double cp){this.cp=cp;}
    public double getSp(){return sp;}
    public void setSp(double sp){this.sp=sp;}
    public double getAmount(){return amount;}
    public void setAmount(double amt)
{this.amount=amt;}
    public double getPercent()
{return percent;}
    public void setPercent(double p)
{this.percent=p;}
    public boolean isProfit()
{return isProfit;}
    public void setProfit
(boolean profit){this.isProfit=profit;}
    public Instant getCreatedAt()
{return createdAt;}
    public void setCreatedAt
(Instant t){this.createdAt=t;}
}

Repository: CalculationRepository.java

package com.example.profitloss.repo;

import com.example.profitloss.
model.Calculation;
import org.springframework.data.
jpa.repository.JpaRepository;

public interface CalculationRepository 
extends JpaRepository<Calculation, Long> {}

DTO: CalculateRequest.java

package com.example.profitloss.dto;

import jakarta.validation.constraints.Min;

public class CalculateRequest {
    @Min(value = 0, message = 
"Cost price must be >= 0")
    private double cp;

    @Min(value = 0, message =
 "Selling price must be >= 0")
    private double sp;

    public double getCp(){return cp;}
    public void setCp(double cp){this.cp=cp;}
    public double getSp(){return sp;}
    public void setSp(double sp){this.sp=sp;}
}

Response DTO: CalculateResponse.java

package com.example.profitloss.dto;

public class CalculateResponse {
    private String type; // "profit",
"loss","no-profit-no-loss"
    private double amount;
    private double percent;
    private long id; // persisted 
record id (if saved)

    public CalculateResponse
(String type, double amount, 
double percent, long id){
        this.type = type; 
this.amount = amount; this.percent = 
percent; this.id = id;
    }
    // getters
    public String getType(){return type;}
    public double getAmount(){return amount;}
    public double getPercent(){return percent;}
    public long getId(){return id;}
}

Service: CalculationService.java

package com.example.profitloss.service;

import com.example.profitloss.
dto.CalculateRequest;
import com.example.profitloss.
model.Calculation;
import com.example.profitloss.
repo.CalculationRepository;
import org.springframework.
stereotype.Service;

@Service
public class CalculationService {

    private final CalculationRepository repo;

    public CalculationService
(CalculationRepository repo){
        this.repo = repo;
    }

    public Calculation calculateAndSave
(double cp, double sp){
        if (cp == sp) {
            Calculation calc = new 
Calculation(cp, sp, 0.0, 0.0, false);
            return repo.save(calc);
        }
        boolean isProfit = sp > cp;
        double amount = Math.abs(sp - cp);
        double percent = (amount / cp) * 100;
        Calculation calc = new 
Calculation(cp, sp, amount, percent, isProfit);
        return repo.save(calc);
    }
}

Controller (REST): CalculationController.java

package com.example.profitloss.controller;

import com.example.profitloss.
dto.CalculateRequest;
import com.example.profitloss.
dto.CalculateResponse;
import com.example.profitloss.
model.Calculation;
import com.example.profitloss.
service.CalculationService;
import jakarta.validation.Valid;
import org.springframework.http.
ResponseEntity;
import org.springframework.web.
bind.annotation.*;

@RestController
@RequestMapping("/api")
public class CalculationController {

    private final CalculationService service;

    public CalculationController
(CalculationService service){
        this.service = service;
    }

    // POST /api/calculate -> saves 
to DB and returns result
    @PostMapping("/calculate")
    public ResponseEntity<CalculateResponse>
 calculateAndSave(@Valid @RequestBody
 CalculateRequest req) {
        Calculation saved = service.
calculateAndSave(req.getCp(), req.getSp());
        String type;
        if (saved.getAmount() == 0.0) 
type = "no-profit-no-loss";
        else type = saved.isProfit() ?
 "profit" : "loss";
        CalculateResponse resp = new
 CalculateResponse(type, saved.getAmount(), 
saved.getPercent(), saved.getId());
        return ResponseEntity.ok(resp);
    }

    // GET /api/calculation/{id} -> 
fetch saved calculation
    @GetMapping("/calculation/{id}")
    public ResponseEntity<Calculation>
 getById(@PathVariable Long id) {
        return service.repo.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.
notFound().build());
    }
}

Note: For brevity service.repo was used in controller GET. In production extract via service method.

Application main

package com.example.profitloss;

import org.springframework.boot.
SpringApplication;
import org.springframework.boot.
autoconfigure.SpringBootApplication;

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

How to run

  1. Start MySQL and create DB profitlossdb (or let JPA create; ensure user has privileges).
    Example:
    CREATE DATABASE profitlossdb;
    
  2. Update application.properties credentials.
  3. mvn spring-boot:run or build jar.

Example REST call (curl)

curl -X POST http://localhost:
8080/api/calculate \
 -H "Content-Type: application/json" \
 -d '{"cp":500,"sp":650}'

Response:

{"type":"profit","amount":
150.0,"percent":30.0,"id":1}

2) MySQL Integration (already included above)

  • JPA entity Calculation persists each calculation.
  • spring.jpa.hibernate.ddl-auto=update will create the table automatically.
  • You can query results via JPA repository or exposed REST endpoint.

If you want explicit SQL schema:

CREATE TABLE calculation (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  cp DOUBLE,
  sp DOUBLE,
  amount DOUBLE,
  percent DOUBLE,
  is_profit BOOLEAN,
  created_at TIMESTAMP DEFAULT
 CURRENT_TIMESTAMP
);

3) REST API (standalone description)

The Spring Boot app provides:

  • POST /api/calculate — accepts JSON { "cp": <number>, "sp": <number> } and returns { type, amount, percent, id }. Saves to DB.
  • GET /api/calculation/{id} — fetch saved record.

Validation: @Min(0) on input; add more error handling as needed.

4) Kotlin Android App (Android Studio)

Minimum: Android Gradle Plugin + Kotlin. Create new project (Empty Activity) and replace files.

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="24dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etCP"
        android:hint="Cost Price (CP)"
        android:inputType="numberDecimal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/etSP"
        android:hint="Selling Price (SP)"
        android:inputType="numberDecimal"
        android:layout_marginTop="12dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnCalculate"
        android:text="Calculate"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tvResult"
        android:textSize="18sp"
        android:layout_marginTop="18dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.kt

package com.example.profitlossapp

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var etCP: EditText
    private lateinit var etSP: EditText
    private lateinit var btnCalculate: Button
    private lateinit var tvResult: TextView

    override fun onCreate(savedInstanceState:
 Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        etCP = findViewById(R.id.etCP)
        etSP = findViewById(R.id.etSP)
        btnCalculate = findViewById
(R.id.btnCalculate)
        tvResult = findViewById(R.id.tvResult)

        btnCalculate.setOnClickListener {
            val cpText = etCP.text.
toString().trim()
            val spText = etSP.text.
toString().trim()
            if (cpText.isEmpty() || 
spText.isEmpty()) {
                tvResult.text = 
"Please enter both CP and SP."
                return@setOnClickListener
            }

            val cp = cpText.toDoubleOrNull()
            val sp = spText.toDoubleOrNull()
            if (cp == null || sp == null) {
                tvResult.text = 
"Invalid numbers."
                return@setOnClickListener
            }
            if (cp == 0.0) {
                tvResult.text = 
"CP cannot be zero for percentage calculation."
                return@setOnClickListener
            }

            when {
                sp > cp -> {
                    val profit = sp - cp
                    val percent = 
profit / cp * 100
                    tvResult.text =
 "Profit: %.2f\nProfit %%: %.2f".
format(profit, percent)
                }
                cp > sp -> {
                    val loss = cp - sp
                    val percent = 
loss / cp * 100
                    tvResult.text = 
"Loss: %.2f\nLoss %%: %.2f".format
(loss, percent)
                }
                else -> {
                    tvResult.text = 
"No Profit, No Loss."
                }
            }
        }
    }
}

Optional: Call Spring Boot REST from Android

  • Add Retrofit or OkHttp to build.gradle and POST to /api/calculate to persist results remotely.

Final notes & next steps

  • The Spring Boot project already includes REST endpoints and MySQL JPA integration — that covers items (1)-(3).
  • The Kotlin Android project is a simple UI app; it can be extended to call the REST API to persist calculations remotely.

Docker plus Docker Compose for Spring Boot app

 


Docker + Docker Compose for Spring Boot app

Kubernetes manifests (Deployment, Service, HorizontalPodAutoscaler, ConfigMap, Secret)

GitHub Actions CI/CD workflow (build, test, build Docker image, push to registry)

Android app updated to MVVM (Kotlin) with Retrofit integration and simple persistence

placeholders is the place where you must insert credentials (Docker registry, secrets). Copy/paste into your projects and adjust names/credentials.

Docker (Spring Boot)

Dockerfile

# Use a multi-stage build for a Spring 
Boot jar
FROM eclipse-temurin:17-jdk-jammy AS build
WORKDIR /app
COPY pom.xml mvnw ./
COPY .mvn .mvn
COPY src src
RUN ./mvnw -B -DskipTests package

FROM eclipse-temurin:17-jre-jammy
ARG JAR_FILE=target/*.jar
COPY --from=build /app/${JAR_FILE} 
/app/app.jar
EXPOSE 8080
ENTRYPOINT ["java","-Xms256m","
-Xmx512m","-jar","/app/app.jar"]

.dockerignore

target/
.vscode/
.idea/
*.iml
.mvn/wrapper/maven-wrapper.jar

docker-compose.yml (app + mysql)

version: "3.8"
services:
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: examplepassword
      MYSQL_DATABASE: profitlossdb
    ports:
      - "3306:3306"
    volumes:
      - mysql-data:/var/lib/mysql

  profitloss-app:
    build: .
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql
://mysql:3306/profitlossdb?useSSL=
false&serverTimezone=UTC
      SPRING_DATASOURCE_USERNAME: root
      SPRING_DATASOURCE_PASSWORD: 
examplepassword
    depends_on:
      - mysql
    ports:
      - "8080:8080"

volumes:
  mysql-data:

Kubernetes manifests

Assume namespace profitloss. Secrets contain DB password and Docker registry creds — replace placeholders.

k8s/namespace.yaml

apiVersion: v1
kind: Namespace
metadata:
  name: profitloss

k8s/secret.yaml (DB password & optional registry)

apiVersion: v1
kind: Secret
metadata:
  name: profitloss-secret
  namespace: profitloss
type: Opaque
stringData:
  DB_PASSWORD: "examplepassword"        
   # replace
  REGISTRY_USERNAME: "your-registry-user" 
# replace if pushing private image
  REGISTRY_PASSWORD: "registry-pass"      
# replace

k8s/configmap.yaml (app config)

apiVersion: v1
kind: ConfigMap
metadata:
  name: profitloss-config
  namespace: profitloss
data:
  SPRING_DATASOURCE_URL: jdbc:mysql:
//profitloss-mysql:3306/profitlossdb?
useSSL=false&serverTimezone=UTC
  SPRING_DATASOURCE_USERNAME: root
  SPRING_JPA_HIBERNATE_DDL_AUTO: update

k8s/mysql-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: profitloss-mysql
  namespace: profitloss
spec:
  replicas: 1
  selector:
    matchLabels:
      app: profitloss-mysql
  template:
    metadata:
      labels:
        app: profitloss-mysql
    spec:
      containers:
        - name: mysql
          image: mysql:8.0
          env:
            - name: MYSQL_ROOT_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: profitloss-secret
                  key: DB_PASSWORD
            - name: MYSQL_DATABASE
              value: profitlossdb
          ports:
            - containerPort: 3306
          volumeMounts:
            - name: mysql-data
              mountPath: /var/lib/mysql
      volumes:
        - name: mysql-data
          persistentVolumeClaim:
            claimName: mysql-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-pvc
  namespace: profitloss
spec:
  accessModes: ["ReadWriteOnce"]
  resources:
    requests:
      storage: 5Gi

k8s/app-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: profitloss-app
  namespace: profitloss
spec:
  replicas: 2
  selector:
    matchLabels:
      app: profitloss-app
  template:
    metadata:
      labels:
        app: profitloss-app
    spec:
      containers:
        - name: profitloss-app
          image: your-registry/profitloss
-service:latest   # replace with built image
          imagePullPolicy: IfNotPresent
          env:
            - name: SPRING_DATASOURCE_URL
              valueFrom:
                configMapKeyRef:
                  name: profitloss-config
                  key: SPRING_DATASOURCE_URL
            - name: SPRING_DATASOURCE_USERNAME
              valueFrom:
                configMapKeyRef:
                  name: profitloss-config
                  key:
 SPRING_DATASOURCE_USERNAME
            - name: SPRING_DATASOURCE_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: profitloss-secret
                  key: DB_PASSWORD
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: profitloss-service
  namespace: profitloss
spec:
  selector:
    app: profitloss-app
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  type: ClusterIP

k8s/hpa.yaml (autoscale)

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: profitloss-hpa
  namespace: profitloss
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: profitloss-app
  minReplicas: 2
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60

Optional: add Ingress manifest depending on your cluster.

GitHub Actions — CI/CD

This workflow:

  • Runs tests
  • Builds jar
  • Builds Docker image
  • Logs into Docker registry (Docker Hub/GitHub Packages)
  • Pushes image
  • Optionally applies Kubernetes manifests via kubectl (if you configure KUBE_CONFIG)

Create .github/workflows/ci-cd.yml:

name: CI/CD Pipeline

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  IMAGE_NAME: your-registry/profitloss-service

jobs:
  build-test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 17

      - name: Build and run tests
        run: ./mvnw -B clean verify

  build-and-push:
    needs: build-test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to registry
        uses: docker/login-action@v2
        with:
          registry: docker.io
          username: ${{ secrets.
DOCKERHUB_USERNAME }}   # set in repo secrets
          password: ${{ secrets.
DOCKERHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ${{ env.IMAGE_NAME }}:latest

  deploy-k8s:
    needs: build-and-push
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup kubectl
        uses: azure/setup-kubectl@v3
        with:
          version: 'latest'

      - name: Configure kubectl
        run: |
          echo "${{ secrets.KUBE_CONFIG }}" 
> kubeconfig
          export KUBECONFIG=$PWD/kubeconfig

      - name: Update image in deployment
 (kubectl set image)
        run: |
          kubectl -n profitloss set 
image deployment/profitloss-app 
profitloss-app=${{ env.IMAGE_NAME }}
:latest || true
          kubectl -n profitloss
 rollout status deployment/
profitloss-app --timeout=120s || true

Secrets to add in repo settings

  • DOCKERHUB_USERNAME, DOCKERHUB_TOKEN (or GitHub Packages token)
  • KUBE_CONFIG — base64 encoded kubeconfig or raw kubeconfig contents (use caution)

Android — MVVM architecture (Kotlin)

I’ll provide a minimal, clean MVVM structure with Retrofit + LiveData + ViewModel + Repository.

Gradle dependencies (app/build.gradle)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 34
    defaultConfig {
        applicationId "com.example.
profitlossapp"
        minSdk 21
        targetSdk 34
        versionCode 1
        versionName "1.0"
    }
}

dependencies {
    implementation "org.jetbrains.
kotlin:kotlin-stdlib:1.9.0"
    implementation 'androidx.core:
core-ktx:1.12.0'
    implementation 'androidx.
appcompat:appcompat:1.6.1'
    implementation 'com.google.
android.material:material:1.9.0'
    implementation 'androidx.
lifecycle:lifecycle-livedata-ktx:2.6.2'
    implementation 'androidx.
lifecycle:lifecycle-viewmodel-ktx:2.6.2'
    implementation 'com.
squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.
squareup.retrofit2:converter-gson:2.9.0'
    implementation 
'org.jetbrains.kotlinx:
kotlinx-coroutines-android:1.7.3'
}

Network layer (Retrofit)

network/ProfitLossApi.kt

package com.example.profitlossapp.network

import com.example.
profitlossapp.model.CalculateRequest
import com.example.
profitlossapp.model.CalculateResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST

interface ProfitLossApi {
    @POST("/api/calculate")
    suspend fun calculate
(@Body req: CalculateRequest): 
Response<CalculateResponse>
}

network/RetrofitClient.kt

package com.example.profitlossapp.network

import retrofit2.Retrofit
import retrofit2.converter.
gson.GsonConverterFactory

object RetrofitClient {
    private const val BASE_URL = 
"http://10.0.2.2:8080" // emulator -> host

    val api: ProfitLossApi by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory
(GsonConverterFactory.create())
            .build()
            .create
(ProfitLossApi::class.java)
    }
}

Models

model/CalculateRequest.kt

package com.example.profitlossapp.model
data class CalculateRequest(val cp: 
Double, val sp: Double)

model/CalculateResponse.kt

package com.example.profitlossapp.model
data class CalculateResponse(val type:
 String, val amount: Double, 
val percent: Double, val id: Long)

Repository

repository/ProfitLossRepository.kt

package com.example.profitlossapp.repository

import com.example.profitlossapp.
model.CalculateRequest
import com.example.profitlossapp.
model.CalculateResponse
import com.example.profitlossapp.
network.RetrofitClient
import retrofit2.Response

class ProfitLossRepository {
    suspend fun calculate(req: 
CalculateRequest): Response<CalculateResponse> {
        return RetrofitClient.
api.calculate(req)
    }
}

ViewModel

ui/MainViewModel.kt

package com.example.profitlossapp.ui

import androidx.lifecycle.*
import com.example.profitlossapp.
model.CalculateRequest
import com.example.profitlossapp.
model.CalculateResponse
import com.example.profitlossapp.
repository.ProfitLossRepository
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {

    private val repo = ProfitLossRepository()

    private val _result = 
MutableLiveData<CalculateResponse?>()
    val result: 
LiveData<CalculateResponse?> = _result

    private val _error = 
MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    fun calculate(cp: Double, sp: Double) {
        viewModelScope.launch {
            try {
                val response =
 repo.calculate(CalculateRequest(cp, sp))
                if (response.isSuccessful) {
                    _result.value = 
response.body()
                    _error.value = null
                } else {
                    _error.value =
 "Server error: ${response.code()}"
                }
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }
}

UI (Activity)

ui/MainActivity.kt

package com.example.profitlossapp.ui

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.
app.AppCompatActivity
import com.example.profitlossapp.R

class MainActivity : AppCompatActivity() {
    private val vm:
 MainViewModel by viewModels()

    override fun 
onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etCP =
 findViewById<EditText>(R.id.etCP)
        val etSP = 
findViewById<EditText>(R.id.etSP)
        val btn =
 findViewById<Button>(R.id.btnCalculate)
        val tv =
 findViewById<TextView>(R.id.tvResult)

        btn.setOnClickListener {
            val cp =
 etCP.text.toString().toDoubleOrNull()
            val sp =
 etSP.text.toString().toDoubleOrNull()
            if (cp == 
null || sp == null) {
                tv.text = "Enter valid numbers"
                return@setOnClickListener
            }
            vm.calculate(cp, sp)
        }

        vm.result.observe(this) { resp ->
            resp?.let {
                tv.text = 
"Type: ${it.type}\nAmount:
 ${it.amount}\nPercent:
 ${it.percent}\nID: ${it.id}"
            }
        }

        vm.error.observe(this) { err ->
            err?.let { tv.text = "Error: $it" }
        }
    }
}

Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="24dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText android:id="@+id/etCP" 
android:hint="Cost Price" 
android:inputType="numberDecimal" 
android:layout_width="match_parent" 
android:layout_height="wrap_content"/>
    <EditText android:id="@+id/etSP"
 android:hint="Selling Price" 
android:inputType="numberDecimal"
 android:layout_marginTop="12dp"
 android:layout_width="match_parent" 
android:layout_height="wrap_content"/>
    <Button android:id="@+id/btnCalculate" 
android:text="Calculate" 
android:layout_marginTop="16dp" 
android:layout_width="match_parent"
 android:layout_height="wrap_content"/>
    <TextView android:id="@+id/tvResult" 
android:textSize="16sp" 
android:layout_marginTop="18dp" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"/>
</LinearLayout>

Quick instructions & notes

  • Docker: docker build -t your-registry/profitloss-service:latest . then docker push ... (or use the GitHub Actions workflow).
  • Docker Compose: docker compose up --build
  • Kubernetes: kubectl apply -f k8s/namespace.yaml && kubectl apply -f k8s/secret.yaml && kubectl apply -f k8s/configmap.yaml && kubectl apply -f k8s/mysql-deployment.yaml && kubectl apply -f k8s/app-deployment.yaml && kubectl apply -f k8s/hpa.yaml
  • GitHub Actions: set repository secrets (DOCKERHUB_USERNAME, DOCKERHUB_TOKEN, KUBE_CONFIG).
  • Android MVVM: run emulator and ensure Spring Boot is reachable — use 10.0.2.2 for the emulator or your machine IP for a real device. Allow CORS on Spring Boot if calling from other origins (add @CrossOrigin to controller or CorsFilter).

Class-Based Java Program (Object-Oriented)

 

Class-Based Java Program (Object-Oriented)



1. Class-Based Java Program (Object-Oriented)

class ProfitLoss {

    private double cp;
    private double sp;

    public ProfitLoss(double cp, double sp) {
        this.cp = cp;
        this.sp = sp;
    }

    public void calculate() {
        if (sp > cp) {
            double profit = sp - cp;
            double profitPercent = 
(profit / cp) * 100;
            System.out.println(
"Profit: " + profit);
            System.out.println(
"Profit Percentage: " + profitPercent + "%");

        } else if (cp > sp) {
            double loss = cp - sp;
            double lossPercent = 
(loss / cp) * 100;
            System.out.println
("Loss: " + loss);
            System.out.println
("Loss Percentage: " + lossPercent + "%");

        } else {
            System.out.println
("No Profit, No Loss.");
        }
    }
}

public class ProfitLossMain {
    public static void main(String[] args) {
        ProfitLoss obj = 
new ProfitLoss(500, 650);
        obj.calculate();
    }
}

2. Menu-Driven Console Version

(Choose 1 for profit/loss, 2 to exit)

import java.util.Scanner;

public class ProfitLossMenu {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n
===== PROFIT & LOSS CALCULATOR =====");
            System.out.println("1.
 Calculate Profit / Loss");
            System.out.println("2. Exit");
            System.out.print("Enter
 your choice: ");
            choice = sc.nextInt();

            switch (choice) {

                case 1:
                    System.out.print
("Enter Cost Price (CP): ");
                    double cp = 
sc.nextDouble();

                    System.out.print
("Enter Selling Price (SP): ");
                    double sp = 
sc.nextDouble();

                    if (sp > cp) {
                        double profit = 
sp - cp;
                        double profitPercent
 = (profit / cp) * 100;
                        System.out.println
("Profit: " + profit);
                        System.out.println
("Profit Percentage: " + profitPercent + "%");

                    } else if (cp > sp) {
                        double loss = cp - sp;
                        double lossPercent 
= (loss / cp) * 100;
                        System.out.println
("Loss: " + loss);
                        System.out.println
("Loss Percentage: " + lossPercent + "%");

                    } else {
                        System.out.println
("No Profit, No Loss.");
                    }
                    break;

                case 2:
                    System.out.println
("Exiting...");
                    break;

                default:
                    System.out.println
("Invalid Choice! Try again.");
            }

        } while (choice != 2);

        sc.close();
    }
}

3. GUI Version (Java Swing)

This version shows a small graphical window for input and output.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ProfitLossGUI extends JFrame {

    private JTextField cpField, spField;
    private JButton btnCalculate;
    private JLabel resultLabel;

    public ProfitLossGUI() {
        setTitle("Profit & Loss Calculator");
        setSize(350, 250);
        setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(4, 2));

        add(new JLabel("Cost Price (CP): "));
        cpField = new JTextField();
        add(cpField);

        add(new JLabel("Selling Price (SP): "));
        spField = new JTextField();
        add(spField);

        btnCalculate = new JButton
("Calculate");
        add(btnCalculate);

        resultLabel = new JLabel("");
        add(resultLabel);

        btnCalculate.
addActionListener(new ActionListener() {
            public void
 actionPerformed(ActionEvent e) {
                double cp = 
Double.parseDouble(cpField.getText());
                double sp = 
Double.parseDouble(spField.getText());

                if (sp > cp) {
                    double profit = sp - cp;
                    double profitPer
 = (profit / cp) * 100;
                    resultLabel.setText
("Profit: " + profit + " 
| " + profitPer + "%");

                } else if (cp > sp) {
                    double loss = cp - sp;
                    double lossPer = 
(loss / cp) * 100;
                    resultLabel.
setText("Loss: " + loss + " | " 
+ lossPer + "%");

                } else {
                    resultLabel.
setText("No Profit, No Loss.");
                }
            }
        });

        setVisible(true);
    }

    public static void main(String[] args) {
        new ProfitLossGUI();
    }
}

🎉 All Versions Completed

You now have: ✔ Simple Java Program
✔ OOP/Class-based Program
✔ Menu-driven Console Program
✔ GUI Program using Swing

Mastering Image Mirroring in Python: A Comprehensive Guide to Horizontal and Vertical Flips

  Mastering Image Mirroring in Python: A Comprehensive Guide to Horizontal and Vertical Flips Ever snapped a selfie only to notice it's...