
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Java Program to calculate Sum of squares of first n natural numbers
To calculate the sum of squares of first n natural numbers, the Java code is as follows −
Example
import java.io.*; import java.util.*; public class Demo{ public static int sum_of_squares(int val){ return (val * (val + 1) / 2) * (2 * val + 1) / 3; } public static void main(String[] args){ int val = 8; System.out.println("The sum of squares of first 8 natural numbers is "); System.out.println(sum_of_squares(val)); } }
Output
The sum of squares of first 8 natural numbers is 204
A class named Demo contains a function named ‘sum_of_squares’. This function is used to add up the first ‘n’ natural numbers. This returns the sum of the numbers. In the main function, a value for ‘n’ is defined and the function is called with this ‘n’ value. Relevant output is displayed on the console.
- Related Articles
- Sum of squares of first n natural numbers in C Program?
- Python Program for Sum of squares of first n natural numbers
- C++ Program for Sum of squares of first n natural numbers?
- Swift Program to Calculate Cube Sum of First n Natural Numbers
- Java Program to cube sum of first n natural numbers
- PHP program to calculate the sum of square of first n natural numbers
- Java Program to Display Numbers and Sum of First N Natural Numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- Java Program to Calculate the Sum of Natural Numbers
- Sum of first n natural numbers in C Program
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- Sum of squares of the first n even numbers in C Program
- C Program for cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers

Advertisements