# Java Programming | Mass conversion

Introduction

This is a tutorial for conversion of mass in java. The program converts the mass from one unit to other and prints it. The program is extendable. Go enjoy the program. Lets begin………

Program for mass conversion from kg to gram in java.

``````
//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class MassConversion {
//void main
public static void main (String[] args)
{
//declare float
float to,from;
//print message
System.out.println("Enter Mass in kilogram:");
//Take input
Scanner input = new Scanner(System.in);
//calculate
from = input.nextFloat();
to = from*1000;
//print the average
System.out.println("Mass in gram = "+to);
}
}
``````

Output

Enter Mass in kilogram:
1.254
Mass in gram = 1254.0

How it works

1. The program prints the message to enter mass.
2. The user enters mass.
3. Mass is converted.
4. The converted mass is printed.

Extending it

The Program can be extended by adding more unit to conversion and by adding their Conversion formula for other unit and more variables can be added to program to convert multiple masses. Like wise you can also use following unit for conversion :-

• Milligram
• Gram
• Kilogram
• Tonne
• Ton(UK)
• Tons(US)
• Grain
• Ounce
• Pound
• Stone

Explanation.

1. Import the Scanner.
2. Declare the class as public
3. Add the void main function
4. Add system.out.println() function with the message to enter mass.
5. Declare input as Scanner.
6. Take the mass and save it in variable.
7. Convert mass and save it in other variable.
8. Add system.out.println() function to print the converted mass.

At the end.

You learnt creating the Java program for Mass conversion. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: