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

 

Program to reverse a String without using StringBuilder

🔁 Reverse a String in Java (Without Using StringBuilder.reverse())

🧩 What problem are we solving?

The goal is to reverse the characters of a given string manually — without using built-in helper methods like StringBuilder.reverse().

This exercise helps understand string manipulation, loops, and index-based access in Java.

For example:
If the input is

"My Name is Vinod"

Then the output will be

"doniV si emaN yM"

⚙️ How it works (step by step)

  1. Start with an input string, e.g. "My Name is Vinod".

  2. Initialize an empty string reverse = "".

  3. Loop backward from the end of the string (str.length() - 1) to the beginning (0).

  4. For each character:

    • Append it to reverse.

  5. Once the loop completes, reverse will contain the reversed text.

  6. Print the reversed string.


🧠 Example Walkthrough

StepCurrent IndexCharacterReverse String
115dd
214odo
313ndon
412idoni
511VdoniV
610(space)doniV
Final0MdoniV si emaN yM

Final Output:
doniV si emaN yM


package com.vinod.test;


/**
 * Example to reverse a String without using StringBuilder reverse method.
 *@authorvinodkariyathungalkumaran
 *
 */
public class ReverseStringExample {

public static void main(String[] args) {
String str = "My Name is Vinod";
System.out.println("Input=" + str);
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
System.out.println("Output=" + reverse);
}

}

Ouput

Input=My Name is Vinod
Output=doniV si emaN yM

Algorithm and program to find out duplicate character in a String

🧮 Find Duplicate Characters in a String (Java)

🧩 What problem are we solving?

The goal is to analyze a given string and determine how many times each character appears — effectively identifying duplicate or repeating characters.

For example, given:

"My name is Vinod"

the output should display how often each character occurs:

Character : Count : 3 Character : a Count : 1 Character : s Count : 1 Character : d Count : 1 Character : e Count : 1 Character : V Count : 1 Character : y Count : 1 Character : i Count : 2 Character : M Count : 1 Character : m Count : 1 Character : n Count : 2 Character : o Count : 1

This problem is useful for understanding:

  • How to work with maps (HashMap)

  • How to iterate characters in a string

  • How to count frequencies of elements efficiently


⚙️ Algorithm (Step-by-Step)

  1. Create a HashMap<Character, Integer>
    → To store each character as a key and its count as the value.

  2. Convert the string into a character array
    → Use toCharArray() to easily loop through characters.

  3. Iterate through the character array
    → For each character:

    • If it’s already in the map → increment the count.

    • If not → add it with count = 1.

  4. Display the results
    → Print each key-value pair to show how many times each character occurs.


🧠 Example Walkthrough

Let’s trace through the string:
"My name is Vinod"

StepCharacterAlready in Map?ActionUpdated Count
1MAdd M=11
2yAdd y=11
3(space)Add space=11
4nAdd n=11
5aAdd a=11
6mAdd m=11
7eAdd e=11
8(space)Increment2
9iAdd i=11
10sAdd s=11
11(space)Increment3
12VAdd V=11
13iIncrement2
14nIncrement2
15oAdd o=11
16dAdd d=11

✅ Final Map contents printed in iteration order:

(space)=3, a=1, s=1, d=1, e=1, V=1, y=1, i=2, M=1, m=1, n=2, o=1

📘 Java Implementation

package com.vinod.test;

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

/**
 * FindDuplicateCharactorInString
 *
 * Problem:
 *   Count and identify duplicate characters in a given string.
 *
 * Algorithm:
 *   1. Create a HashMap to store each character and its frequency.
 *   2. Convert the input string into a char[] array.
 *   3. Iterate through the array:
 *        - If the character exists in the map, increment its count.
 *        - Otherwise, add it to the map with count = 1.
 *   4. Print all characters and their counts.
 *
 * Example:
 *   Input:  "My name is Vinod"
 *   Output:
 *     Character :   Count : 3
 *     Character : a Count : 1
 *     Character : s Count : 1
 *     Character : d Count : 1
 *     Character : e Count : 1
 *     Character : V Count : 1
 *     Character : y Count : 1
 *     Character : i Count : 2
 *     Character : M Count : 1
 *     Character : m Count : 1
 *     Character : n Count : 2
 *     Character : o Count : 1
 *
 * Time Complexity:
 *   O(n) – Each character is processed once.
 *
 * Space Complexity:
 *   O(k) – Where k is the number of unique characters.
 *
 * Author: Vinod Kariyathungal Kumaran
 */
