Basic Programs
1. Program to Accept values of Two Numbers and print their Addition.
import [Link];
class AddNumbers
{
public static void main(String args[])
{
int x, y, z;
[Link]("Enter two integers to calculate their sum : ");
Scanner in = new Scanner([Link]);
x = [Link]();
y = [Link]();
z = x + y;
[Link]("Sum of entered integers = " + z);
}
}
2. Program to Accept value of Radius and Calculate Area of Circle.
class CircleArea
{
public static void main(String[] args)
{
int radius = 3;
[Link]("The radius of the circle is " + radius);
// NOTE : use [Link] constant to get value of pi
double area = [Link] * radius * radius;
[Link]("Area of a circle is " + area);
}
}
3. Program to Find Simple Interest and Compound Interest.
import [Link].*;
import [Link];
class CalculateInterest
{
public static void main(String[] args)
{
double p, n, r, si, ci;
Scanner s = new Scanner([Link]);
[Link]("Enter the amount : ");
p = [Link]();
[Link]("Enter the [Link] years : ");
n = [Link]();
[Link]("Enter the Rate of interest : ");
r = [Link]();
si = (p * n * r) / 100;
ci = p * [Link](1.0 + r / 100.0, n) - p;
[Link]("\nAmount : " + p);
[Link]("No. of years : " + n);
[Link]("Rate of interest : " + r);
[Link]("Simple Interest : " + si);
[Link]("Compound Interest : " + ci);
}
}
4. Program to Convert Celsius to Fahrenheit.
import [Link].*;
class CelsiustoFahrenheit
{
public static void main(String[] args)
{
double temperature;
Scanner in = new Scanner([Link]);
[Link]("Enter temperature in Celsius");
temperature = [Link]();
temperature = (temperature * 9 / 5.0) + 32;
[Link]("Temperature in Fahrenheit = " + temperature);
}
}
5. Program to swap two numbers without using temporary variable.
public class Swapping
{
public static void main(String[] args)
{
int x = 100;
int y = 200;
//Swapping in steps
x = x + y; //x = 100 + 200 = 300
y = x - y; //y = 300 - 200 = 100
x = x - y; //x = 300 - 100 = 200
//Verify swapped values
[Link]("x = " + x + " and y = " + y);
}
}
6. Program to swap two numbers without using temporary variable.
public class Main
{
static int num1, num2, num3;
public static void main(String[] args)
{
num1 = 30; num2 = 60; num3 = 90;
[Link]("Before swapping: num1="+num1+",num2="+num2+",num3="+num3);
num1 = num1 + num2 + num3;
num2 = num1 - (num2 + num3);
num3 = num1 - (num2 + num3);
num1 = num1 - (num2 + num3);
[Link]("After swapping: num1="+num1+",num2="+num2+",num3="+num3);
}
}