Java Interview Coding Examples
Java Interview Coding Examples
md 2024-05-28
if (num > 0)
[Link] ("The number is positive");
else if (num < 0)
[Link] ("The number is negative");
else
[Link] ("Zero");
}
}
// 0 is a positive number because if we represent 0 in terms of binary :
0000 0000
// in the above representation the Most Significant Bit (MSD - First bit)
is 0 which
// indicate a positive number
1 / 57
Java Interview Specific [Link] 2024-05-28
if (isEven (number))
[Link] ("Even");
else
[Link] ("Odd");
}
int n = 10;
int sum = 0;
//using formula
public class Main
{
public static void main (String[]args)
{
int n = 10;
[Link] (n*(n+1)/2);
}
}
2 / 57
Java Interview Specific [Link] 2024-05-28
int sum = 0;
//using formula
public class Main
{
public static void main(String[] args) {
int num1 = 2;
int num2 = 5;
int sum = num2*(num2+1)/2 - num1*(num1+1)/2 + num1;
[Link]("The Sum is "+ sum);
}
}
}
}
4 / 57
Java Interview Specific [Link] 2024-05-28
}
}
}
if (n < 2)
return false;
// checking the number of divisors b/w 1 and the number n-1
for (int i = 2; i < n; i++){
if (n % i == 0)
return false;
}
// if reached here then must be true
return true;
}
}
### 13. Find the Armstrong Numbers in a given Range using Java
```java
import [Link];
{
len++;
num = num/10;
}
return len;
}
private static int getArmstrongSum(int num, int order) {
if(num == 0)
return 0;
import [Link];
public class Anagram {
public static boolean isAnagram(String str1, String str2) {
// Remove all whitespace and convert to lowercase
str1 = [Link]();
str2 = [Link]();
// Check if the two strings have the same length
if ([Link]() != [Link]()) {
return false;
}
// Convert both strings to char arrays and sort them
char[] charArray1 = [Link]();
char[] charArray2 = [Link]();
[Link](charArray1);
[Link](charArray2);
17. Write a program to count the number of words in the given string
. check for spaces in the given string
. count the spaces inside a third party variable
. Add 1 to the total space count to find the total number of words.
10 / 57
Java Interview Specific [Link] 2024-05-28
for(int i=0;i<[Link]();i++){
if([Link](i)==' ' || i==[Link]()-1){
wordCount++;
}
}
return wordCount;
}
18. Write a program to find the count of all the uppercase letters in the given string
. Identify the ASCII value for A and Z (A=65 and Z=90)
. use a conditional statement to check if the character being checked falls under the given ranges
. if yes increment count
11 / 57
Java Interview Specific [Link] 2024-05-28
19. Write a program to print the smallest and biggest numbers in an array.
import [Link];
import [Link];
int factorial = 1;
12 / 57
Java Interview Specific [Link] 2024-05-28
import [Link];
int num = n;
int sum = 0;
int digits = [Link](n).length();
13 / 57
Java Interview Specific [Link] 2024-05-28
}
}
if (isPerfectSquare) {
[Link](n + " is a perfect square.");
} else {
[Link](n + " is not a perfect square.");
}
}
}
23. Program for Finding out the Prime Factors of a number in Java
import [Link];
import [Link];
26. Check Whether or Not the Given Number is a Strong Number in Java Language
import [Link];
if (sum == originalNum) {
[Link](originalNum + " is a strong number.");
} else {
[Link](originalNum + " is not a strong number.");
}
}
}
27. Program to check if the given number is an Automorphic number or not using Java
import [Link];
if (lastDigits == originalNum) {
[Link](originalNum + " is an Automorphic
number.");
} else {
[Link](originalNum + " is not an Automorphic
number.");
}
}
}
import [Link];
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
16 / 57
Java Interview Specific [Link] 2024-05-28
17 / 57
Java Interview Specific [Link] 2024-05-28
[Link]("Mins : "+mins);
[Link]("Seconds : "+secs);
}
}
18 / 57
Java Interview Specific [Link] 2024-05-28
//0 : 0 0 0 0 0 0 0 0
/*
* input-1 0 0 1 1
* input-2 0 1 0 1
* output 0 1 1 0
*
*
* if n is the number ---> 42
* then n is said to be even if n^1 == n+1 : 42 ^ 1 == 43
* then n is said to be odd if n^1 == n-1 : 43 ^ 1 == 42
*
* 42 in binary
* 2^0 2^1 2^2 2^3 2^4 2^5 2^6
19 / 57
Java Interview Specific [Link] 2024-05-28
* 1 2 4 8 16 32 64
* 0 1 0 1 0 1
*
* --> 101010
* 1
* ----------
* 101011
*
* 43 in binary
* 2^0 2^1 2^2 2^3 2^4 2^5 2^6
* 1 2 4 8 16 32 64
* 1 1 0 1 0 1
* 101011
* 1
* ------
* 101010
*/
[Link]("Armstrong");
}
else {
[Link]("Not Armstrong");
}
}
public static boolean armstrongCheck(int n) {
int temp=n, power=0, last=0;
double sum=0;
while(temp>0) {
temp = temp/10;//153/10 --> 15/10-->1/10-->0
power++;//1,2,3
}
temp = n;
while(temp>0) {
last = temp % 10;//153%10-->3, 15%10-->5, 1%10-->1
sum = sum + ([Link](last,
power));//0+27=27,27+125=152,152+1=153
temp = temp/10;//153/10-->15, 15/10-->1
}
if(sum==n)
{
return true;
}
else {
return false;
}
}
}
Inheritance:
--> It refers to the hierarchy of classes
--> It represents Parent - Child relationship
--> Inheritance can be achieved by making used of extends key word
--> Advantages of Inheritance:
1. re-usability of code
2. coding time reduces
3. profit is increased
--> We cannot include private members for inheritance
--> We cannot inherit constructors
21 / 57
Java Interview Specific [Link] 2024-05-28
class A{
A(){}
}
class B extends A{
A(){};//error
}
--> We cannot have multiple inheritance
class Parent1{
}
class Parent2{
}
class Child extends Parent1,Parent2{ //error
}
--> We can have multi-level inheritance in Java
class Shankar{
}
class Gopal extends Shankar{
}
class Vignesh extends Gopal{
}
--> We cannot have cyclic inheritance in java
class Shankar extends Gopal{
}
class Gopal extends Shankar{
}
class Vignesh extends Gopal{
}
--> We have 3 types of methods in inheritance
1. Inherited Method
2. Overridden method
3. Specialized method
Polymorphism:
--> Refers to 1:M relation
--> 2 categories
1. Complie time polymorphism
(Method overloading)
2. Run time polymorphism
(Method Overriding)
Abstraction:
--> Refers to the process of hiding the implementation
--> if a method does not have a implementation then we call such
methods as abstract method
--> An abstract method is indicated using "abstract" keyword
--> A class can be called as abstract class if it contains atleast one
abstract method
--> Can we create the object of an abstract class??
YES */
abstract class Shape {
double area;
abstract void input();//collecting input
abstract void calculate();//to calculate area
void display()
22 / 57
Java Interview Specific [Link] 2024-05-28
{
[Link](area);
}
}
class Circle extends Shape {
private double radius;
void input(){
Scanner sc = new Scanner([Link]);
[Link]("Enter the radius : ");
radius = [Link]();
}
void calculate() {
area = 3.147 * radius * radius;
}
}
class Square extends Shape {
private double side;
void input(){
Scanner sc = new Scanner([Link]);
[Link]("Enter the side : ");
side = [Link]();
}
void calculate() {
area = side * side;
}
}
//
//class Rectangle extends Shape {
// // your code goes here
//}
int vow = 0;
int con = 0;
for(int i=0;i<[Link]();i++)
{
if([Link](i)=='A' || [Link](i)=='E' || [Link](i)=='I'
||
[Link](i)=='O' || [Link](i)=='U') {
vow++;
}
else if([Link](i)=='a' || [Link](i)=='e' ||
[Link](i)=='i' ||
[Link](i)=='o' || [Link](i)=='u') {
vow++;
}
else if([Link](i)!=' '){
con++;
}
}
[Link]("Vowel : "+vow);
[Link]("Consonant : "+con);
}
}
38. Find max and min value in array with using built in class Arrays
24 / 57
Java Interview Specific [Link] 2024-05-28
25 / 57
Java Interview Specific [Link] 2024-05-28
40. Anagram
import [Link];
if ([Link]() == [Link]()) {
for (int i = 0; i <= [Link]() - 1; i++) {
if ([Link](i) == ' ') {
} else {
s1_mod = s1_mod + [Link](i);
}
}
for (int i = 0; i <= [Link]() - 1; i++) {
if ([Link](i) == ' ') {
} else {
s2_mod = s2_mod + [Link](i);
}
}
s1_mod = s1_mod.toUpperCase();
s2_mod = s2_mod.toUpperCase();
[Link](s1_mod);
[Link](s2_mod);
[Link](s1_arr);
[Link](s2_arr);
26 / 57
Java Interview Specific [Link] 2024-05-28
} else {
[Link]("Strings are not anagrams");
}
} else {
[Link]("Strings are not anagrams");
}
}
}
} else {
s2 = s2 + [Link](i);
}
}
}
[Link](s3);
[Link]([Link]([Link]() - 1));
}
}
{
int cond1=0,cond2=0,cond3=0,cond4=0;
if([Link]()>=8 && [Link]()<=15)
{
for(int i=0;i<=[Link]()-1;i++) {
if([Link](" ")) {
[Link]("Not a valid Password");
}
else {
if([Link](i)>=48 && [Link](i)<=57)
{
cond1++;
}
if([Link](i)>=97 && [Link](i)<=122)
{
cond2++;
}
if([Link](i)>=65 && [Link](i)<=90)
{
cond3++;
}
if([Link](i)>=35 && [Link](i)<=38)
{
cond4++;
}
}
}
}
else {
[Link]("Invalid Password");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the String :");
String s1 = [Link]();
validation(s1);
}
}
28 / 57
Java Interview Specific [Link] 2024-05-28
//arr[0] = "gninevE";
//arr[1] = "doog";
//arr[2] = "iH";
for(int i=[Link]-1;i>=0;i--) {
[Link](arr[i]+" ");
}
}
}
29 / 57
Java Interview Specific [Link] 2024-05-28
for(int j=0;j<[Link];j++) {
if(arr[i]==arr[j]) {
count++;
}
}
if(count%2 != 0) {
[Link](arr[i]);
}
count=0;
}
[Link](ts);
}
}
class DataTypes{
public static void main(String []argh)
{
Scanner sc = new Scanner([Link]);
//int t=[Link]();
// for(int i=1;i<=t;i++)
// {
// try
// {
long x=[Link]();
[Link](x+" can be fitted in: ");
if(x>=-128 && x<=127) {[Link]("* byte");}
if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE)
{[Link]("* short");}
if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE)
{[Link]("* int");}
if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE)
{[Link]("* long");}
// }
// catch(Exception e)
// {
// [Link]([Link]()+" can't be fitted
anywhere.");
// }
//
30 / 57
Java Interview Specific [Link] 2024-05-28
// }
}
}
[Link]("---------");
for(int i=0;i<[Link];i++)//school
{
[Link]("inside school no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("inside class no: "+(j+1));
for(int k=0;k<arr[i][j].length;k++) {
[Link]("Student "+(k+1)+" Please Enter
the feedback:");
arr[i][j][k] = [Link]();
}
}
}
for(int i=0;i<[Link];i++)//school
{
[Link]("inside school no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("inside class no: "+(j+1));
for(int k=0;k<arr[i][j].length;k++) {
[Link]("Feedback from Student-"+(k+1+" is
: "+arr[i][j][k]));
}
}
}
}
}
31 / 57
Java Interview Specific [Link] 2024-05-28
for(int i=0;i<[Link];i++) {
[Link]("inside class no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("Student "+(j+1)+" Please Enter the
name:");
arr[i][j] = [Link]();
}
}
for(int i=0;i<[Link];i++) {
[Link]("inside class no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("Student "+(j+1)+" name is : "+arr[i]
[j]);
}
}
}
}
32 / 57
Java Interview Specific [Link] 2024-05-28
33 / 57
Java Interview Specific [Link] 2024-05-28
[Link](a,b);
[Link](c1);
Calcy2 c2 = ()->{
// int a = 10;
// int b = 20;
int res = a+b;
[Link](res);
};
[Link]();
}
}
stmt = [Link]();
[Link](sql);
[Link]("Database Created");
[Link]();
[Link]();
}
}
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
stmt = [Link]();
// pstmt = [Link](sql);
[Link](sql);
// [Link]();
[Link]("Table Created");
[Link]();
[Link]();
}
}
35 / 57
Java Interview Specific [Link] 2024-05-28
[Link]();
[Link]();
}
36 / 57
Java Interview Specific [Link] 2024-05-28
stmt = [Link]();
res = [Link](sql);
while([Link]()) {
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
}
[Link]();
[Link]();
[Link]();
}
37 / 57
Java Interview Specific [Link] 2024-05-28
[Link]();
}
56. 1D Array
import [Link];
57. 2D Array
import [Link];
/* (i) (j)
* class students
* 0 5
* 1 5
* 2 5
*/
public class ArrayCode2 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the count of classes: ");
int cls = [Link]();
[Link]("Enter the count of students: ");
int stu = [Link]();
int arr[][] = new int[cls][stu];//two dimensional array
//storing the marks
for(int i=0;i<[Link];i++) {
[Link]("Inside class :"+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("Enter marks of student no: "+(j+1));
arr[i][j] = [Link]();
}
}
//fetching the marks
for(int i=0;i<[Link];i++) {
[Link]("Inside class :"+(i+1));
for(int j=0;j<arr[i].length;j++) {
[Link]("The marks of student no: "+(j+1)+" is:
"+arr[i][j] );
39 / 57
Java Interview Specific [Link] 2024-05-28
}
}
}
}
59. WAP to replace all the vowels with a special character specified
/*
* a --> @
* e --> #
* i --> $
* o --> %
* u --> &
*
* Sample i/p : aeiou
* Sample o/p : @#$%&
*/
40 / 57
Java Interview Specific [Link] 2024-05-28
import [Link];
public class StringCode12 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the string: ");
String str = [Link]();
str = [Link]();
int vowels_cnt=0;
int cons_cnt=0;
String str2="";
for(int i=0;i<[Link]();i++) {
if([Link](i)=='a') {
str2=str2+"@";
}
else if([Link](i)=='e') {
str2=str2+"#";
}
else if([Link](i)=='i') {
str2=str2+"$";
}
else if([Link](i)=='o') {
str2=str2+"%";
}
else if([Link](i)=='u') {
str2=str2+"&";
}
else {
str2=str2+[Link](i);
}
}
[Link](str2);
}
}
String str2="";
for(int i=0;i<[Link]();i++) {
if([Link](i)==' ' && [Link](i+1)==' ') {
}
else {
str2=str2+[Link](i);
41 / 57
Java Interview Specific [Link] 2024-05-28
}
}
[Link](str2);
}
}
//[Link]([Link](50));//ArrayIndexOutOfBoundException
[Link]([Link]('B'));
[Link]([Link]('z'));
[Link]([Link]("MaHa"));//true
[Link]([Link]("Vaha"));//false
[Link]([Link]("ratHA"));//true
[Link]([Link]("Vaha"));//false
[Link]([Link]("Bharat"));//true
[Link]([Link]("Vharat"));//false
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]('a'));
}
}
62. find the longest common prefix string amongst an array of strings
import [Link];
}
public static void main(String[] args) {
String str[] = {"flower","flow","blight"};
String prefix = findPrefix(str);
[Link](prefix);
}
}
case 'I':
num = 1;
break;
case 'V':
num = 5;
break;
case 'X':
num = 10;
break;
case 'L':
num = 50;
break;
case 'C':
num = 100;
break;
case 'D':
num = 500;
break;
case 'M':
num = 1000;
break;
}
if (4 * num < ans)
ans = ans - num;
else
ans = ans + num;
}
return ans;//14
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==0 || i==(n-1) // first and last rows
|| j==0 || j==(n-1)// first and last column
|| i==(n/2) || j==(n/2)// middle row and column
|| i==j // first big diagonal (left to right)
44 / 57
Java Interview Specific [Link] 2024-05-28
66. Pattern-1
/*
* 1 1 1 1 1
* 2 2 2 2 2
* 3 3 3 3 3
* 4 4 4 4 4
* 5 5 5 5 5
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
[Link](i+" ");
}
[Link]();
}
}
}
66. Pattern-2
45 / 57
Java Interview Specific [Link] 2024-05-28
/*
* 1 2 3 4 5
* 1 2 3 4 5
* 1 2 3 4 5
* 1 2 3 4 5
* 1 2 3 4 5
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
[Link](j+" ");
}
[Link]();
}
}
}
67. Pattern-3
/*
* 1 2 3 4 5
* 6 7 8 9 10
* 11 12 13 14 15
* 16 17 18 19 20
* 21 22 23 24 25
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
int count = 1;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
[Link](count+" ");
count++;
}
[Link]();
}
}
}
46 / 57
Java Interview Specific [Link] 2024-05-28
68. Pattern-4
/*
* 25 24 23 22 21
* 20 19 18 17 16
* 15 14 13 12 11
* 10 9 8 7 6
* 5 4 3 2 1
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
int count = n*n;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
[Link](count+" ");
count--;
}
[Link]();
}
}
}
69. Pattern-5
/*
* 1 6 11 16 21
* 2 7 12 17 22
* 3 8 13 18 23
* 4 9 14 19 24
* 5 10 15 20 25
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
int count = 1;
for(int i=1;i<=n;i++) {
count=i;
for(int j=1;j<=n;j++) {
[Link](count+" ");
count = count+n;
}
[Link]();
}
47 / 57
Java Interview Specific [Link] 2024-05-28
}
}
70. Pattern-6
/*
* @
* @ @
* @ @ @
* @ @ @ @
* @ @ @ @ @
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
[Link]("@ ");
}
[Link]();
}
}
}
71. Patter-7
/*
* * * * * *
* * * * *
* * * *
* * *
* *
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=n;j>=i;j--) { //*
[Link]("* ");
}
[Link]();
}
48 / 57
Java Interview Specific [Link] 2024-05-28
}
}
72. Pattern-8
/*
* 1
* 2 2
* 3 3 3
* 4 4 4 4
* 5 5 5 5 5
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
[Link](i+" ");
}
[Link]();
}
}
}
73. Pattern-9
/*
* 1
* 1 2
* 1 2 3
* 1 2 3 4
* 1 2 3 4 5
*/
49 / 57
Java Interview Specific [Link] 2024-05-28
}
}
74. Pattern-10
/* 1
* 2 3
* 4 5 6
* 7 8 9 10
* 11 12 13 14 15
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int count=1;
int n = [Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
[Link](count+" ");
count++;
}
[Link]();
}
}
}
* {
* this block of code will execute if the condition inside else if is
satisfied
* }
*
* ----- in-case condition inside else if also fails then the else
condition will be executed directly ----
*
* else
* {
* this block of code is directly executed if both if and else if
fails.
* }
*
*/
76. Pattern - 11
/*
* # # # # #
* # - - - #
* # - - - #
* # - - - #
* # # # # #
*/
51 / 57
Java Interview Specific [Link] 2024-05-28
}
}
77. Pattern-12
/*
* #
* # #
* # - #
* # - - #
* # # # # #
*/
}
}
78. Alphabet-A
52 / 57
Java Interview Specific [Link] 2024-05-28
}
}
79. Alphabet-B
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if(j==0 || (j==n/2 && i!=0 && i!=n/2 && i!=(n-1))||
(i==n/2 && j<n/2) ||
(i==0 && j<n/2) ||
(i==(n-1) && j<n/2)) {
[Link]("# ");
}
else {
[Link](" ");
}
}
[Link]();
}
}
}
80. Alphabet-C
53 / 57
Java Interview Specific [Link] 2024-05-28
}
}
81. Alphabet-D
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if(j==0 || (i==0 && j<n/2) || (i==n-1 && j<n/2)
|| (j==n/2 && i!=0 && i!=n-1)) {
[Link]("# ");
}
else {
[Link](" ");
}
}
[Link]();
}
}
}
82. Alphabet-E
54 / 57
Java Interview Specific [Link] 2024-05-28
}
}
83. Alphabet-F
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the value:");
int n = [Link]();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if(j==0 || (i==0 && j<n/2)
|| (i==n/2 && j<n/2)) {
[Link]("# ");
}
else {
[Link](" ");
}
}
[Link]();
}
}
}
84. Alphabet-G
public class Program{
public static void main(String[] args) {
55 / 57
Java Interview Specific [Link] 2024-05-28
}
[Link]();
}
}
}
import [Link];
void getData()
{
Scanner sc = new Scanner([Link]);
[Link]("Enter the age : ");
age = [Link]();
56 / 57
Java Interview Specific [Link] 2024-05-28
}
void verify()
{
if(age<18)
{
UnderAgeExpcetion uae = new UnderAgeExpcetion();
[Link]([Link]());
}
else if(age>60) {
OverAgeExpcetion oae = new OverAgeExpcetion();
[Link]([Link]());
}
else {
[Link]("Accepted");
}
}
}
public class CustomException {
public static void main(String[] args) {
Customer c = new Customer();
[Link]();
[Link]();
}
}
57 / 57
The program iterates through the string, counting spaces to determine word boundaries, and increments a word counter each time a space is encountered or when the end of the string is reached . An improvement for edge cases would be to first trim the string to remove leading and trailing spaces and then handle potential multiple consecutive spaces, which can lead to an inaccurate word count .
The Java code determines the greatest of three numbers using a series of conditional statements. First, it uses a ternary operator to find the larger of the first two numbers and stores it in a temporary variable. It then compares this temporary value with the third number to decide the greatest number. This logical sequence ensures that the code methodically evaluates all possibilities with the efficiency of minimizing comparisons .
In the Java implementation for generating the Fibonacci series, the program initializes the first two terms of the series, 0 and 1, and then iteratively calculates each subsequent term by adding the two preceding numbers. The first two prints in the program directly handle these initial terms, ensuring that 0 and 1 are included in the output before entering a loop that calculates and prints terms from the second position onwards up to the specified Nth term .
The Java program uses recursion to calculate the sum of each digit raised to the power equal to the number of digits (order). The getArmstrongSum method calls itself recursively, decrementing the number until it reaches zero and accumulates the results . The computational complexity is primarily determined by the number of digits, as the recursive call depth is linear with respect to the number of digits, making it O(d) for digit count 'd', but requires additional operations for exponentiation within each call .
The Java program for leap year calculation first checks if a year is divisible by 4, which is necessary because a leap year occurs every 4 years . If a year is divisible by 100, it must also be divisible by 400 to be considered a leap year, addressing the exception where every 100 years is not a leap year unless it coincides with the end of a century divisible by 400 . These nested conditions ensure accurate identification of leap years according to the Gregorian calendar rules .
To verify if two strings are anagrams, the program converts both strings to character arrays, sorts them, and checks if the sorted arrays are identical . Potential pitfalls include the computational expense of sorting when dealing with large datasets. Additionally, the approach presumes identical characters solely through sorting, neglecting potential inefficiencies of unnecessarily frequent sorting operations or failing to account for extended character sets beyond basic alphabets .
The program utilizes nested loops: an outer loop iterates over rows, while an inner loop fills each row with characters contingent upon loop indices and conditions (e.g., drawing the border of a shape). The primary limitation arises with larger input values, leading to increased computational time and memory usage since each additional line proportionally scales loop iterations, possibly exceeding practical space limitations or fostering inefficient execution speeds .
The algorithm checks each number within the specified interval to determine if it is prime, using a helper method that verifies primality by confirming no divisors exist between 2 and the number minus one . To optimize performance, the algorithm could reduce the range of divisor checks to the square root of each number, similar to single number primality tests . This optimization significantly reduces computational complexity, especially for larger numbers in the interval.
The program defines custom exceptions for underage and overage scenarios, providing meaningful messages through the exceptions' getMessage methods . This approach benefits code clarity and maintainability by separating error-handling logic specific to business rules (age validation) from generic exception handling. Custom messages facilitate better understanding of failures when exceptions are caught and displayed, aiding both debugging and user comprehension .
The Java program determines whether a number is prime by checking if the number is divisible by any integer from 2 to the number minus one . The program uses a flag variable to indicate whether any divisor is found, breaking the loop if a divisor is detected. However, this method can be optimized by reducing the number of checks to integers up to the square root of the number, since if a number is divisible by any integer greater than its square root, it must be a multiple of a smaller integer .