Sum in Java
javaprogram
In Java, there are different ways to do this in Java depending on what the input type happens to be (e.g., integers, arrays, etc.). Here's four examples:
1. Sum of Two Integers
public class Main {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
3. Sum of Two Floating Point Numbers:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of array: " + sum);
}
3. Sum of Two Floating Point Numbers:
public class Main {
public static void main(String[] args) {
double num1 = 5.5;
double num2 = 10.2;
double sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
4. Sum of Numbers Using Java Streams (Java 8+):
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = IntStream.of(numbers).sum();
System.out.println("Sum using streams: " + sum);
}
}
These are some simple ways to calculate the sum in Java. Let me know if you need a specific implementation!