In Java, we can convert an integer type variable to a String using the Integer.toString() method.
This method takes an integer as an argument and returns its equivalent String representation.
Here is an example program to demonstrate this:
public class IntToString {
public static void main(String[] args) {
int num = 123;
String str = Integer.toString(num);
System.out.println("String value: " + str);
}
}The output of the above program will be:
String value: 123
Calculating the Sum of Natural Numbers in Java
To calculate the sum of natural numbers, we can use a simple for loop and keep adding the numbers until the desired sum is obtained.
Here is an example program to demonstrate this:
public class SumOfNaturalNumbers {
public static void main(String[] args) {
int num = 10;
int sum = 0;
for (int i = 1; i <= num; i++) {
sum += i;
}
System.out.println("Sum of first " + num + " natural numbers is: " + sum);
}
}The output of the above program will be:
Sum of first 10 natural numbers is: 55
Conclusion
Converting int type variables to String and calculating the sum of natural numbers are two common tasks that Java programmers frequently encounter.
By using the Integer.toString() method and a simple for loop, respectively, we can easily perform these tasks.