public class FindDuplicateCharactorInString {

    public static void main(String[] args) {
        Map duplicateMap = new HashMap<>();

        String str = "My name is Vinod";
        char[] chrs = str.toCharArray();

        for (Character ch : chrs) {
            if (duplicateMap.containsKey(ch)) {
                duplicateMap.put(ch, duplicateMap.get(ch) + 1);
            } else {
                duplicateMap.put(ch, 1);
            }
        }

        duplicateMap.forEach((k, v) ->
            System.out.println("Character : " + k + " Count : " + v)
        );
    }
} 
 
Character :   Count : 3
Character : a Count : 1
Character : s Count : 1
Character : d Count : 1
Character : e Count : 1
Character : V Count : 1
Character : y Count : 1
Character : i Count : 2
Character : M Count : 1
Character : m Count : 1
Character : n Count : 2
Character : o Count : 1
 

Algorithm and program to reverse a Number in java

🔢 Reverse a Number in Java (Without Using Built-in Reverse Methods)

🧩 What problem are we solving?

The goal is to reverse the digits of an integer — for example, converting 122 into 221.
This is a classic example to understand how to work with loops, integer division, and the modulo operator in Java.


⚙️ Algorithm (Step by Step)

We want to rebuild the number by extracting its last digit and adding it to a new reversed number in each step.

Formula:

Reverse = (Reverse * 10) + (Number % 10) Number = Number / 10

Step-by-Step Example

Let’s take the input number 122:

StepNumberReverse CalculationReverse ResultNew Number
1122(0 × 10) + (122 % 10)212
212(2 × 10) + (12 % 10)221
31(22 × 10) + (1 % 10)2210

Final Output: 221


🧠 Key Concept

  • % (modulo) gives the last digit of a number.
    122 % 10 = 2

  • / (integer division) removes the last digit.
    122 / 10 = 12

  • Multiplying the current reverse by 10 shifts digits left to make room for the next digit.


📘 Java Implementation


package com.vinod.test;

/**
 * ReverseNumberExample
 *
 * Problem:
 *   Reverse the digits of an integer without using built-in reverse functions.
 *
 * Algorithm:
 *   1. Initialize reverse = 0.
 *   2. Repeat while number != 0:
 *        - Extract the last digit using number % 10.
 *        - Multiply reverse by 10 and add the extracted digit.
 *        - Divide number by 10 to remove the last digit.
 *   3. Print the reversed number.
 *
 * Example:
 *   Input:  122
 *   Output: 221
 *
 * Time Complexity:
 *   O(log10(n)) → proportional to the number of digits.
 *
 * Space Complexity:
 *   O(1)
 *
 * Author: Vinod Kariyathungal Kumaran
 */
public class ReverseNumberExample {
    public static void main(String[] args) {
        int reverse = 0;
        int number = 122;

        System.out.println("Input number = " + number);
        System.out.println("Intermediate steps:");

        while (number != 0) {
            reverse = (reverse * 10) + (number % 10);
            System.out.println("Reverse = " + reverse);
            number = number / 10;
            System.out.println("Number = " + number);
        }

        System.out.println("Reversed number = " + reverse);

        // Alternative method using StringBuilder
        StringBuilder sb = new StringBuilder(String.valueOf(122));
        System.out.println("Reversed number using StringBuilder = " + sb.reverse().toString());
    }
} 

🧩 Output

Input number = 122
Intermediate steps:
Reverse = 2
Number = 12
Reverse = 22
Number = 1
Reverse = 221
Number = 0
Reversed number = 221
Reversed number using StringBuilder = 221

How to find duplicate number between 1 to n th Numbers

Sample program and Algorithm

package com.vinod.test;


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


/**
 *@authorvinodkariyathungalkumaran
 *
 */
