Java Programs
Java Programs
Code:-
import java.util.Scanner;
scanner.close();
}
}
Output:-
2. Write a program to check if two strings are equals or not.
Code:-
import java.util.Scanner;
Output:-
3. Write a program to add two numbers.
Code:-
import java.util.Scanner;
scanner.close();
}
}
Output:-
4. Write a program to find out how many digits in given number.
Code:-
import java.util.Scanner;
// Input a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
}
}
Output:-
5. Write a program to check given no. is palindrome or not and
Armstrong or not.
Code:-
import java.util.Scanner;
// Input a number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
}
scanner.close();
}
}
Output:-
7. Write a program to find out factorial of given number with
and without recursion method.
Code:-
import java.util.Scanner;
scanner.close();
}
// Non-Recursive method to calculate factorial
public static long factorialNonRecursive(int num) {
long factorial = 1;
return factorial;
}
// Display results
System.out.println("Number of characters (excluding
spaces): " + characterCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of sentences: " +
sentenceCount);
scanner.close();
}
}
Output:-
scanner.close();
}
}
Output:-
10. Write a program to find season of month.
Code:-
import java.util.Scanner;
switch (month) {
case 1: case 2: case 12:
season = "Winter";
break;
case 3: case 4: case 5:
season = "Spring";
break;
case 6: case 7: case 8:
season = "Summer";
break;
case 9: case 10: case 11:
season = "Fall (Autumn)";
break;
default:
season = "Invalid month number! Please enter a
number between 1 and 12.";
}
scanner.close();
}
}
Output:-
11. Write a program using Human as a class and derive its
members and methods.
Code:-
// Base class
class Human {
// Member variables
String name;
int age;
// Constructor
public Human(String name, int age) {
this.name = name;
this.age = age;
}
// Constructor
public Student(String name, int age, String school) {
super(name, age); // Call to base class constructor
this.school = school;
}
// Constructor
public Employee(String name, int age, String company) {
super(name, age); // Call to base class constructor
this.company = company;
}
System.out.println("\nEmployee Info:");
employee.displayInfo();
}
}
Output:-
12. Write a program to display following pattern_
*
**
***
****
*****
****
***
**
*
Code:-
public class Pattern {
public static void main(String[] args) {
int n = 5; // The middle width of the pattern (largest row)
Output:-
13. Write a program to swap two variables using third variable
and swap two variables without using third variable.
Code:-
import java.util.Scanner;
scanner.close();
}
}
Output:-