Java Programs for Beginners (Without If-Else and Loops)
1. Swap Two Numbers Without a Third Variable
class SwapNumbers {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("Before Swap: a = " + a + ", b = " + b);
a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
2. Find the Cube of a Number Using a Method
class CubeCalculator {
int cube(int num) {
return num * num * num;
}
public static void main(String[] args) {
CubeCalculator obj = new CubeCalculator();
int result = obj.cube(5);
System.out.println("Cube of 5 is: " + result);
}
}
3. Concatenate Two Strings Using Method
class Concatenate {
String join(String a, String b) {
return a + b;
}
public static void main(String[] args) {
Concatenate c = new Concatenate();
String result = c.join("Hello", "World");
System.out.println("Concatenated String: " + result);
}
}
4. Calculate Area of a Rectangle Using a Class
class Rectangle {
int length = 7;
int breadth = 4;
Java Programs for Beginners (Without If-Else and Loops)
int area() {
return length * breadth;
}
public static void main(String[] args) {
Rectangle r = new Rectangle();
System.out.println("Area of Rectangle: " + r.area());
}
}
5. Calculate Simple Interest (No if/loop)
class Interest {
double principal = 10000;
double rate = 5;
double time = 2;
double simpleInterest() {
return (principal * rate * time) / 100;
}
public static void main(String[] args) {
Interest i = new Interest();
System.out.println("Simple Interest: " + i.simpleInterest());
}
}
6. Add Two Complex Numbers Using a Class
class Complex {
int real;
int imag;
Complex(int r, int i) {
real = r;
imag = i;
}
Complex add(Complex c) {
return new Complex(real + c.real, imag + c.imag);
}
void display() {
System.out.println(real + " + " + imag + "i");
}
public static void main(String[] args) {
Complex c1 = new Complex(3, 4);
Java Programs for Beginners (Without If-Else and Loops)
Complex c2 = new Complex(5, 6);
Complex result = c1.add(c2);
System.out.print("Sum of Complex Numbers: ");
result.display();
}
}