Recent Posts

  • How to Convert String to int in Java

    In this Java tutorial, we will learn how to convert a String into an int value using both traditional Java and Java 8.

    For example:

    String : "100"
    int    : 100

    1. Traditional Java Program

    The Integer.parseInt() method is the simplest way to convert a String into an int.

    public class StringToInt {
    
        public static void main(String[] args) {
            String str = "100";
            int number = Integer.parseInt(str);
            System.out.println("String: " + str);
            System.out.println("Integer: " + number);
        }
    }

    Output

    String: 100
    Integer: 100

    Explanation

    The following statement converts the String "100" into the integer 100:

    int number = Integer.parseInt(str);

    Here:

    • str is a String.
    • Integer.parseInt() converts the String into a primitive int.
    • number stores the converted integer value.

    For example:

    String str = "250";
    
    int number = Integer.parseInt(str);

    Now number contains the integer value 250.


    2. Java 8 Program

    Java 8 does not introduce a special new method for converting a String to an int. The recommended method is still Integer.parseInt().

    However, Java 8 also allows us to use the Stream API when we need to convert multiple String values.

    import java.util.Arrays;
    
    public class StringToIntJava8 {
    
        public static void main(String[] args) {
            String[] strArray = {"10", "20", "30", "40"};
            int[] numbers = Arrays.stream(strArray)
                    .mapToInt(Integer::parseInt)
                    .toArray();
            System.out.println("Integer Array: "
                    + Arrays.toString(numbers));
        }
    }

    Output

    Integer Array: [10, 20, 30, 40]

    Explanation of Java 8 Program

    First, the String array is converted into a Stream:

    Arrays.stream(strArray)

    Then, mapToInt() converts each String into an integer:

    .mapToInt(Integer::parseInt)

    Here, Integer::parseInt is a Java 8 method reference.

    Finally, toArray() converts the values into an int array:

    .toArray();

    3. Converting a Single String in Java 8

    If you only need to convert one String to an integer, simply use:

    String str = "100";
    
    int number = Integer.parseInt(str);

    This works perfectly in Java 8.

    You do not need to use Streams for a single String conversion.


    Difference Between Traditional Java and Java 8

    FeatureTraditional JavaJava 8
    Single String conversionInteger.parseInt()Integer.parseInt()
    Multiple String conversionLoopStream API
    LambdaNoOptional
    Method referenceNoInteger::parseInt
    Easy for beginnersVery easyModerate
    Java VersionJava 5+Java 8+

    Important Note

    If the String does not contain a valid integer, Integer.parseInt() throws a NumberFormatException.

    For example:

    String str = "ABC";
    
    int number = Integer.parseInt(str);

    This will produce:

    NumberFormatException

    Therefore, make sure the String contains a valid numeric value before converting it.

    Conclusion

    Converting a String to an int is very easy in Java. The Integer.parseInt() method is the standard approach and works in Java 8 as well. For converting multiple String values, Java 8 Streams and method references can make the code concise and readable.

  • How to Convert String Array to List in Java

    In this Java tutorial, we will learn how to convert a String array into a List using both traditional Java and Java 8.

    For example:

    String Array : {"Java", "Python", "C++", "JavaScript"}
    
    List        : [Java, Python, C++, JavaScript]

    1. Traditional Java Program

    The Arrays.asList() method can be used to convert a String array into a List.

    import java.util.Arrays;
    import java.util.List;
    
    public class StringArrayToList {
        public static void main(String[] args) {
            String[] array = {"Java", "Python", "C++", "JavaScript"};
            List<String> list = Arrays.asList(array);
            System.out.println("String Array: "
                    + Arrays.toString(array));
            System.out.println("List: " + list);
        }
    }

    Output

    String Array: [Java, Python, C++, JavaScript]
    List: [Java, Python, C++, JavaScript]

    Explanation

    The Arrays.asList() method converts the array into a List:

    List<String> list = Arrays.asList(array);

    Here, array is a String array and list is a List<String>.

    Important Note

    The List returned by Arrays.asList() is fixed-size. You can change an existing element, but you cannot add or remove elements.

    For example:

    list.set(0, "C");

    is allowed, but:

    list.add("HTML");

    will throw UnsupportedOperationException.

    If you need a modifiable List, use:

    List<String> list = new ArrayList<>(Arrays.asList(array));

    2. Java 8 Program

    Java 8 introduced the Stream API, which provides another way to convert an array into a List.

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class StringArrayToListJava8 {
        public static void main(String[] args) {
            String[] array = {"Java", "Python", "C++", "JavaScript"};
            List<String> list = Arrays.stream(array)
                    .collect(Collectors.toList());
            System.out.println("String Array: "
                    + Arrays.toString(array));
            System.out.println("List: " + list);
        }
    }

    Output

    String Array: [Java, Python, C++, JavaScript]
    List: [Java, Python, C++, JavaScript]

    Explanation of Java 8 Program

    First, we convert the array into a Stream:

    Arrays.stream(array)

    Then, collect() collects the stream elements into a List:

    .collect(Collectors.toList())

    The complete statement is:

    List<String> list = Arrays.stream(array)
            .collect(Collectors.toList());

    This is a common Java 8 approach when you also want to filter, transform, or process the array elements while creating the List.


    3. Java 8 Using Arrays.asList()

    It is also important to understand that Arrays.asList() works perfectly in Java 8:

    String[] array = {"Java", "Python", "C++", "JavaScript"};
    
    List<String> list = Arrays.asList(array);

    You do not need Streams just because you are using Java 8.

    Difference Between the Approaches

    FeatureTraditional JavaJava 8 Stream
    MethodArrays.asList()Arrays.stream()
    Stream APINoYes
    Lambda requiredNoNo
    Simple conversionExcellentGood
    Filtering/processingLess convenientExcellent
    Java VersionJava 5+Java 8+

    Which Method Should You Use?

    If your only requirement is to convert a String array to a List, the simplest approach is:

    List<String> list = Arrays.asList(array);

    If you need to filter or modify elements while converting, Java 8 Streams are useful:

    List<String> list = Arrays.stream(array)
            .filter(s -> s.length() > 4)
            .collect(Collectors.toList());

    For example, the above code creates a List containing only Strings with more than four characters.

    Conclusion

    Converting a String array to a List is simple in Java. Arrays.asList() is the easiest option for a direct conversion, while the Java 8 Stream API is useful when additional processing such as filtering or transformation is required.

  • Java Program to Sort an Array Using Bubble Sort

    In this Java program, we will learn how to sort an array in ascending order using the Bubble Sort algorithm.

    What is Bubble Sort?

    Bubble Sort is a simple sorting algorithm that repeatedly compares two adjacent elements and swaps them if they are in the wrong order.

    For example:

    Input  : {50, 20, 40, 10, 30}
    Output : {10, 20, 30, 40, 50}

    During each pass, the largest unsorted element moves to the end of the array.

    1. Traditional Java Program Using Bubble Sort

    public class BubbleSort {
    
        public static void main(String[] args) {
            int[] arr = {50, 20, 40, 10, 30};
            System.out.println("Before Sorting:");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
            // Bubble Sort
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    if (arr[j] > arr[j + 1]) {
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            System.out.println("\nAfter Sorting:");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
        }
    }

    Output

    Before Sorting:
    50 20 40 10 30
    
    After Sorting:
    10 20 30 40 50

    Explanation

    The outer for loop controls the number of passes:

    for (int i = 0; i < arr.length - 1; i++)

    The inner loop compares adjacent elements:

    for (int j = 0; j < arr.length - 1 - i; j++)

    If the current element is greater than the next element, they are swapped:

    if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
    }

    For example:

    50 20 40 10 30
    ↑  ↑
    Compare 50 and 20 → Swap
    
    20 50 40 10 30
       ↑  ↑
    Compare 50 and 40 → Swap
    
    20 40 50 10 30
          ↑  ↑
    Compare 50 and 10 → Swap
    
    20 40 10 50 30
             ↑  ↑
    Compare 50 and 30 → Swap
    
    20 40 10 30 50

    After the first pass, the largest value 50 reaches the end.


    2. Java 8 Program Using Lambda Expression

    Java 8 provides Lambda expressions and the Stream API. For learning purposes, we can use a lambda expression to perform the swapping operation.

    import java.util.Arrays;
    import java.util.stream.IntStream;
    
    public class BubbleSortJava8 {
        public static void main(String[] args) {
            int[] arr = {50, 20, 40, 10, 30};
            System.out.println("Before Sorting: "
                    + Arrays.toString(arr));
            IntStream.range(0, arr.length - 1)
                    .forEach(i -> IntStream.range(0, arr.length - 1 - i)
                            .forEach(j -> {
                                if (arr[j] > arr[j + 1]) {
                                    int temp = arr[j];
                                    arr[j] = arr[j + 1];
                                    arr[j + 1] = temp;
                                }
                            }));
            System.out.println("After Sorting: "
                    + Arrays.toString(arr));
        }
    }

    Output

    Before Sorting: [50, 20, 40, 10, 30]
    After Sorting: [10, 20, 30, 40, 50]

    Explanation of Java 8 Program

    The Java 8 version uses IntStream.range() instead of traditional for loops:

    IntStream.range(0, arr.length - 1)

    The forEach() method processes each pass:

    .forEach(i -> ...)

    The inner IntStream compares adjacent elements:

    IntStream.range(0, arr.length - 1 - i)

    The lambda expression:

    i -> ...

    and:

    j -> ...

    are Java 8 features.

    The actual Bubble Sort logic remains the same:

    if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
    }

    Difference Between Traditional Java and Java 8

    FeatureTraditional JavaJava 8
    Sorting algorithmBubble SortBubble Sort
    Loopfor loopIntStream
    Lambda expressionNoYes
    Stream APINoYes
    Easy for beginnersVery easyModerate
    Best for learning Bubble SortYesAfter understanding basics

    Time Complexity

    Bubble Sort has:

    • Best case: O(n) with an optimized implementation
    • Average case: O(n²)
    • Worst case: O(n²)
    • Space complexity: O(1)

    The simple implementation above performs O(n²) comparisons.

    Which Method Should You Use?

    For beginners, the traditional for loop version is strongly recommended because it makes the Bubble Sort algorithm easy to understand.

    The Java 8 version is useful for learning how Streams and Lambda expressions can be used with existing algorithms.

    Conclusion

    Bubble Sort is one of the easiest sorting algorithms to understand. It repeatedly compares adjacent elements and swaps them when necessary. The traditional Java approach clearly demonstrates the sorting logic, while the Java 8 version demonstrates a functional programming style.

  • Java Program to Find an Element Using Linear Search

    In this Java program, we will learn how to find an element in an array using Linear Search.

    What is Linear Search?

    Linear Search is a simple searching technique in which each element of an array is checked one by one until the required element is found.

    For example:

    Array  : {10, 20, 30, 40, 50}
    Search : 30
    Output : Element found at index 2

    The search starts from the first element and continues until the element is found.


    1. Traditional Java Program Using for Loop

    import java.util.Scanner;
    
    public class LinearSearch {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int[] arr = {10, 20, 30, 40, 50};
            System.out.print("Enter element to search: ");
            int search = sc.nextInt();
            int index = -1;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == search) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                System.out.println("Element found at index: " + index);
            } else {
                System.out.println("Element not found");
            }
            sc.close();
        }
    }

    Output

    Enter element to search: 30
    Element found at index: 2

    Explanation

    The program checks each element using a for loop:

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == search) {
            index = i;
            break;
        }
    }

    If the current array element matches the search value:

    arr[i] == search

    the index is stored and the loop stops using break.

    For example:

    Index :  0   1   2   3   4
    Array : 10  20  30  40  50
                      ↑
                   Found

    Therefore, 30 is found at index 2.


    2. Java 8 Program Using Stream API

    Java 8 provides the Stream API, which can be used to perform a linear search in a simple functional style.

    import java.util.Scanner;
    import java.util.stream.IntStream;
    
    public class LinearSearchJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int[] arr = {10, 20, 30, 40, 50};
            System.out.print("Enter element to search: ");
            int search = sc.nextInt();
            int index = IntStream.range(0, arr.length)
                    .filter(i -> arr[i] == search)
                    .findFirst()
                    .orElse(-1);
            if (index != -1) {
                System.out.println("Element found at index: " + index);
            } else {
                System.out.println("Element not found");
            }
            sc.close();
        }
    }

    Output

    Enter element to search: 40
    Element found at index: 3

    Explanation of Java 8 Program

    IntStream.range() creates a stream of array indexes:

    IntStream.range(0, arr.length)

    The filter() method checks whether the element at each index matches the search value:

    .filter(i -> arr[i] == search)

    Here, i -> is a Java 8 lambda expression.

    The findFirst() method returns the first matching index:

    .findFirst()

    If no element is found, orElse(-1) returns -1:

    .orElse(-1)

    Difference Between Traditional Java and Java 8

    FeatureTraditional JavaJava 8
    Approachfor loopStream API
    Lambda expressionNoYes
    Stream APINoYes
    Easy for beginnersVery easyModerate
    Returns first matchbreakfindFirst()
    Java VersionAll common versionsJava 8+

    Which Method Should You Use?

    For beginners, the traditional for loop is recommended because it clearly shows how Linear Search works.

    The Java 8 version is useful for learning Streams, Lambda expressions, filter(), and findFirst().

    Time Complexity

    The best-case time complexity is O(1) when the element is found at the first position.

    The worst-case time complexity is O(n) when the element is at the last position or is not present in the array.

    The traditional and Java 8 approaches both perform a linear search.

    Conclusion

    Linear Search is one of the easiest searching algorithms to understand. It checks each element one by one until the required element is found. The traditional for loop is best for learning the basic logic, while the Java 8 Stream API provides a concise functional approach.

  • Java Program to Replace Each Array Element with the Sum of All Other Elements

    In this Java program, we will learn how to transform an array so that each element is replaced by the sum of all the other elements.

    For example:

    Input  : {10, 20, 30, 40}
    Output : {90, 80, 70, 60}

    How does it work?

    For each element, we calculate the total sum of the array and subtract the current element.

    Total = 10 + 20 + 30 + 40 = 100
    
    100 - 10 = 90
    100 - 20 = 80
    100 - 30 = 70
    100 - 40 = 60

    1. Traditional Java Program Using for Loop

    public class ArraySumExceptElement {
    
        public static void main(String[] args) {
    
            int[] arr = {10, 20, 30, 40};
            int[] result = new int[arr.length];
    
            int sum = 0;
    
            // Calculate the total sum
            for (int i = 0; i < arr.length; i++) {
                sum = sum + arr[i];
            }
    
            // Subtract each element from total sum
            for (int i = 0; i < arr.length; i++) {
                result[i] = sum - arr[i];
            }
    
            System.out.print("Output: {");
    
            for (int i = 0; i < result.length; i++) {
                System.out.print(result[i]);
    
                if (i < result.length - 1) {
                    System.out.print(", ");
                }
            }
    
            System.out.println("}");
        }
    }

    Output

    Output: {90, 80, 70, 60}

    Explanation

    First, we calculate the sum of all array elements:

    int sum = 0;
    
    for (int i = 0; i < arr.length; i++) {
        sum = sum + arr[i];
    }

    For the input array:

    {10, 20, 30, 40}

    the total sum is:

    100

    Then we subtract each element from the total sum:

    result[i] = sum - arr[i];

    Therefore:

    100 - 10 = 90
    100 - 20 = 80
    100 - 30 = 70
    100 - 40 = 60

    The final result is:

    {90, 80, 70, 60}

    2. Java 8 Program Using Stream API

    Java 8 provides the Stream API, which can be used to calculate the total sum and transform each array element.

    import java.util.Arrays;
    
    public class ArraySumExceptElementJava8 {
    
        public static void main(String[] args) {
    
            int[] arr = {10, 20, 30, 40};
    
            int sum = Arrays.stream(arr).sum();
    
            int[] result = Arrays.stream(arr)
                    .map(n -> sum - n)
                    .toArray();
    
            System.out.println("Output: " + Arrays.toString(result));
        }
    }

    Output

    Output: [90, 80, 70, 60]

    Explanation of Java 8 Program

    The following statement calculates the sum of all elements:

    int sum = Arrays.stream(arr).sum();

    For the given array:

    {10, 20, 30, 40}

    the sum is 100.

    The map() method then subtracts each element from the total:

    .map(n -> sum - n)

    Here, n -> is a Java 8 lambda expression.

    The resulting stream is converted back into an array using:

    .toArray();

    Finally, Arrays.toString() displays the result.


    Comparison of Both Methods

    FeatureTraditional JavaJava 8
    Approachfor loopStream API
    Lambda expressionNoYes
    Stream APINoYes
    Easy for beginnersYesModerate
    Code lengthLongerShorter
    Java VersionAll common versionsJava 8+

    Which Method Should You Use?

    • For beginners: Use the for loop method because it clearly explains the logic.
    • For Java 8 learning: Use the Stream API version.
    • For interviews: Understand both approaches and the time complexity.

    Time Complexity

    Both approaches take O(n) time because the array needs to be processed.

    The traditional approach uses an additional result array, so the extra space complexity is O(n).

    Conclusion

    This Java program demonstrates how to replace every array element with the sum of all other elements. The traditional for loop approach is easy to understand, while the Java 8 Stream API provides a concise functional programming solution.

  • Java Program to Remove White Spaces from a String

    In this Java program, we will learn how to remove white spaces from a String using three different approaches:

    1. Using Loop (Manual Method)
    2. Using replaceAll() Method
    3. Using Java 8 Stream API

    For example:

    Input  : Java Programming Language
    Output : JavaProgrammingLanguage

    1. Traditional Java Program (Using Loop)

    In this approach, we manually check each character and remove spaces and tabs.

    import java.util.Scanner;
    
    public class RemoveWhiteSpace {
        public static void main(String[] args) {
            System.out.print("Enter any string : ");
            Scanner sc = new Scanner(System.in);
            String str = sc.nextLine();
            char[] c = str.toCharArray();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < c.length; i++) {
                if ((c[i] != ' ') && (c[i] != '\t')) {
                    sb.append(c[i]);
                }
            }
            System.out.println(sb);
            sc.close();
        }
    }

    Explanation (Loop Method)

    • The string is converted into a character array using toCharArray().
    • Each character is checked one by one.
    • If the character is not a space or tab, it is added to StringBuffer.
    • Finally, the result is printed without spaces.

    👉 This method is useful for beginners to understand character-level processing.


    2. Using replaceAll() Method

    This is the simplest and most commonly used approach.

    import java.util.Scanner;
    
    public class RemoveWhiteSpace {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a String: ");
            String str = sc.nextLine();
            String result = str.replaceAll("\\s", "");
            System.out.println("String without white spaces: " + result);
            sc.close();
        }
    }

    Explanation (replaceAll Method)

    • replaceAll("\\s", "") removes all whitespace characters.
    • \\s represents:
      • space
      • tab
      • newline
    • "" replaces them with nothing.

    👉 This is the shortest and most efficient traditional approach.


    3. Java 8 Program (Using Stream API)

    Java 8 provides a modern functional approach using Streams.

    import java.util.Scanner;
    import java.util.stream.Collectors;
    
    public class RemoveWhiteSpaceJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a String: ");
            String str = sc.nextLine();
            String result = str.chars()
                    .filter(c -> !Character.isWhitespace(c))
                    .mapToObj(c -> String.valueOf((char) c))
                    .collect(Collectors.joining());
            System.out.println("String without white spaces: " + result);
            sc.close();
        }
    }

    Explanation (Java 8 Stream Method)

    • str.chars() → converts string into stream of characters
    • filter(c -> !Character.isWhitespace(c)) → removes all whitespace characters
    • mapToObj() → converts int values back to characters
    • Collectors.joining() → combines all characters into final string

    👉 This method is useful for learning functional programming in Java.


    Comparison of All Three Methods

    FeatureLoop MethodreplaceAll()Java 8 Stream
    ApproachManualBuilt-in methodFunctional
    DifficultyEasyVery EasyModerate
    PerformanceGoodBestGood
    Code LengthLongShortMedium
    Best ForBeginners learning logicReal-world useJava 8 learning

    Conclusion

    Removing white spaces from a String is a common Java programming task. We learned three different ways:

    • Manual loop method for understanding logic
    • replaceAll() for simple and fast solution
    • Java 8 Stream API for modern functional programming

    Each method has its own importance depending on learning level and use case.

  • Java Program to Check Prime Number

    In this Java program, we will learn how to check whether a given number is a prime number using both the traditional Java approach and Java 8 features.

    What is a Prime Number?

    A prime number is a number greater than 1 that has only two factors: 1 and itself.

    Examples of prime numbers are:

    2, 3, 5, 7, 11, 13, 17, 19

    For example, 7 is a prime number because it can only be divided evenly by 1 and 7.

    1. Traditional Java Program

    import java.util.Scanner;
    
    public class PrimeNumber {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            boolean isPrime = true;
            if (number <= 1) {
                isPrime = false;
            } else {
                for (int i = 2; i <= number / 2; i++) {
                    if (number % i == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
            if (isPrime) {
                System.out.println(number + " is a Prime Number");
            } else {
                System.out.println(number + " is not a Prime Number");
            }
            sc.close();
        }
    }

    Output

    Enter a number: 17
    17 is a Prime Number

    Explanation

    The program first takes a number from the user.

    A number less than or equal to 1 is not a prime number:

    if (number <= 1) {
        isPrime = false;
    }

    For numbers greater than 1, the for loop checks whether the number is divisible by any number between 2 and number / 2.

    if (number % i == 0)

    If the remainder is 0, the number has another factor and therefore is not prime.


    2. Java 8 Program to Check Prime Number

    Java 8 introduced the Stream API, which can be used to check whether a number is divisible by any value in a range.

    import java.util.Scanner;
    import java.util.stream.IntStream;
    
    public class PrimeNumberJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            boolean isPrime = number > 1 &&
                    IntStream.rangeClosed(2, number / 2)
                             .noneMatch(i -> number % i == 0);
            if (isPrime) {
                System.out.println(number + " is a Prime Number");
            } else {
                System.out.println(number + " is not a Prime Number");
            }
            sc.close();
        }
    }

    Output

    Enter a number: 13
    13 is a Prime Number

    Explanation of Java 8 Program

    The Java 8 version uses IntStream.rangeClosed() to generate numbers from 2 to number / 2.

    IntStream.rangeClosed(2, number / 2)

    The noneMatch() method checks whether none of the numbers divide the given number evenly:

    .noneMatch(i -> number % i == 0)

    Here, i -> is a lambda expression, which is one of the important features introduced in Java 8.

    If no divisor is found, noneMatch() returns true, meaning the number is prime.

    Difference Between Traditional Java and Java 8

    FeatureTraditional JavaJava 8
    Approachfor loopStream API
    Lambda expressionNoYes
    Stream APINoYes
    % operatorYesYes
    Beginner friendlyVery easyModerate
    Java VersionAll common versionsJava 8+

    Which Approach Should You Use?

    For beginners, the traditional for loop approach is recommended because it is easier to understand and debug.

    The Java 8 version is useful when learning the Stream API, lambda expressions, and functional programming.

    Conclusion

    Checking whether a number is prime is a common Java programming problem and interview question. The traditional approach uses a simple loop, while the Java 8 approach demonstrates how IntStream and noneMatch() can be used to solve the same problem.

  • Java Program to Swap Two Numbers Without Using a Third Variable

    In this Java program, we will learn how to swap two numbers without using a third or temporary variable.

    For example, if:

    a = 10
    b = 20

    After swapping:

    a = 20
    b = 10

    Java Program

    We can swap two numbers using arithmetic operators without requiring a third variable.

    import java.util.Scanner;
    
    public class SwapWithoutThirdVariable {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int a = sc.nextInt();
    
            System.out.print("Enter second number: ");
            int b = sc.nextInt();
    
            System.out.println("Before Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
    
            a = a + b;
            b = a - b;
            a = a - b;
    
            System.out.println("After Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            sc.close();
        }
    }

    Output

    Enter first number: 10
    Enter second number: 20
    
    Before Swapping:
    a = 10
    b = 20
    
    After Swapping:
    a = 20
    b = 10

    Explanation

    The swapping is performed using three arithmetic operations:

    a = a + b;
    b = a - b;
    a = a - b;

    Suppose:

    a = 10
    b = 20

    The first statement adds both values:

    a = 10 + 20 = 30

    Now:

    a = 30
    b = 20

    The second statement calculates the original value of a:

    b = 30 - 20 = 10

    Now:

    a = 30
    b = 10

    Finally, the third statement calculates the original value of b:

    a = 30 - 10 = 20

    Therefore:

    a = 20
    b = 10

    The two values have been successfully swapped without using a third variable.

    Alternative Method Using XOR

    For integer values, two numbers can also be swapped without a third variable using the XOR (^) operator:

    a = a ^ b;
    b = a ^ b;
    a = a ^ b;

    However, the addition/subtraction approach is generally easier for beginners to understand.

    Important Note

    The addition/subtraction method can cause integer overflow if a + b exceeds the range of the int data type. For production code, using a temporary variable is usually clearer and safer.

    Key Points

    • No third or temporary variable is used.
    • The values are swapped using arithmetic operations.
    • The program works with Java 8 and later versions.
    • XOR can also be used as an alternative for integer values.

    Conclusion

    Swapping two numbers without a third variable is a common Java programming interview question. The addition and subtraction method provides a simple way to exchange two integer values without using an additional variable.

  • Java Program to Swap Two Numbers

    In this Java program, we will learn how to swap two numbers. Swapping means exchanging the values of two variables.

    For example, if:

    a = 10
    b = 20

    After swapping:

    a = 20
    b = 10

    1. Normal Java Program Using a Temporary Variable

    import java.util.Scanner;
    
    public class SwapTwoNumbers {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int a = sc.nextInt();
            System.out.print("Enter second number: ");
            int b = sc.nextInt();
            System.out.println("Before Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            int temp = a;
            a = b;
            b = temp;
            System.out.println("After Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            sc.close();
        }
    }

    Output

    Enter first number: 10
    Enter second number: 20
    
    Before Swapping:
    a = 10
    b = 20
    
    After Swapping:
    a = 20
    b = 10

    Explanation

    A temporary variable is used to store the value of the first number:

    int temp = a;

    Then the value of b is assigned to a:

    a = b;

    Finally, the value stored in temp is assigned to b:

    b = temp;

    This exchanges the values of a and b.

    Swapping Process

    temp = a
    a = b
    b = temp

    2. Java 8 Program to Swap Two Numbers

    Java 8 does not provide a special swapping feature for primitive variables. The simplest approach is still to use a temporary variable.

    We can, however, demonstrate the operation using a Java 8 lambda expression:

    import java.util.Scanner;
    import java.util.function.BiFunction;
    
    public class SwapTwoNumbersJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter first number: ");
            int a = sc.nextInt();
    
            System.out.print("Enter second number: ");
            int b = sc.nextInt();
    
            System.out.println("Before Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
    
            BiFunction<Integer, Integer, int[]> swap =
                    (x, y) -> new int[]{y, x};
    
            int[] result = swap.apply(a, b);
    
            a = result[0];
            b = result[1];
    
            System.out.println("After Swapping:");
            System.out.println("a = " + a);
            System.out.println("b = " + b);
    
            sc.close();
        }
    }

    Output

    Enter first number: 10
    Enter second number: 20
    
    Before Swapping:
    a = 10
    b = 20
    
    After Swapping:
    a = 20
    b = 10

    Explanation of Java 8 Program

    The Java 8 version uses the BiFunction functional interface:

    BiFunction<Integer, Integer, int[]>

    The lambda expression receives two numbers and returns them in reverse order:

    (x, y) -> new int[]{y, x}

    The apply() method executes the lambda expression:

    int[] result = swap.apply(a, b);

    The returned values are then assigned back to a and b.

    Difference Between Normal Java and Java 8

    FeatureNormal JavaJava 8
    ApproachTemporary variableLambda + BiFunction
    Easy to understandYesModerate
    Extra objectNoint[]
    Java 8 featureNoLambda expression
    RecommendedYesFor learning Java 8

    Conclusion

    The temporary variable approach is the simplest and most recommended way to swap two numbers in Java. The Java 8 version demonstrates how a lambda expression and BiFunction can be used to perform the same operation.

    For beginners, understanding the traditional approach first is important before moving to Java 8 functional programming.

  • Java Program to Find Factorial of a Number

    In this Java program, we will learn how to find the factorial of a number using a simple for loop. We will also see a Java 8 version using a lambda expression.

    What is Factorial?

    The factorial of a positive integer n is the product of all positive integers from 1 to n.

    For example:

    5! = 5 × 4 × 3 × 2 × 1
    5! = 120

    1. Normal Java Program

    import java.util.Scanner;
    
    public class Factorial {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            long factorial = 1;
            for (int i = 1; i <= number; i++) {
                factorial = factorial * i;
            }
            System.out.println("Factorial of " + number + " = " + factorial);
            sc.close();
        }
    }

    Output

    Enter a number: 5
    Factorial of 5 = 120

    Explanation

    The program first accepts a number from the user.

    int number = sc.nextInt();

    The factorial variable is initialized with 1:

    long factorial = 1;

    A for loop is then used to multiply all numbers from 1 to the given number:

    for (int i = 1; i <= number; i++) {
        factorial = factorial * i;
    }

    For example, when the input is 5:

    1 × 2 × 3 × 4 × 5 = 120

    2. Java 8 Program to Find Factorial

    Java 8 introduced lambda expressions and functional interfaces. We can use them to create a simple factorial function.

    import java.util.Scanner;
    import java.util.function.Function;
    
    public class FactorialJava8 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter a number: ");
            int number = sc.nextInt();
            Function<Integer, Long> factorial =
                    n -> {
                        long result = 1;
                        for (int i = 1; i <= n; i++) {
                            result = result * i;
                        }
                        return result;
                    };
            System.out.println("Factorial of " + number + " = "
                    + factorial.apply(number));
            sc.close();
        }
    }

    Output

    Enter a number: 6
    Factorial of 6 = 720

    Explanation of Java 8 Program

    The Java 8 program uses the Function functional interface:

    Function<Integer, Long>

    The lambda expression defines the factorial calculation:

    n -> {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result = result * i;
        }
        return result;
    }

    The factorial function is executed using:

    factorial.apply(number)

    Difference Between Normal Java and Java 8

    FeatureNormal JavaJava 8
    Approachfor loopLambda + Function
    LoopYesYes
    Lambda expressionNoYes
    Functional interfaceNoYes
    Beginner friendlyVery easyModerate
    Java VersionAll common versionsJava 8+

    Important Note

    For a simple factorial problem, the normal for loop is recommended. Java 8 does not mean every program needs Streams or Lambda expressions. The Java 8 version is mainly useful for learning functional programming features.

    Conclusion

    The factorial of a number can be calculated easily using a for loop. The traditional Java approach is simple and beginner-friendly, while the Java 8 approach demonstrates how lambda expressions and functional interfaces can be used in Java.