Challenging Java programs and succeeding in coding interviews-7

In “Challenging Java programs and succeeding in coding interviews part-7”, we solve some problems such as swapping, reversing, finding square roots, removing white spaces etc.

Write a Java Program to swap two numbers without using the third variable.

What is a swap?

In programming, a swap refers to the exchange of the values of two variables.
This can be done using a temporary variable to hold one of the values while the swap is being performed.

import java.util.Scanner;

public class javatechypid {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();

        System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);

        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);
    }
}

Output:

Enter first number: 5
Enter second number: 10
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5

Explanation Of Above Java Code:

The above Java program swaps the values of two variables using a mathematical approach, without using a third variable.

The program swaps the values of “num1” and “num2” using a mathematical approach without using a third variable. First, the value of “num1” is updated to be the sum of “num1” and “num2”. Then, the value of “num2” is updated to be the difference between the new value of “num1” and the original value of “num2”. Finally, the value of “num1” is updated to be the difference between the new value of “num1” and the new value of “num2”. This effectively swaps the values of “num1” and “num2” without using a temporary variable.

Write a program to print a given number’s square root without using the Math.sqrt() function

public class javatechypid {

    public static void main(String[] args) {
        double number = 25;
        double squareRoot = squareRoot(number);
        System.out.println("The square root of " + number + " is " + squareRoot);
    }

    public static double squareRoot(double number) {
        double temp;
        double squareRoot = number / 2;

        do {
            temp = squareRoot;
            squareRoot = (temp + (number / temp)) / 2;
        } while ((temp - squareRoot) != 0);

        return squareRoot;
    }
}

Output:

The square root of 25.0 is 5.0

Explanation Of Above Java Code:

In this program, we have created a public class named javatechypid. We have declared a static method named squareRoot which takes a number as an input parameter and returns the square root of that number.

Inside the squareRoot method, we have initialized two variables temp and squareRoot. We have set the initial value of squareRoot to half of the input number. We have used a do-while loop to calculate the square root of the number.

Inside the do-while loop, we have assigned the value of squareRoot to temp. Then, we have calculated the new value of squareRoot using the formula squareRoot = (temp + (number / temp)) / 2. This formula calculates the average of temp and number/temp and assigns it to squareRoot. We have repeated this process until the difference between temp and squareRoot is zero.

In the main method, we have initialized a variable named number with the value 25. We have called the squareRoot method with the number variable as an input parameter and stored the result in a variable named squareRoot. Finally, we have printed the square root of the number.

Write a Java program to reverse the order of elements in a string

public class javatechypid {
    public static void main(String[] args) {
        String str = "Hello World!";
        String reversed = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }

        System.out.println("Original String: " + str);
        System.out.println("Reversed String: " + reversed);
    }
}

Output:

Original String: Hello World!
Reversed String: !dlroW olleH

Explanation Of Above Java Code:

In this program, we declare a string str and an empty string reversed. We then use a for loop to iterate through the characters of the string in reverse order, starting from the last character. Within the loop, we append each character to the reversed string. Finally, we print both the original and reversed strings to the console.

Write a Java program to reverse the order of digits in an integer

public class javatechypid {
    public static void main(String[] args) {
        int num = 12345;
        int reversed = 0;

        while (num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num /= 10;
        }

        System.out.println("Original Integer: 12345");
        System.out.println("Reversed Integer: " + reversed);
    }
}

Output:

Original Integer: 12345
Reversed Integer: 54321

Explanation Of Above Java Code:

The given program is written in Java and uses a while loop to reverse the order of digits in an integer.

A sample integer value of 12345 is assigned to the variable num.

A variable named reversed is initialized to 0.

Inside the while loop, the last digit of the input number is extracted using the modulus operator and stored in the digit variable.

The reversed variable is updated by multiplying its value by 10 and adding the value of digit variable to it.

The input number is updated by dividing it by 10 to remove the last digit.

The loop continues until the input number becomes 0.

Write a Java program to reverse the order of elements in a character array

public class JavaTechypid {
    public static void main(String[] args) {
        char[] arr = {'h', 'e', 'l', 'l', 'o'};
        int start = 0;
        int end = arr.length - 1;

        while (end > start) {
            char temp = arr[end];
            arr[end] = arr[start];
            arr[start] = temp;
            end--;
            start++;
        }

        System.out.println("Original Array: " + new String(arr));
    }
}

Output:

Original Array: olleh

Explanation Of Above Java Code:

Declaring a char array named “arr” with the values {‘h’, ‘e’, ‘l’, ‘l’, ‘o’}.

Two integer variables named “start” and “end” are declared and initialized. “start” is initialized to 0, which is the index of the first element of the array. “end” is initialized to the length of the array minus 1, which is the index of the last element of the array.

A while loop is used to swap the elements of the array in reverse order. The loop will continue as long as “end” is greater than “start”.

Inside the loop, the character at index “end” is stored in a temporary variable “temp”. The character at index “end” is then replaced with the character at index “start”, and the character at index “start” is replaced with “temp”. This effectively swaps the values of the two characters.

After swapping the characters, “end” is decremented by 1 and “start” is incremented by 1. This ensures that the loop will eventually terminate when “end” becomes less than or equal to “start”.

Java programs

Write a Java program to identify and remove all white spaces in a given string of characters

import java.util.Scanner;

public class JavaTechypid {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = input.nextLine();

        // Identify and remove all white spaces
        str = str.replaceAll("\\s", "");

        System.out.println("The string without white spaces is: " + str);
    }
}

Output:

Enter a string: Techy Pid
The string without white spaces is: TechyPid

Explanation Of Above Java Code:

The replaceAll() method is used to identify and remove all white spaces in the input string. The regular expression “\s” matches all white space characters, including spaces, tabs, and newlines. The method replaces all occurrences of white space characters with an empty string, effectively removing them from the string.

Java programs

Write a Java program to swap two numbers using a third variable

public class JavaTechypid {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int temp;

        System.out.println("Before Swapping: a = " + a + ", b = " + b);

        temp = a;
        a = b;
        b = temp;

        System.out.println("After Swapping: a = " + a + ", b = " + b);
    }
}

Output:

Before Swapping: a = 10, b = 20
After Swapping: a = 20, b = 10

Explanation Of Above Java Code:

Two integer variables “a” and “b” are declared and initialized with the values 10 and 20 respectively.

A third integer variable “temp” is declared to temporarily hold one of the values during the swapping process.

The values of “a” and “b” are printed to the console using the System.out.println() method.

The value of “a” is stored in “temp” and The value of “b” is assigned to “a”.

The value of “temp” (which is the original value of “a”) is assigned to “b”.

The values of “a” and “b” are printed to the console again to show that they have been swapped.

Leave a Reply