Core Java Programs with Answers and Outputs
Summary:
In this comprehensive Java programming compilation, various applications and concepts are explored. Firstly, a program is designed to add two times in HH:MM:SS format, showcasing static method usage. Next, the bubble sort algorithm is implemented for sorting integers. A prime number generator generates prime numbers within a user-defined range. The stack data structure is then implemented using an array, supporting push, pop, and traversal operations. Another program performs a binary search on an array of integers to find a specific value. Palindrome checking is demonstrated for user-inputted strings.
A math package is also created with an abstract ‘Shape’ class containing area and perimeter methods, and subclasses ‘Circle,’ ‘Triangle,’ and ‘Rectangle’ that extend ‘Shape,’ exemplifying package usage. Runtime polymorphism is illustrated via inheritance and method overriding. Object counting is showcased by tracking the number of objects created in a program. The average of the largest and smallest numbers in an integer array is calculated using arrays. Lastly, handling exceptions is demonstrated, including dealing with NullPointerException
through a singleton class and addressing ArrayIndexOutOfBoundsException
when accessing elements outside an array’s bounds.
These Java programs cover fundamental programming concepts, including object-oriented principles, data structures, sorting algorithms, and exception handling. Whether it’s performing mathematical operations on shapes, sorting data efficiently, or ensuring robust error handling, these programs exemplify essential Java programming skills and techniques.
Excerpt:
Core Java Programs with Answers and Outputs
1. Write a Java program to accept two Time from the user in HH:MM:SS
format and perform the Addition of Two given Time and Print the Result in
HH:MM:SS format using static Method.
import java.util.*;
class time
{
int hour,min,sec;
time addtime(time tt1, time tt2)
{
time ttt= new time();
ttt.sec=tt1.sec+tt2.sec;
ttt.min=ttt.sec/60;
ttt.sec=ttt.sec%60;
ttt.min=tt1.min+tt2.min+ttt.min;
ttt.hour=ttt.min/60;
ttt.min=ttt.min%60;
ttt.hour=tt1.hour+tt2.hour+ttt.hour;
System.out.println(“After addition time is :”);
System.out.println(ttt.hour +”:” +ttt.min +”:”+ttt.sec);
return(ttt);
}
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
time t1=new time();
time t2=new time();
System.out.println(“Enter first time in HH:MM:SS format”);
t1.hour=sc.nextInt();
t1.min=sc.nextInt();
t1.sec=sc.nextInt();
System.out.println(“Enter second time in HH:MM:SS format”);
t2.hour=sc.nextInt();
t2.min=sc.nextInt();
t2.sec=sc.nextInt();
t1.addtime(t1,t2);
}
}
Reviews