Sure! Here's each Java program rewritten using static inputs (i.e.
, inputs are hardcoded in
the program), along with printed output examples as comments.
---
✅ 1. Pattern Printing
public class PatternPrinter {
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
/* Output:
*****
****
***
**
*
*/
---
✅ 2. Sort Array in Ascending or Descending Order
import java.util.Arrays;
public class ArraySorter {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 3};
String order = "desc"; // Change to "asc" or "desc"
if (order.equals("asc")) {
Arrays.sort(arr);
} else if (order.equals("desc")) {
Arrays.sort(arr);
// reverse
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
System.out.println("Sorted Array (" + order + "): " + Arrays.toString(arr));
}
}
/* Output (for "desc"):
Sorted Array (desc): [8, 5, 3, 2, 1]
Output (for "asc"):
Sorted Array (asc): [1, 2, 3, 5, 8]
*/
---
✅ 3. Declare a Class and Access Members Using Object
class Student {
String name = "Tina";
int age = 21;
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class ClassObjectExample {
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}
/* Output:
Name: Tina
Age: 21
*/
---
✅ 4. Implement this Keyword
class Employee {
String name;
int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
void showDetails() {
System.out.println("Name: " + this.name);
System.out.println("ID: " + this.id);
}
}
public class ThisKeywordDemo {
public static void main(String[] args) {
Employee e1 = new Employee("Raj", 1001);
e1.showDetails();
}
}
/* Output:
Name: Raj
ID: 1001
*/
---
✅ 5. Method Overloading Example
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class MethodOverloading {
public static void main(String[] args) {
Calculator calc = new Calculator();
int sum1 = calc.add(10, 20);
double sum2 = calc.add(5.5, 4.5);
int sum3 = calc.add(1, 2, 3);
System.out.println("Sum of two ints: " + sum1);
System.out.println("Sum of two doubles: " + sum2);
System.out.println("Sum of three ints: " + sum3);
}
}
/* Output:
Sum of two ints: 30
Sum of two doubles: 10.0
Sum of three ints: 6
*/
---
Let me know if you want a combined version of all programs or need them exported to a
.java file.