
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to calculate distance light travels
In this article, we will demonstrate how to calculate the distance light travels in one year using Java. We will use the Demo class and the main method to perform this calculation.
Speed of light: 186000
Days = 365
dist = speed * seconds
Problem Statement
Write a Java program to calculate the total distance that light travels in a year, given that the speed of light is 186,000 miles per second.
Output
Light travels: 5865696000000 miles
Steps to calculate distance light travels
Following are the steps to calculate the distance light travels ?
- Initialize the Demo class.
- Define the speed of light in miles per second in the main() method.
- Calculate the total number of seconds in a year.
- Multiply the speed of light by the total time in seconds to find the distance.
- Print the distance.
Java program to calculate distance light travels
The following is the complete example to calculate the distance light travels ?
public class Demo { public static void main(String[] args) { int speed; long days, seconds, dist; speed = 186000; days = 365; seconds = days * 24 * 60 * 60; dist = speed * seconds; System.out.print("Light travels: "+dist + " miles"); } }
Output
Light travels: 5865696000000 miles
Code Explanation
To calculate the distance light travels, we need to follow the basic formulae to calculate distance.
Distance = Speed x Time
Here, the following are the parameters ?
speed = 186000; days = 365; seconds = days * 24 * 60 * 60;
Above, we calculated the time in seconds for a year ?
days = 365; seconds = days * 24 * 60 * 60;
In this program, we use the Demo class as the main method to calculate the distance light travels. First, we define the speed of light as 186,000 miles per second. We then calculate the total number of seconds in a year. Finally, we multiply the speed of light by the total seconds to get the distance light travels in a year, which is printed using the System.out.print() method.