Enum Constructor example

📘 Java Enums with Constructors — A Simple & Clear Guide

Enums in Java are often misunderstood as simple lists of constants.
But Enums are actually powerful types — they can include fields, methods, and even constructors.

In this blog, we’ll explore how to use Enum constructors to attach data to each enum constant.
We’ll also walk through an example where each subject has a maximum mark.


✅ What Are Enums in Java?

enum stands for enumeration, and it represents a fixed set of constants.

Example:

enum Color { RED, GREEN, BLUE }

But Java enums are much more than constants.
They are full-fledged classes with:

  • Variables (fields)

  • Methods

  • Constructors


🎯 Why Use Constructors in Enums?

Sometimes, each enum constant needs to hold some extra information.

For example:

  • Days of week → working hours

  • Planets → mass, radius

  • Subjects → maximum marks

By using a constructor inside an enum, we can store additional data for each constant.


🧩 Example Use Case: Subjects and Maximum Marks

Suppose you want to store maximum marks for each subject:

SubjectCodeMaximum Mark
PhysicsP50
ChemistryC50
BiologyB75
MathM100

Instead of using separate variables or maps, we attach values directly to enum constants.


🧱 Text Diagram: How Enum with Constructor Works

┌───────────────────────────────┐ │ enum MaxMark │ ├───────────────────────────────┤ │ P(50) → maxmark = 50 │ │ C(50) → maxmark = 50 │ │ B(75) → maxmark = 75 │ │ M(100) → maxmark = 100 │ ├───────────────────────────────┤ │ getMaxmark() returns value │ └───────────────────────────────┘

Each constant calls the constructor with a different value.


🧑‍💻 Full Java Code Example

package com.vinod.test; /** * Example showing Java Enum with Constructor * Author: Vinod Kariyathungal Kumaran */ public class EnumConstructorExample { public static void main(String[] args) { // Print all subjects and their maximum marks for (MaxMark m : MaxMark.values()) { System.out.println("Subject code=" + m + " Maximum Mark " + m.getMaxmark()); } // Print a specific subject's maximum mark System.out.println("Physics Maximum Mark=" + MaxMark.P.getMaxmark()); } } enum MaxMark { P(50), C(50), B(75), M(100); private int maxmark; // Enum constructor MaxMark(int p) { maxmark = p; } // Getter method int getMaxmark() { return maxmark; } }

🟦 Explanation

🔹 1. Enum Constants with Values

P(50), C(50), B(75), M(100)

Each constant calls the constructor with a number (max mark).

🔹 2. Constructor

MaxMark(int p) { maxmark = p; }

This assigns the passed value to the internal variable.

🔹 3. Getter Method

int getMaxmark() { return maxmark; }

Used to read the stored value.


🖨️ Program Output

Subject code=P Maximum Mark 50 Subject code=C Maximum Mark 50 Subject code=B Maximum Mark 75 Subject code=M Maximum Mark 100 Physics Maximum Mark=50

🎉 Final Thoughts

Java Enums are more powerful than most people realize.
By adding constructors and fields, you can treat them like lightweight data holders — clean, readable, and type-safe.

This approach is perfect for:

✔ Subject mark mapping
✔ Error codes with descriptions
✔ HTTP status codes
✔ Pricing tiers
✔ Role definitions


Abstraction and Encapsulation difference in simple way

Abstraction vs Encapsulation (Explained for Backend Engineers)

Simple, Practical, and Use-Case Based

Understanding Abstraction and Encapsulation is essential for writing maintainable backend code.
Most interviewers ask this, and many developers mix them up.

Here is the clearest possible explanation.


1. What is Abstraction?

Hiding unnecessary details and exposing only essential behavior.
Abstraction answers the question:

“WHAT does this object do?”

It focuses on the capabilities of a system, not how it is implemented.

Think of abstraction as a contract.


Real-World Example (Simple)

You drive a car using:

  • Steering

  • Brake

  • Accelerator

You don’t need to know:

  • how fuel injectors work

  • how ABS works

  • internal engine mechanics

You only care about what the car can do → turn, slow, speed up.


Java Code Example — Abstraction

interface PaymentService { void pay(double amount); }

The interface says what can be done → pay.
Nothing about how payment actually happens.


2. What is Encapsulation?

Bundling data + methods and protecting internal details using access modifiers.
Encapsulation answers:

“HOW does this object do what it does?”

It focuses on controlling access and hiding implementation.


Real-World Example

A washing machine:

  • You select a mode (normal, deep wash)

  • Inside: motor speed, timers, water levels are controlled

You cannot directly change internal components → they’re encapsulated.


Java Code Example — Encapsulation

class PaymentProcessor { private double balance; // hidden data (encapsulation) public void addMoney(double amount) { balance += amount; } public double getBalance() { return balance; } }

Here:

  • balance is hidden

  • access only through getter/setter

  • internal logic protected from misuse


3. Key Difference (Simple Interview Answer)

FeatureAbstractionEncapsulation
MeaningHides complexityHides internal data
FocusWhat object doesHow object works
Achieved ByInterfaces, Abstract classesClasses, access modifiers (private, public)
PurposeExpose essential features onlyProtect data & maintain integrity
ExamplePaymentService.pay()private balance variable

4. Use Case for Backend Engineers

✅ Use Case: Payment System in a Microservice Architecture

Abstraction:

Expose only the required behavior to other services.

public interface PaymentGateway { TransactionResponse makePayment(double amount); }
  • Other microservices don’t care if payment is done via Stripe, PayPal, RazorPay →

  • Abstraction hides vendor-specific logic.


Encapsulation:

Protect internal state inside the payment processor.

class RazorPayProcessor implements PaymentGateway { private String apiKey; // encapsulated data private String secretKey; // encapsulated data @Override public TransactionResponse makePayment(double amount) { // internal API call logic (hidden) } }
  • API keys hidden

  • Authentication logic hidden

  • No external service can modify internal state


5. Text-Based Diagram (Perfect for Blog & Interview)

┌─────────────────────────────┐ │ ABSTRACTION │ │ "WHAT action is allowed?" │ │ │ │ Interface: PaymentGateway │ │ - makePayment() │ └─────────────────────────────┘ │ ▼ ┌─────────────────────────────┐ │ ENCAPSULATION │ │ "HOW is the action done?" │ │ │ │ Class: RazorPayProcessor │ │ - private apiKey │ │ - private secretKey │ │ - internal logic hidden │ └─────────────────────────────┘

6. Super-Simple Memory Trick

Abstraction = Remote Control
You can press the button → but you don’t know the internals.

Encapsulation = TV Circuit Box
Everything wired inside → protected from you touching it.


✅ Final 1-Line Summary (Best for Interview)

Abstraction defines what an object can do. Encapsulation defines how it does it while protecting the internal state.


 

 

 

 

Linear Search example


🔎 Linear Search (Sequential Search)

What problem are we solving?

Given an array and a target value (the “key”), find the index where the key occurs. If it isn’t present, report that clearly (commonly -1).

When should you use it?

  • Arrays or lists that are unsorted (binary search won’t help).

  • Small to medium collections where code simplicity matters.

  • One-off searches where building an index or sorting is overkill.

How it works (step by step)

  1. Start at index 0.

  2. Compare the current element to the key.

  3. If they match → return the index.

  4. Otherwise move to the next element and repeat.

  5. If you reach the end with no match → return -1.

Complexity

  • Time: O(n) in the worst/average case; O(1) best case (if the key is at index 0).

  • Space: O(1) (in-place, no extra memory).


Java Implementation





 




package com.vinod.test;

/**
 * LinearSearch (Sequential Search)
 *
 * Problem:
 *   Given an array and a key, return the index of the key if present; otherwise -1.
 *
 * Approach:
 *   Scan from left to right and compare each element with the key.
 *
 * Time Complexity:
 *   Worst/Average: O(n), Best: O(1) if the first element matches.
 *
 * Space Complexity:
 *   O(1)
 *
 * Notes:
 *   - Works on unsorted arrays.
 *   - For sorted arrays, consider Binary Search (O(log n)).
 */
public class LinearSearch {

    public static void main(String[] args) {
        int[] arr = { 1, 3, 5, 7, 9, 12, 16, 18 };

        int key1 = 5;
        int idx1 = indexOf(arr, key1);
        System.out.println("Key " + key1 + " found at index = " + idx1); // expected: 2

        int key2 = 10;
        int idx2 = indexOf(arr, key2);
        System.out.println("Key " + key2 + " found at index = " + idx2); // expected: -1
    }

    /**
     * Returns the zero-based index of {@code key} in {@code arr}, or -1 if not found.
     *
     * @param arr the array to scan (may be unsorted)
     * @param key the value to find
     * @return index of the key if present; otherwise -1
     */
    public static int indexOf(int[] arr, int key) {
        if (arr == null || arr.length == 0) {
            return -1; // handle null/empty safely
        }

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == key) {
                return i; // found
            }
        }
        return -1; // not found
    }
}

Binary search algorithm and example

🔍 Binary Search (Divide-and-Conquer Algorithm)

What problem are we solving?

When we have a sorted array, we often need to locate a specific value efficiently — for example, to find the index of a student ID or a product code.
Instead of scanning element by element like Linear Search (which takes O(n) time), Binary Search repeatedly divides the search space in half, achieving much faster performance.


🧠 How it works (step by step)

  1. Precondition: The array must already be sorted (either ascending or descending).

  2. Initialize two pointers:

    • start = 0 (beginning of the array)

    • end = arr.length - 1 (end of the array)

  3. Find the middle index:
    mid = (start + end) / 2

  4. Compare the middle element (arr[mid]) with the key you’re searching for:

    • If arr[mid] == key → ✅ Found → return mid

    • If key < arr[mid] → search left half → set end = mid - 1

    • If key > arr[mid] → search right half → set start = mid + 1

  5. Repeat until start > end.
    If the loop ends with no match, the key isn’t present → return -1.

 


package
com.vinod.test;


/**
 * Binary search use to find out the position of the elements for the given key.
 *
 * The Array should be either in ascending or decending order.
 *
 *@authorvinodkariyathungalkumaran
 *
 */
public class BinarySearch {

public static void main(String[] args) {
int[] arr = { 1, 3, 5, 7, 9, 12, 16, 18 };
System.out.println("Position of 5=" + getPositionUsingBinarySearch(arr, 5));

}

/**
     * Algorithm
     *
     *1) First get the array mid position, if mid position of the value equal to the search key will return that one
     *
     *2) Else if key is less the mid value our start value will be o and end value will be mid -1
     *
     *3) Else if the key is greater than the mid value we will mark our start value as mid value +1
     *
     * This activity we will do until the start and end values are equal.
     *
     *
     *@param arr
     *@param key
     *@return
     */
public static int getPositionUsingBinarySearch(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (key == arr[mid]) {
return mid;
}
if (key < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}

Program to find out sum of digits

🔢 Find the Sum of Digits of a Number (Java)

🧩 What problem are we solving?

We often need to find the sum of digits in a number — for example, to check whether a number is divisible by 3 or 9, or as a simple exercise in integer manipulation.

Given a number (like 111), the goal is to extract each digit, add them together, and display the total.
For 111, the result is 1 + 1 + 1 = 3.


⚙️ How it works (step by step)

  1. Start with a number, say a = 111.

  2. Initialize sum = 0.

  3. Repeat while a > 0:

    • Get the last digit using the modulo operator: d = a % 10

    • Add it to sum: sum = sum + d

    • Remove the last digit from the number using integer division: a = a / 10

  4. When a becomes 0, print the sum.


🧠 Example Walkthrough

Let’s trace the steps for a = 111:

Stepa    a % 10 (digit)    sum after addition    a / 10 (next a)
1111            1            1            11
211            1            2            1
31            1            3            0

✅ Final sum = 3


Main program

package com.vinod.test;


/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindSumOfDigits {
public static void main(String[] args) {
{
int sum, d;
int a = 111;
sum = 0;
for (int i = 1; i <= 10; i++) {
d = a % 10;
a = a / 10;
sum = sum + d;
}
System.out.println("Sum of Digit =" + sum);
}
}

}

Ouput

Sum of Digit =3


How to find out common elements between two arrays

🔗 Find Common Numbers Between Two Arrays (Java)

🧩 What problem are we solving?

Given two arrays of integers, the goal is to find and print all the numbers that appear in both arrays — i.e., the common elements or intersection of the two arrays.

For example:
If we have

Array 1 = [12, 13, 14, 15, 16, 17] Array 2 = [12, 18, 29, 15, 7, 17]

then the numbers common to both are 12, 15, and 17.


⚙️ How it works (step by step)

  1. Start with two arrays of integers.

  2. Loop through each element of the first array (array1).

  3. For each element in array1, loop through the second array (array2).

  4. If a match is found (array1[i] == array2[j]), print or store that number.

  5. Continue until all elements have been compared.

This approach compares every element in array1 with every element in array2, ensuring all common numbers are identified.


🧠 Example Walkthrough

StepCompareMatch?Common Numbers Found
112 vs 1212
213 vs all12
314 vs all12
415 vs 1512, 15
516 vs all12, 15
617 vs 1712, 15, 17

Output:

12 15 17


package com.vinod.test;


/**
 * Class to find common numbers from two arrays
 *
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindCommonNumbers {

public static void main(String[] args) {
int array1[] = { 12, 13, 14, 15, 16, 17 };
int array2[] = { 12, 18, 29, 15, 7, 17 };

for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
System.out.println(array1[i]);
}
}
}

}

}

Output

12
15
17


Program to find out Largest and Smallest Value in an Array

🔺 Find the Largest and Smallest Number in an Array (Java)

🧩 What problem are we solving?

Given an array of numbers, we need to identify the largest and smallest values without sorting the array.
This is one of the most fundamental problems in programming — often used to teach how to iterate, compare, and track state within a loop.

Example:
If we have

[35, 21, 44, 55, 22, 1, 7]

Then:
Largest value = 55
Smallest value = 1


⚙️ How it works (step by step)

  1. Initialize two variables:

    • largest = first element in the array (numbers[0])

    • smallest = first element in the array (numbers[0])

  2. Iterate through the array starting from the second element (index 1).

  3. For each element:

    • If the element is greater than largest, update largest.

    • If the element is smaller than smallest, update smallest.

  4. After scanning all elements, print both values.


🧠 Example Walkthrough

Let’s trace the logic for:

numbers = [35, 21, 44, 55, 22, 1, 7]
StepCurrent NumberLargestSmallest
Start353535
1213521
2444421
3555521
4225521
51551
67551

✅ Final Output:

Largest value 55 Smallest value 1


package com.vinod.test;

/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindLargestAndSmallestNumber {

public static void main(String[] args) {

int numbers[] = new int[] { 35, 21, 44, 55, 22, 1, 7 };
int smallest = numbers[0];
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}
System.out.println("Largest value " + largest);
System.out.println("Smallest value " + smallest);
}
}

Output

Largest value 55
Smallest value 1

 

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts