Java Sum and Product of Array Elements Example
This Snippet is coded by a user inOnline java Compiler. You can see and run this code too.
زبان: Java
This Java code demonstrates a simple class named MyClass that contains two static methods: sum and multiple. The sum method calculates the sum of all integers in an array, while the multiple method calculates their product. In the main method, an array of integers from 1 to 9 is created, and both methods are invoked.
How to use: Compile and run this Java program. The output will be the sum (45) and the product (362880) of the numbers 1 through 9. You can modify the array to test other values.
Key points:
- Static methods are called directly from the
mainmethod without creating an instance. - For-each loop simplifies array iteration.
- The
multiplemethod initializes the product to 1 to handle multiplication correctly.