1. //Write a Java program to Add two Numbers.
Source Code:
public class Addition {
public static void main(String[] args) {
// declare variables
int num1, num2, sum;
// take two numbers
num1 = 10;
num2 = 20;
// calculate sum value
sum = num1 + num2;
// display the sum value
System.out.println("Sum = " + sum);
}
}
2. //Find ASCII value of a character
Source Code:
public class AsciiValue {
public static void main(String[] args) {
char ch = 'a';
int ascii = ch;
// You can also cast char to int
int castAscii = (int) ch;
System.out.println("The ASCII value of " + ch + " is: " + ascii);
System.out.println("The ASCII value of " + ch + " is: " + castAscii);
}
}
3. // Java Program to Demonstrate Primitive Data Types
class DataType {
// Main driver method
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
// use byte and short
// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value
// is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
// need to hold big range of numbers then we need
// this data type
long l = 12121;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}
Output:
C:\Users\Dell>E:
E:\>cd JavaPrograms
E:\JavaPrograms>javac DataType.java
E:\JavaPrograms>java DataType.java
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
E:\JavaPrograms>
4. // Write a Java Program to find Average
Source Code:
public class Average {
public static void main(String[] args) {
// take two numbers
double num1 = 10;
double num2 = 20;
// declare sum variable
// and initialize with 0
double sum = 0.0;
// declare average variable
double avg = 0.0;
// calculate the sum value
sum = num1 + num2;
// calculate the average value
avg = sum/2;
// display result
System.out.println("Average: " + avg );
}
}
5. //Write a Java program to swap two numbers.
class Swap
{
public static void main(String[] args)
{
int a = 5;
int b = 10;
int temp;
System.out.println("Before swapping, a: "+a+" b: "+b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping, a: "+a+" b: "+b);
}
}
6. //Program to swap two numbers without using third variable.
class SwapNumber
{
public static void main(String[] args)
{
int a = 15;
int b = 17;
System.out.println("Before swapping a: "+a+", b: "+b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping a: "+a+", b: "+b);
}
}