0% found this document useful (0 votes)
15 views3 pages

Java Programs: Factorial, Sorting, Palindrome

The document contains three Java programs: the first demonstrates the creation of a class and objects by calculating the factorial of a number, the second sorts a list of names in ascending order, and the third calculates the sum of the digits of a number while checking if it is a palindrome. Each program includes user input and output functionality. The code snippets illustrate fundamental programming concepts in Java.

Uploaded by

Janki Sharan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Java Programs: Factorial, Sorting, Palindrome

The document contains three Java programs: the first demonstrates the creation of a class and objects by calculating the factorial of a number, the second sorts a list of names in ascending order, and the third calculates the sum of the digits of a number while checking if it is a palindrome. Each program includes user input and output functionality. The code snippets illustrate fundamental programming concepts in Java.

Uploaded by

Janki Sharan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dt.

04-09-2024

1. Demonstration of Creation of Class, Objects

class Main {

int factorial(int a) {
int i, fact = 1;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
return fact;
}
public static void main(String args[]) {
int a, fact;
Scanner sc = new Scanner([Link]);
[Link]("Enter a number:");
a = [Link]();
Main ff = new Main();
fact = [Link](a);
[Link]("Factorial of "+a+" is:" + fact);
}
}

2. Write a Java program for sorting a given list of names in ascending order
import [Link].*;
class Sorting
{
void sortStrings()
{
Scanner s = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
String[] str = new String[n];
[Link]("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String([Link]());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
[Link]("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
[Link](str[i]);
}
}
}
class Sort
{
public static void main(String[] args)
{
Sorting obj = new Sorting();
[Link]();
}
}

[Link] a java program to print sum of Sum of Digits and check for
palindrome.
import [Link].*;
class sod_pal
{
public static void main(String args[])
{
int n,rev=0, t,res,sum=0;
Scanner s= new Scanner([Link]);
[Link]("Please Enter No. = ");
n=[Link]();
t=n;
[Link]("Sum of digits of a number" +n+ "is = ");
while(n>0)
{
res=n%10;
rev = rev *10 + res;
n=n/10;
sum=sum+res;
}
[Link](+sum);
if(rev==t)
[Link]("Given number is a palindrome");
else
[Link]("Given number is not a palindrome");

}
}

Common questions

Powered by AI

The programs demonstrate basic use of classes and methods but lack comprehensive use of object-oriented features like inheritance, polymorphism, and encapsulation. They don't showcase data abstraction or encapsulation, as all operations occur within a single class without modifiers, risking accidental data manipulation. To overcome these limitations, access modifiers can be used to protect critical data, and inheritance can be introduced for shared functionality. For example, defining abstract classes or interfaces can standardize methods like 'compute()', promoting polymorphism and reducing redundancy in different program modules .

The program detects a palindrome by reversing the number and comparing it to the original. Within the main method of the sod_pal class, it continually extracts the last digit of the number and appends it to a reversed version 'rev' while dividing the number by 10. After obtaining the reversed number, it compares this value ('rev') to the original number ('t'). If they match, the program prints 'Given number is a palindrome'; otherwise, it prints 'Given number is not a palindrome' .

The program uses the Scanner class to handle input, assuming the input will always be valid integers for numbers or valid strings for names. However, it doesn't handle potential input errors like non-integers or empty strings. To improve robustness, input validation could be added; for instance, using try-catch blocks to manage exceptions arising from invalid input types and prompting the user to re-enter data when errors occur. Additionally, the program could include checks for empty inputs or null values to avoid exceptions and provide a better user experience .

The program sorts a list of names in ascending order using a nested loop approach with the compareTo() method for string comparison. Within the Sorting class, the sortStrings() method reads an integer 'n' for the number of names and a string array 'str' to store the names. It then employs two nested for-loops to iterate over the array, using compareTo() to compare and swap elements if they are out of order. This implements a basic form of the bubble sort algorithm. The sorted names are subsequently printed to the console .

The program calculates the sum of digits by initializing a 'sum' variable to zero and repeatedly extracting the last digit by using modulo operation (n % 10), adding it to 'sum', and removing the last digit by dividing the number by 10. This loop continues until the number reduces to zero. The sum is printed as 'Sum of digits of a number is =' before determining whether the number is a palindrome, which is done independently by checking if the reversed number (rev) matches the original (t).

Both programs utilize classes but could further apply object-oriented principles like encapsulation and modularity. Enhancing modularity could involve defining separate classes for input handling, computation, and output generation. Methods responsible for distinct tasks can be neatly encapsulated within their classes, limiting their scope and increasing maintainability. Applying inheritance or interfaces can provide more flexible and reusable code structures. For example, creating a separate utility class for common operations like input validations or array handling would isolate these concerns and facilitate easier updates or modifications .

The Java program calculates the factorial of a given number by creating a method factorial(int a) within the Main class. The method initializes a variable 'fact' to 1 and uses a for-loop to iterate from 1 to 'a', multiplying 'fact' by the loop index 'i' on each iteration, effectively computing the factorial. The main() function prompts the user to enter a number, reads the input using a Scanner object, and calls the factorial method on the input. The calculated factorial is then printed to the console .

Extending these programs for more complex data operations, such as handling large datasets or multi-threaded processes, may challenge current structures due to lack of scalability and weak modularization. Current sequential execution models won't efficiently handle parallel processing. To address these, adding modular designs using classes and interfaces can improve readability and maintainability. Implementing multi-threading for concurrent processing can enhance performance. Additionally, utilizing libraries such as Java Streams for higher abstraction levels in data handling and transformation can help manage complex data operations more efficiently .

The current sorting uses a basic bubble sort algorithm, which is not optimal for larger datasets due to its O(n^2) time complexity. To improve efficiency, a more advanced sorting algorithm like quicksort or mergesort could be implemented, both offering better average and worst-case performance at O(n log n). For adaptability, the sorting could be generalized to sort objects by different attributes besides strings by implementing Comparator interfaces, allowing sorting flexibility depending on specific needs .

The program handles input operations using the Scanner class from java.util package to read user input from the console. For factorial calculation, the program prompts the user with 'Enter a number:' and reads an integer with sc.nextInt(). For sorting strings, it similarly prompts with 'Enter the value of n:', reads the integer, and then reads 'n' strings into an array using a loop with s.next(). Output operations are managed using System.out.println(), displaying the calculated factorial or sorted strings to the console in each respective program .

You might also like