Write a Java Program to Check if two strings are anagram

An anagram is a word or phrase formed by rearranging the letters of another word or phrase.

For example, the word “listen” can be rearranged to form the word “silent”.

In this Java program, we will write a method to check whether two given strings are anagrams or not.


Here is the Java code:

import java.util.Arrays;

public class AnagramChecker {

  public static boolean areAnagrams(String str1, String str2) {

    // Convert strings to character arrays
    char[] arr1 = str1.toCharArray();
    char[] arr2 = str2.toCharArray();

    // Sort character arrays
    Arrays.sort(arr1);
    Arrays.sort(arr2);

    // Compare sorted arrays
    return Arrays.equals(arr1, arr2);
  }

  public static void main(String[] args) {

    String str1 = "listen";
    String str2 = "silent";

    if (areAnagrams(str1, str2)) {
      System.out.println(str1 + " and " + str2 + " are anagrams.");
    } else {
      System.out.println(str1 + " and " + str2 + " are not anagrams.");
    }
  }
}

In the areAnagrams method, we first convert the given strings to character arrays using the toCharArray method.

We then sort the character arrays using the Arrays.sort method.

Finally, we compare the sorted arrays using the Arrays.equals method. If the two arrays are equal, we return true, indicating that the two strings are anagrams.

In the main method, we create two strings, str1 and str2, and call the areAnagrams method to check if they are anagrams or not.

Java Program to Calculate the Sum of Natural Numbers

In this Java program, we will write a method to calculate the sum of the first n natural numbers.

The natural numbers are the positive integers starting from 1.

Here is the Java code:

public class SumOfNaturalNumbers {

  public static int calculateSum(int n) {

    // Initialize sum to 0
    int sum = 0;

    // Add each natural number from 1 to n to the sum
    for (int i = 1; i <= n; i++) {
      sum += i;
    }

    return sum;
  }

  public static void main(String[] args) {

    int n = 10;
    int sum = calculateSum(n);

    System.out.println("The sum of the first " + n + " natural numbers is " + sum + ".");
  }
}

In the calculateSum method, we first initialize the sum to 0.

We then use a for loop to iterate from 1 to n, adding each natural number to the sum.

Finally, we return the sum.

In the main method, we create a variable n representing the number of natural numbers to sum, and call the calculateSum method to calculate the sum.

We then print the result using the println method.


Conclusion

In this tutorial, we have covered two Java programs.

The first program checks if two given strings are anagrams by sorting the character arrays and comparing them.

The second program calculates the sum of the first n natural numbers using a for loop.

These are two fundamental programming concepts that are essential to any Java programmer’s skill set.