public class FindDuplicateNumber {


public static void main(String a[]) {
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i <= 50; i++) {
numbers.add(i);
}
numbers.add(11);
FindDuplicateNumber duplicateNumber = new FindDuplicateNumber();
System.out.println("Duplicate Number in the list: " + duplicateNumber.findDuplicateNumber(numbers));
}

/**
     * Algorithm to find out the duplicate number from 1 to n th value
     *
     *1)First find out the sum of the all values in the array list
     *
     *2)Find out the sum of the 1 to n th values
     *
     *3) duplicate value = Frist step value- Second step value
     *
     *
     *@param numbers
     *@return
     */
public int findDuplicateNumber(List<Integer> numbers) {
int highestNumber = numbers.size() - 1;
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
int duplicate = sum - (highestNumber * (highestNumber + 1) / 2);
return duplicate;
}


}

Output

Duplicate Number in the list: 11

 

 

Java program to print available Locales

Here is one java program to print all java supported locales and its countries.

package com.vinod.testt;


import java.text.SimpleDateFormat;
import java.util.Locale;


public class LocaleTest {

public static void main(String[] args) {
Locale locales[] = SimpleDateFormat.getAvailableLocales();
for (int i = 0; i < locales.length; i++) {
System.out.printf("%10s - %s, %s \n" , locales[i].toString(),
locales[i].getDisplayName(), locales[i].getDisplayCountry());
}}

}

Output

     ar_AE - Arabic (United Arab Emirates), United Arab Emirates
ar_JO - Arabic (Jordan), Jordan
ar_SY - Arabic (Syria), Syria
hr_HR - Croatian (Croatia), Croatia
fr_BE - French (Belgium), Belgium
es_PA - Spanish (Panama), Panama
mt_MT - Maltese (Malta), Malta
es_VE - Spanish (Venezuela), Venezuela
bg - Bulgarian,
zh_TW - Chinese (Taiwan), Taiwan
it - Italian,
ko - Korean,
uk - Ukrainian,
lv - Latvian,
da_DK - Danish (Denmark), Denmark
es_PR - Spanish (Puerto Rico), Puerto Rico
vi_VN - Vietnamese (Vietnam), Vietnam
en_US - English (United States), United States
sr_ME - Serbian (Montenegro), Montenegro
sv_SE - Swedish (Sweden), Sweden
es_BO - Spanish (Bolivia), Bolivia
en_SG - English (Singapore), Singapore
ar_BH - Arabic (Bahrain), Bahrain
pt - Portuguese,
ar_SA - Arabic (Saudi Arabia), Saudi Arabia
sk - Slovak,
ar_YE - Arabic (Yemen), Yemen
hi_IN - Hindi (India), India
ga - Irish,
en_MT - English (Malta), Malta
fi_FI - Finnish (Finland), Finland
et - Estonian,
sv - Swedish,
cs - Czech,
sr_BA_#Latn - Serbian (Latin,Bosnia and Herzegovina), Bosnia and Herzegovina
el - Greek,
uk_UA - Ukrainian (Ukraine), Ukraine
hu - Hungarian,
fr_CH - French (Switzerland), Switzerland
in - Indonesian,
es_AR - Spanish (Argentina), Argentina
ar_EG - Arabic (Egypt), Egypt
ja_JP_JP_#u-ca-japanese - Japanese (Japan,JP), Japan
es_SV - Spanish (El Salvador), El Salvador
pt_BR - Portuguese (Brazil), Brazil
be - Belarusian,
is_IS - Icelandic (Iceland), Iceland
cs_CZ - Czech (Czech Republic), Czech Republic
es - Spanish,
pl_PL - Polish (Poland), Poland
tr - Turkish,
ca_ES - Catalan (Spain), Spain
sr_CS - Serbian (Serbia and Montenegro), Serbia and Montenegro
ms_MY - Malay (Malaysia), Malaysia
hr - Croatian,
lt - Lithuanian,
es_ES - Spanish (Spain), Spain
es_CO - Spanish (Colombia), Colombia
bg_BG - Bulgarian (Bulgaria), Bulgaria
sq - Albanian,
fr - French,
ja - Japanese,
sr_BA - Serbian (Bosnia and Herzegovina), Bosnia and Herzegovina
is - Icelandic,
es_PY - Spanish (Paraguay), Paraguay
de - German,
es_EC - Spanish (Ecuador), Ecuador
es_US - Spanish (United States), United States
ar_SD - Arabic (Sudan), Sudan
en - English,
ro_RO - Romanian (Romania), Romania
en_PH - English (Philippines), Philippines
ca - Catalan,
ar_TN - Arabic (Tunisia), Tunisia
sr_ME_#Latn - Serbian (Latin,Montenegro), Montenegro
es_GT - Spanish (Guatemala), Guatemala
sl - Slovenian,
ko_KR - Korean (South Korea), South Korea
el_CY - Greek (Cyprus), Cyprus
es_MX - Spanish (Mexico), Mexico
ru_RU - Russian (Russia), Russia
es_HN - Spanish (Honduras), Honduras
zh_HK - Chinese (Hong Kong), Hong Kong
no_NO_NY - Norwegian (Norway,Nynorsk), Norway
hu_HU - Hungarian (Hungary), Hungary
th_TH - Thai (Thailand), Thailand
ar_IQ - Arabic (Iraq), Iraq
es_CL - Spanish (Chile), Chile
fi - Finnish,
ar_MA - Arabic (Morocco), Morocco
ga_IE - Irish (Ireland), Ireland
mk - Macedonian,
tr_TR - Turkish (Turkey), Turkey
et_EE - Estonian (Estonia), Estonia
ar_QA - Arabic (Qatar), Qatar
sr__#Latn - Serbian (Latin),
pt_PT - Portuguese (Portugal), Portugal
fr_LU - French (Luxembourg), Luxembourg
ar_OM - Arabic (Oman), Oman
th - Thai,
sq_AL - Albanian (Albania), Albania
es_DO - Spanish (Dominican Republic), Dominican Republic
es_CU - Spanish (Cuba), Cuba
ar - Arabic,
ru - Russian,
en_NZ - English (New Zealand), New Zealand
sr_RS - Serbian (Serbia), Serbia
de_CH - German (Switzerland), Switzerland
es_UY - Spanish (Uruguay), Uruguay
ms - Malay,
el_GR - Greek (Greece), Greece
iw_IL - Hebrew (Israel), Israel
en_ZA - English (South Africa), South Africa
th_TH_TH_#u-nu-thai - Thai (Thailand,TH), Thailand
hi - Hindi,
fr_FR - French (France), France
de_AT - German (Austria), Austria
nl - Dutch,
no_NO - Norwegian (Norway), Norway
en_AU - English (Australia), Australia
vi - Vietnamese,
nl_NL - Dutch (Netherlands), Netherlands
fr_CA - French (Canada), Canada
lv_LV - Latvian (Latvia), Latvia
de_LU - German (Luxembourg), Luxembourg
es_CR - Spanish (Costa Rica), Costa Rica
ar_KW - Arabic (Kuwait), Kuwait
sr - Serbian,
ar_LY - Arabic (Libya), Libya
mt - Maltese,
it_CH - Italian (Switzerland), Switzerland
da - Danish,
de_DE - German (Germany), Germany
ar_DZ - Arabic (Algeria), Algeria
sk_SK - Slovak (Slovakia), Slovakia
lt_LT - Lithuanian (Lithuania), Lithuania
it_IT - Italian (Italy), Italy
en_IE - English (Ireland), Ireland
zh_SG - Chinese (Singapore), Singapore
ro - Romanian,
en_CA - English (Canada), Canada
nl_BE - Dutch (Belgium), Belgium
no - Norwegian,
pl - Polish,
zh_CN - Chinese (China), China
ja_JP - Japanese (Japan), Japan
de_GR - German (Greece), Greece
sr_RS_#Latn - Serbian (Latin,Serbia), Serbia
iw - Hebrew,
en_IN - English (India), India
ar_LB - Arabic (Lebanon), Lebanon
es_NI - Spanish (Nicaragua), Nicaragua
zh - Chinese,
mk_MK - Macedonian (Macedonia), Macedonia
be_BY - Belarusian (Belarus), Belarus
sl_SI - Slovenian (Slovenia), Slovenia
es_PE - Spanish (Peru), Peru
in_ID - Indonesian (Indonesia), Indonesia
en_GB - English (United Kingdom), United Kingdom

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts