Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

java_interview_specific_codes

The document contains a collection of Java programs that demonstrate various fundamental programming concepts, such as determining if a number is positive or negative, checking for even or odd numbers, calculating sums, and identifying prime numbers. Each program is presented with code snippets and explanations, covering topics like leap years, palindromes, Armstrong numbers, and Fibonacci series. Additionally, there are programs for string manipulation, including checking for anagrams and counting words and uppercase letters.

Uploaded by

Julai J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java_interview_specific_codes

The document contains a collection of Java programs that demonstrate various fundamental programming concepts, such as determining if a number is positive or negative, checking for even or odd numbers, calculating sums, and identifying prime numbers. Each program is presented with code snippets and explanations, covering topics like leap years, palindromes, Armstrong numbers, and Fibonacci series. Additionally, there are programs for string manipulation, including checking for anagrams and counting words and uppercase letters.

Uploaded by

Julai J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Java Interview Specific Codes.

md 2024-05-28

Java Important Programs


1. Find a number is positive or negative ?
import java.util.Scanner;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();

if (num > 0)
System.out.println ("The number is positive");
else if (num < 0)
System.out.println ("The number is negative");
else
System.out.println ("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

2. Find a number is Even or Odd?


// Using Modulus Operator
public class Main
{
public static void main(String[] args) {
int number = 29;

//checking whether the number is even or odd


if (number % 2 == 0)
System.out.println(number + " is Even");
else
System.out.println(number + " is odd");
}
}

// Using Bitwise Operator


public class Main
{

1 / 57
Java Interview Specific Codes.md 2024-05-28

public static void main (String[]args)


{
int number = 29;

if (isEven (number))
System.out.println ("Even");
else
System.out.println ("Odd");
}

// Returns true if n is even, else odd


static bool isEven (int number)
{

// n & 1 is 1, then odd, else even


return (!(number & 1));
}
}

3. Find the Sum of First N Natural Numbers in Java


//using loops
public class Main
{
public static void main (String[]args)
{

int n = 10;
int sum = 0;

for (int i = 1; i <= n; i++){


sum += i;//sum=sum+i;
}
System.out.println (sum);
}
}

//using formula
public class Main
{
public static void main (String[]args)
{
int n = 10;
System.out.println (n*(n+1)/2);
}
}

2 / 57
Java Interview Specific Codes.md 2024-05-28

4. Find the Sum of the Numbers in a Given Interval in Java

//Using Brute Force


public class Main
{
public static void main (String[]args)
{
int a = 5;
int b = 10;

int sum = 0;

for (int i = a; i <= b; i++)


sum = sum + i;
System.out.println ("The sum is " + sum);
}
}

//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;
System.out.println("The Sum is "+ sum);
}
}

5. Find the Greatest of the Three Numbers in Java


//using conditional statements
public class Main
{
public static void main (String[]args)
{
int num1 = 10, num2 = 20, num3 = 30;
//checking if num1 is greatest
if (num1 >= num2 && num1 >= num3)
System.out.println (num1 + " is the greatest");
//checking if num2 is greatest
else if (num2 >= num1 && num2 >= num3)
System.out.println (num2 + " is the greatest");
//checking if num2 is greatest
else if (num3 >= num1 && num3 >= num2)
System.out.println (num3 + " is the greatest");
3 / 57
Java Interview Specific Codes.md 2024-05-28

}
}

public class Main


{
public static void main (String[]args)
{
int num1 = 10, num2 = 20, num3 = 30;
int temp, result;
// find the largest b/w num1 and num2 & store in temp
temp = num1>num2 ? num1:num2;
// find the largest b/w temp and num3 & finally printing it
result = temp>num3 ? temp:num3;
System.out.println (result + " is the greatest");
}
}

6. Check Whether or Not the Year is a Leap Year in Java


import java.util.Scanner;

public class LeapYear {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year :");
int n = sc.nextInt();//
boolean result = leapYear(n);
System.out.println(result);
}
public static boolean leapYear(int n) {
if(n%4 == 0)
{
if(n%100 == 0)
{
if(n%400 == 0)
{
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;

4 / 57
Java Interview Specific Codes.md 2024-05-28

}
}
}

7. Check if the given number is prime or not in Java


import java.util.Scanner;
public class PrimeNumber {
public static boolean isPrime(int num){
boolean flag = true;
for(int i=2;i< num;i++){
if(num%i == 0){//
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
//To collect input
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked :");
//the number to be checked is stored inside num
int num = sc.nextInt();
//calling isPrime(num) by passing num as the parameter
boolean result = isPrime(num);
if(result == true)
{
System.out.println("Given Number is a Prime number");
}
else
{
System.out.println("Given Number is not a Prime Number");
}
}
}

8. Find all the Prime Numbers in a Given Interval in Java


public class Main{
public static void main (String[]args){
int lower = 1, upper = 20;
for (int i = lower; i <= upper; i++)
if (isPrime (i))
System.out.println (i);
}
static boolean isPrime (int n){
int count = 0;
// 0, 1 negative numbers are not prime
5 / 57
Java Interview Specific Codes.md 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;
}
}

9. Find the Sum of the Digits of a Number in Java Language


public class Main
{
public static void main (String[]args)
{
int num = 12345, sum = 0;
System.out.println ("Sum of digits : " + getSum (num, sum));
}
static int getSum (int num, int sum)
{
if (num == 0)
return sum;
sum += num % 10;
/*
12345%10=5 --> sum=5 ---> 12345/10
1234%10 =4 --> sum=9 ---> 1234/10
123%10 =3 --> sum=12---> 123/10
12%10 =2 --> sum=14---> 12/10
1%10 =1 --> sum=15---> 1/10
0

1%10 =1 sum=1 --> 1/10


0
*/
return getSum (num / 10, sum);
}
}

10. Find the Reverse of a Number in Java Language


public class Main
{
public static void main (String[]args)
{
//variables initialization
int num = 1234, reverse = 0, rem;
6 / 57
Java Interview Specific Codes.md 2024-05-28

//loop to find reverse number


while (num != 0)
{
rem = num % 10;//
reverse = reverse * 10 + rem;
num /= 10;
};
/*
1234%10=4 rev=4 1234/10
123%10 =3 rev=43 123/10
12%10 =2 rev=432 12/10
1%10 =1 rev=4321
*/
//output
System.out.println ("Reversed Number: " + reverse);
}
}

11. Check Whether or Not the Number is a Palindrome in Java Language


public class Main{
public static void main (String[]args){
//variables initialization
int num = 12021, reverse = 0, rem, temp;
temp = num;
//loop to find reverse number
while (temp != 0){
rem = temp % 10;
reverse = reverse * 10 + rem;
temp /= 10;
};
// palindrome if num and reverse are equal
if (num == reverse)
System.out.println (num + " is Palindrome");
else
System.out.println (num + " is not Palindrome");
}
}

12. Check Whether or Not the Number is an Armstrong Number


import java.util.*;
import java.lang.*;
//1634 = 1^4+6^4+3^4+4^4 = 1+1296+81+256 = 1634
class Main {
public static void main(String[] args){
//variables initialization
int num = 1634, reverse = 0;
int len = order(num);
7 / 57
Java Interview Specific Codes.md 2024-05-28

if (num == getArmstrongSum(num, len))


System.out.println(num + " is an Armstrong Number");
else
System.out.println(num + " is not an Armstrong Number");
}
private static int getArmstrongSum(int num, int order) {
if(num == 0)
return 0;
int digit = num % 10;
return (int) Math.pow(digit, order) + getArmstrongSum(num/10,
order);
}
private static int order(int num) {
int len = 0;
while (num!=0){
len++;
num = num/10;
}
return len;
}

### 13. Find the Armstrong Numbers in a given Range using Java

```java
import java.util.Scanner;

public class LearnCoding2


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter lower and upper ranges : ");
int low = sc.nextInt();
int high = sc.nextInt();

System.out.println("Armstrong numbers between "+ low + " and " +


high + " are : ");
// loop for finding and printing all armstrong numbers between
given range
for(int num = low ; num <= high ; num++)
{
int len = getOrder(num);
if(num == getArmstrongSum(num, len))
System.out.print(num + " ");
}
}

private static int getOrder(int num) {


int len = 0;
while (num!=0)
8 / 57
Java Interview Specific Codes.md 2024-05-28

{
len++;
num = num/10;
}
return len;
}
private static int getArmstrongSum(int num, int order) {
if(num == 0)
return 0;

int digit = num % 10;

return (int) Math.pow(digit, order) + getArmstrongSum(num/10,


order);
}
}

14. Find the Fibonacci Series up to Nth Term in Java Language


public class Main{
public static void main (String[]args){
int num = 15;
int a = 0, b = 1;
// Here we are printing 0th and 1st terms
System.out.print (a + " , " + b + " , ");
int nextTerm;
// printing the rest of the terms here
for (int i = 2; i < num; i++){
nextTerm = a + b;
a = b;
b = nextTerm;
System.out.print (nextTerm + " , ");
}
}
}

15. Factorial of a Number in Java


class Main{
// Method to find factorial of the given number
static int factorial(int n){
int res = 1, i;
for (i = 2; i <= n; i++)
res *= i;
return res;
}
// Driver method
public static void main(String[] args){
int num = 6;
9 / 57
Java Interview Specific Codes.md 2024-05-28

System.out.println("Factorial of " + num + " is " +


factorial(num));
}
}

16. Program to check if the given 2 strings are anagrams.


. Convert the string to a character array
. sort the array
. check the equality of the 2 arrays.

import java.util.Arrays;
public class Anagram {
public static boolean isAnagram(String str1, String str2) {
// Remove all whitespace and convert to lowercase
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// Check if the two strings have the same length
if (str1.length() != str2.length()) {
return false;
}
// Convert both strings to char arrays and sort them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);

// Compare the sorted char arrays


return Arrays.equals(charArray1, charArray2);
}

public static void main(String[] args) {


String str1 = "restful";
String str2 = "fluster";
if (isAnagram(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams.");
} else {
System.out.println(str1 + " and " + str2 + " are not
anagrams.");
}
}
}

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 Codes.md 2024-05-28

public class WordCounter {


public static int countWords(String str) {
int wordCount = 0;

for(int i=0;i<str.length();i++){
if(str.charAt(i)==' ' || i==str.length()-1){
wordCount++;
}
}
return wordCount;
}

public static void main(String[] args) {


String str = "This is a test string.";
int wordCount = countWords(str);
System.out.println("The number of words in the string is: " +
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

public class UppercaseCounter {


public static int countUppercase(String str) {
int uppercaseCount = 0;
// Approach-1: Iterate through each character in the string
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isUpperCase(c)) {
uppercaseCount++;
}
}
//Approach-1: using ascii table
for(int i=0;i<str.length();i++){
if(str.charAt(i)>=65 && str.charAt(i)<=95){
uppercaseCount++;
}
}
return uppercaseCount;
}
public static void main(String[] args) {
String str = "This is a Test String.";
int uppercaseCount = countUppercase(str);
System.out.println("The number of uppercase letters in the string
is: " + uppercaseCount);
}

11 / 57
Java Interview Specific Codes.md 2024-05-28

19. Write a program to print the smallest and biggest numbers in an array.
import java.util.Arrays;

public class MinMaxFinder {


public static void main(String[] args) {
int[] arr = {10, 5, 7, 25, 30, 2};

// Sort the array in ascending order


Arrays.sort(arr);

// Print the smallest and largest elements of the array


System.out.println("Smallest element: " + arr[0]);
System.out.println("Largest element: " + arr[arr.length - 1]);
}
}

20. Find the Factorial of the given Number in Java


. Call function getFactorial(num)
. Set base case when num == 0 return 1
. Other cases return num * getFactorial(num-1);

import java.util.Scanner;

public class FactorialFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

int factorial = 1;

// Calculate the factorial of n


for (int i = 1; i <= n; i++) {
factorial *= i;
}

System.out.println("Factorial of " + n + " is " + factorial);


}
}

12 / 57
Java Interview Specific Codes.md 2024-05-28

21. Check Whether or Not the given Number is an Armstrong Number


370 = 3^3 + 7^3 + 0^3 = 27 + 343 + 0 = 370

import java.util.Scanner;

public class ArmstrongChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

int num = n;
int sum = 0;
int digits = String.valueOf(n).length();

// Calculate the sum of the cubes of the digits


while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}

// Check if the number is an Armstrong number


if (sum == n) {
System.out.println(n + " is an Armstrong number.");
} else {
System.out.println(n + " is not an Armstrong number.");
}
}
}

22. Check if the given number is a Perfect Square using Java


import java.util.Scanner;

public class PerfectSquareChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

boolean isPerfectSquare = false;

// Check if the number is a perfect square


for (int i = 1; i <= n; i++) {
if (i * i == n) {
isPerfectSquare = true;
break;

13 / 57
Java Interview Specific Codes.md 2024-05-28

}
}

if (isPerfectSquare) {
System.out.println(n + " is a perfect square.");
} else {
System.out.println(n + " is not a perfect square.");
}
}
}

23. Program for Finding out the Prime Factors of a number in Java
import java.util.Scanner;

import java.util.Scanner;

public class PrimeFactors {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

System.out.print("Prime factors of " + n + " are: ");

for (int i = 2; i <= n; i++) {


while (n % i == 0) {
System.out.print(i + " ");
n /= i;
}
}
}
}

24. Program to find the power of a number using Java


import java.util.Scanner;

public class PrimeFactorFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
System.out.print("Prime factors of " + n + ": ");
// Find the prime factors of n
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
14 / 57
Java Interview Specific Codes.md 2024-05-28

System.out.print(i + " ");


n /= i;
}
}
System.out.println();
}
}

25. Program to find factors of a number using Java


import java.util.Scanner;

public class FactorFinder {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();

System.out.print("Factors of " + num + " are: ");


for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
}
}

26. Check Whether or Not the Given Number is a Strong Number in Java Language
import java.util.Scanner;

public class StrongNumberChecker {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();

int originalNum = num;


int sum = 0;
while (num > 0) {
int digit = num % 10;
int factorial = 1;
for (int i = digit; i > 0; i--) {
factorial *= i;
}
sum += factorial;
num /= 10;
15 / 57
Java Interview Specific Codes.md 2024-05-28

if (sum == originalNum) {
System.out.println(originalNum + " is a strong number.");
} else {
System.out.println(originalNum + " is not a strong number.");
}
}
}

27. Program to check if the given number is an Automorphic number or not using Java
import java.util.Scanner;

public class AutomorphicNumberChecker {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
int square = num * num;
int count = 0;
int originalNum = num;
while (num > 0) {
count++;
num /= 10;
}
int lastDigits = (int) (square % (Math.pow(10, count)));

if (lastDigits == originalNum) {
System.out.println(originalNum + " is an Automorphic
number.");
} else {
System.out.println(originalNum + " is not an Automorphic
number.");
}
}
}

28. Binary to decimal conversion using Java

import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
16 / 57
Java Interview Specific Codes.md 2024-05-28

System.out.print("Enter a binary number : ");


int binary = sc.nextInt();
//Declaring variable to store decimal number
int decimal = 0;
//Declaring variable to use in power
int n = 0;
//writing logic for the conversion
while(binary > 0)
{
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
n++;
}
System.out.println("Decimal number : "+decimal);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

29. Octal to decimal conversion in Java


import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a octal number : ");
int octal = sc.nextInt();
//Declare variable to store decimal number
int decimal = 0;
//Declare variable to use in power
int n = 0;
//writing logic for the conversion
while(octal > 0)
{
int temp = octal % 10;
decimal += temp * Math.pow(8, n);
octal = octal/10;
n++;
}
//printing result
System.out.println("Decimal number : "+decimal);
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

17 / 57
Java Interview Specific Codes.md 2024-05-28

30. Calculate Age


import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;

public class AgeCalculator {


public static void main(String[] args) {
System.out.println("Enter the data in YYYY-MM-DD format :");
Scanner sc = new Scanner(System.in);
String dob = sc.nextLine();
ageCalculator(dob);
}

private static void ageCalculator(String dob) {


LocalDate dob_act = LocalDate.parse(dob);
LocalDate today = LocalDate.now();
System.out.println(today);
System.out.println(Period.between(dob_act, today).getYears());
}
}

31. Convert Hour to Second


import java.util.Scanner;

public class HourToSecond {


public static void main(String[] args) {
System.out.println("Enter hours :");
Scanner sc = new Scanner(System.in);
int hours = sc.nextInt();
int mins = hours * 60;
int secs = hours * 60 * 60;

System.out.println("Mins : "+mins);
System.out.println("Seconds : "+secs);
}
}

32. Even Number List


import java.util.Scanner;

public class EvenNumberList {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

18 / 57
Java Interview Specific Codes.md 2024-05-28

System.out.println("Enter the count of even numbers to printed


:");
int n = sc.nextInt();
//findEven(n);
findEvenXOR(n);
}
public static void findEven(int n) {
int arr[] = new int[n];
int count = 0;
for(int i=0;i<(2*n);i++)
{
if((i%2)==0)
{
arr[count]=i;
count++; // for the array index
}
}
//for each
for (int i : arr) {
System.out.print(i+", ");
}
}
public static void findEvenXOR(int n) {
int arr[] = new int[n];
int count = 0;
for(int i=0;i<(2*n);i++)
{
if((i ^ 1)==(i+1))
{
arr[count]=i;
count++; // for the array index
}
}
//for each
for (int i : arr) {
System.out.print(i+", ");
}
}
}

//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 Codes.md 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
*/

33. Leap Year


return true;
}
else {
return false;
}
}
else {
return true;
}
}
else {
return false;
}
}
}

//2000, 2004, 2008, 2012, ....

34. Armstrong Number


import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int n = sc.nextInt();//153
boolean result = armstrongCheck(n);
if(result==true) {
20 / 57
Java Interview Specific Codes.md 2024-05-28

System.out.println("Armstrong");
}
else {
System.out.println("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 + (Math.pow(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;
}
}
}

35. OOPs Pillars Program


/*
Encapsulation:
--> It refers to the process providing security to the most important
component of an object
--> Encapsulation can be achieved by making use of :
1. Private Members
2. Setters
3. Getters

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 Codes.md 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 Codes.md 2024-05-28

{
System.out.println(area);
}
}
class Circle extends Shape {
private double radius;
void input(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the radius : ");
radius = sc.nextDouble();
}
void calculate() {
area = 3.147 * radius * radius;
}
}
class Square extends Shape {
private double side;
void input(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the side : ");
side = sc.nextDouble();
}
void calculate() {
area = side * side;
}
}
//
//class Rectangle extends Shape {
// // your code goes here
//}

//to showcase and implement polymorphism


class Geometry {
void allow(Shape s)
{
s.input();
s.calculate();
s.display();
}
}

public class LaunchShapes {


public static void main(String[] args) {
Circle c = new Circle();
Square s = new Square();
Geometry g = new Geometry();
g.allow(c);
g.allow(s);
}
}

36. Vowel and Consonant Count


23 / 57
Java Interview Specific Codes.md 2024-05-28

public class VowelConsonant {


public static void main(String[] args) {
String s1 = "Hi Good MornIng to Everyone";

int vow = 0;
int con = 0;

for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)=='A' || s1.charAt(i)=='E' || s1.charAt(i)=='I'
||
s1.charAt(i)=='O' || s1.charAt(i)=='U') {
vow++;
}
else if(s1.charAt(i)=='a' || s1.charAt(i)=='e' ||
s1.charAt(i)=='i' ||
s1.charAt(i)=='o' || s1.charAt(i)=='u') {
vow++;
}
else if(s1.charAt(i)!=' '){
con++;
}
}
System.out.println("Vowel : "+vow);
System.out.println("Consonant : "+con);
}
}

37. Word Count


public class WordCount {
public static void main(String[] args) {
String s1 = " Welcome to skill-lync ";
int count=0;
System.out.println("String before trim : "+s1);
s1 = s1.trim();
System.out.println("String after trim : "+s1);
for(int i=0;i<=s1.length()-1;i++)
{
if(s1.charAt(i)==' ' && s1.charAt(i+1)!=' ')
count++;
}
System.out.println("Word Count is "+(count+1));
}
}

38. Find max and min value in array with using built in class Arrays
24 / 57
Java Interview Specific Codes.md 2024-05-28

public class MaxMin {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array : ");
int n = sc.nextInt();
int arr[] = new int[n];
//for(int i=0;i<arr.length;i++)
for(int i=0;i<=arr.length-1;i++) {
System.out.println("Enter the element in the position "+(i));
arr[i] = sc.nextInt();
}
for(int i=0;i<=arr.length-1;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
findMax(arr);
findMin(arr);
}

private static void findMin(int[] arr) {


int min = arr[0];
for(int i=0;i<=arr.length-1;i++) {
if((i+1)<(arr.length)) {
if(min>arr[i+1])
{
min = arr[i+1];
}
}
}
System.out.println("min = "+min);
}

private static void findMax(int[] arr) {


int max = arr[0];
for(int i=0;i<=arr.length-1;i++) {
if((i+1)<(arr.length)) {
if(max<arr[i+1])
{
max = arr[i+1];
}
}
}
System.out.println("max = "+max);
}
}

39. Convert to uppercase without using built-in methods


public class UpperCaseCount {
public static void main(String[] args) {

25 / 57
Java Interview Specific Codes.md 2024-05-28

String s1 = "JaVa Is thE BeSt LANguaGe";


int count=0;
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)>=65 && s1.charAt(i)<=90) {
count++;
}
}
System.out.println(count);
}
}

40. Anagram
import java.util.Arrays;

public class Anagram {


public static void main(String[] args) {
String s1 = "AB CD";
String s1_mod = "";
String s2 = "C ABD";
String s2_mod = "";

if (s1.length() == s2.length()) {
for (int i = 0; i <= s1.length() - 1; i++) {
if (s1.charAt(i) == ' ') {
} else {
s1_mod = s1_mod + s1.charAt(i);
}
}
for (int i = 0; i <= s2.length() - 1; i++) {
if (s2.charAt(i) == ' ') {
} else {
s2_mod = s2_mod + s2.charAt(i);
}
}

s1_mod = s1_mod.toUpperCase();
s2_mod = s2_mod.toUpperCase();

System.out.println(s1_mod);
System.out.println(s2_mod);

char[] s1_arr = s1_mod.toCharArray();


char[] s2_arr = s2_mod.toCharArray();

Arrays.sort(s1_arr);
Arrays.sort(s2_arr);

if (Arrays.equals(s1_arr, s2_arr) == true) {


System.out.println("Strings are anagrams");

26 / 57
Java Interview Specific Codes.md 2024-05-28

} else {
System.out.println("Strings are not anagrams");
}
} else {
System.out.println("Strings are not anagrams");
}
}
}

41. Leading and Tailing spaces


import java.util.Scanner;

public class LeadingAndTailingSpace {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String :");
String s1 = sc.nextLine();
String s2 = "";
String s3 = "";
// " Hi good evening "

for (int i = 0; i < s1.length(); i++) {


if ((i + 1) != s1.length()) {
if (s1.charAt(i) == ' ' && s1.charAt(i + 1) == ' ') {

} else {
s2 = s2 + s1.charAt(i);
}
}
}

if (s2.charAt(0) == ' ' || s2.charAt(s2.length() - 1) == ' ') {


for (int i = 1; i <= s2.length() - 1; i++) {
s3 = s3 + s2.charAt(i);
}
}

System.out.println(s3);
System.out.println(s3.charAt(s3.length() - 1));
}
}

42. Password validation


import java.util.Scanner;

public class PasswordValidation {


public static void validation(String s)
27 / 57
Java Interview Specific Codes.md 2024-05-28

{
int cond1=0,cond2=0,cond3=0,cond4=0;
if(s.length()>=8 && s.length()<=15)
{
for(int i=0;i<=s.length()-1;i++) {
if(s.contains(" ")) {
System.out.println("Not a valid Password");
}
else {
if(s.charAt(i)>=48 && s.charAt(i)<=57)
{
cond1++;
}
if(s.charAt(i)>=97 && s.charAt(i)<=122)
{
cond2++;
}
if(s.charAt(i)>=65 && s.charAt(i)<=90)
{
cond3++;
}
if(s.charAt(i)>=35 && s.charAt(i)<=38)
{
cond4++;
}
}
}
}
else {
System.out.println("Invalid Password");
}

if(cond1>0 && cond2>0 && cond3>0 && cond4>0) {


System.out.println("Valid password");
}
else {
System.out.println("Invalid password");
}

}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String :");
String s1 = sc.nextLine();
validation(s1);
}
}

43. Reverse String Word wise

28 / 57
Java Interview Specific Codes.md 2024-05-28

public class ReverseWordByWord21 {


public static void main(String[] args) {
String s1 = "Hi Good Evening";
int count = 0;
String s2 = "";
int arr_pos = 0;
//word count in the string
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)==' ')
{
count++;
}
}
//Used for storing the reversed words
String arr[] = new String[count+1];
//traversing the string in reverse order
for(int i=s1.length()-1;i>=0;i--)
{
if(s1.charAt(i)!=' ')//' ' != ' '
{
s2 = s2 + s1.charAt(i);//iH
}
else {
arr[arr_pos] = s2;//gninevE,doog
//arr[0] = "gninevE";
//arr[1] = "doog";
arr_pos++;
s2 = "";
}
}
arr[arr_pos] = s2;//iH

//arr[0] = "gninevE";
//arr[1] = "doog";
//arr[2] = "iH";

for(int i=arr.length-1;i>=0;i--) {
System.out.print(arr[i]+" ");
}

}
}

44. Odd Occurrence element


import java.util.TreeSet;

public class CountOddOcc {

29 / 57
Java Interview Specific Codes.md 2024-05-28

public static void main(String[] args) {


int arr[] = {1,2,3,1,1,2,2,3,3,4,4,5,5,5,5,5,6,6,7};
int count=0;
TreeSet ts = new TreeSet();
for(int i=0;i<arr.length;i++) {

for(int j=0;j<arr.length;j++) {
if(arr[i]==arr[j]) {
count++;
}
}
if(count%2 != 0) {
ts.add(arr[i]);
}
count=0;

}
System.out.println(ts);
}
}

45. Data types ranges


import java.util.Scanner;

class DataTypes{
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
//int t=sc.nextInt();

// for(int i=1;i<=t;i++)
// {
// try
// {
long x=sc.nextLong();
System.out.println(x+" can be fitted in: ");
if(x>=-128 && x<=127) {System.out.println("* byte");}
if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE)
{System.out.println("* short");}
if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE)
{System.out.println("* int");}
if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE)
{System.out.println("* long");}
// }
// catch(Exception e)
// {
// System.out.println(sc.next()+" can't be fitted
anywhere.");
// }
//

30 / 57
Java Interview Specific Codes.md 2024-05-28

// }
}
}

46. 3D Jagged Array


import java.util.Scanner;
//3D Jagged Array
public class LaunchSchool {
public static void main(String[] args) {
String arr[][][] = new String[2][][];
Scanner sc = new Scanner(System.in);
for(int i=0;i<arr.length;i++) {

System.out.println("Emter the class count :");


int n = sc.nextInt();
System.out.println("Emter the student count :");
int m = sc.nextInt();
arr[i] = new String[n][m];
}

System.out.println("---------");

for(int i=0;i<arr.length;i++)//school
{
System.out.println("inside school no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("inside class no: "+(j+1));
for(int k=0;k<arr[i][j].length;k++) {
System.out.println("Student "+(k+1)+" Please Enter
the feedback:");
arr[i][j][k] = sc.next();
}
}
}

for(int i=0;i<arr.length;i++)//school
{
System.out.println("inside school no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("inside class no: "+(j+1));
for(int k=0;k<arr[i][j].length;k++) {
System.out.println("Feedback from Student-"+(k+1+" is
: "+arr[i][j][k]));
}
}
}
}
}

31 / 57
Java Interview Specific Codes.md 2024-05-28

47. 2D Jagged Array


import java.util.Scanner;

public class LaunchSchool2 {


public static void main(String[] args) {
String arr[][] = new String[3][];
Scanner sc = new Scanner(System.in);

for (int i = 0; i < arr.length; i++) {


System.out.println("Emter the student count :");
int m = sc.nextInt();
arr[i] = new String[m];
}

for(int i=0;i<arr.length;i++) {
System.out.println("inside class no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("Student "+(j+1)+" Please Enter the
name:");
arr[i][j] = sc.next();
}
}

for(int i=0;i<arr.length;i++) {
System.out.println("inside class no: "+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("Student "+(j+1)+" name is : "+arr[i]
[j]);
}
}
}
}

48. Functional Interface


@FunctionalInterface //annotation
interface Calculator
{
// void div();
void add();//by default it is abstract
default void sub()
{
System.out.println("inside sub");
}
static void mul()
{
System.out.println("inside mul");
}
}

32 / 57
Java Interview Specific Codes.md 2024-05-28

class Launch2 implements Calculator{

public void add() {


System.out.println("inside add");
}
// default void sub()
// {
//
// }
static void mul()
{
System.out.println("inside mul of launch-2");
}

public class Launch1


{
public static void main(String[] args) {
Launch2.mul();
Calculator.mul();
Launch2 l2 = new Launch2();
l2.add();
l2.sub();
l2.mul();
}
}

49. Lambda Expression


//any method inside an interface by default is abstract
@FunctionalInterface
interface Calcy1
{
public abstract void add(int a, int b);//abstract
}
@FunctionalInterface
interface Calcy2
{
public abstract void add();//abstract
}
public class Launch4 {
public static void main(String[] args) {
int a=10;
int b=20;
Calcy1 c1 = (a1,b1)->{
// int a = 10;
// int b = 20;
int res = a1+b1;
System.out.println(res);
};

33 / 57
Java Interview Specific Codes.md 2024-05-28

c1.add(a,b);
System.out.println(c1);

Calcy2 c2 = ()->{
// int a = 10;
// int b = 20;
int res = a+b;
System.out.println(res);
};
c2.add();

}
}

50. JDBC - Create database


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class Challenge1 {


private static String url="jdbc:mysql://localhost:3306/DB_name";
private static String user="root";
private static String pwd="root";
private static Connection con;
private static Statement stmt;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

System.out.println("Enter the Database name:");


String db_name = sc.next();

String sql = "Create database "+db_name;

stmt = con.createStatement();
stmt.executeUpdate(sql);

System.out.println("Database Created");

stmt.close();
con.close();

}
}

51. JDBC - Create Table


34 / 57
Java Interview Specific Codes.md 2024-05-28

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Scanner;

public class Challenge2 {


private static String url="jdbc:mysql://localhost:3306/JDBC_Session";
private static String user="root";
private static String pwd="root";
private static Connection con;
private static Statement stmt;
private static PreparedStatement pstmt;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

System.out.println("Enter the table name:");


String tb_name = sc.next();

String sql = "Create table "+tb_name+" "


+ "(Product_id int,Product_name varchar(60),Product_cost
int,Product_available_quantity int,Product_rating int,Product_owner
varchar(60))";

stmt = con.createStatement();
// pstmt = con.prepareStatement(sql);
stmt.executeUpdate(sql);
// pstmt.executeUpdate();
System.out.println("Table Created");

stmt.close();
con.close();

}
}

52. JDBC - Insert data


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class Challenge3 {


private static String url="jdbc:mysql://localhost:3306/JDBC_Session";
private static String user="root";
private static String pwd="root";

35 / 57
Java Interview Specific Codes.md 2024-05-28

private static Connection con;


private static PreparedStatement pstmt;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

String sql = "insert into ecommerce values(?,?,?,?,?,?)";


pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "mobile");
pstmt.setInt(3, 20000);
pstmt.setInt(4, 40);
pstmt.setInt(5, 5);
pstmt.setString(6, "Samsung");
pstmt.executeUpdate();

System.out.println("Table data added");

pstmt.close();
con.close();
}

53. JDBC - Select All


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class Challenge4 {


private static String url="jdbc:mysql://localhost:3306/JDBC_Session";
private static String user="root";
private static String pwd="root";
private static Connection con;
private static Statement stmt;
private static PreparedStatement pstmt;
private static ResultSet res;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

String sql = "Select * from Ecommerce";

36 / 57
Java Interview Specific Codes.md 2024-05-28

stmt = con.createStatement();
res = stmt.executeQuery(sql);
while(res.next()) {
System.out.println(res.getInt(1));
System.out.println(res.getString(2));
System.out.println(res.getInt(3));
System.out.println(res.getInt(4));
System.out.println(res.getInt(5));
System.out.println(res.getString(6));
}
res.close();
stmt.close();
con.close();
}

54. JDBC - Select specific


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class Challenge5 {


private static String url="jdbc:mysql://localhost:3306/JDBC_Session";
private static String user="root";
private static String pwd="root";
private static Connection con;
private static PreparedStatement pstmt;
private static ResultSet res;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

String sql = "select * from ecommerce where product_price > ?";


pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 2000);
res = pstmt.executeQuery(sql);
while(res.next()) {
System.out.println(res.getInt(1));
System.out.println(res.getString(2));
System.out.println(res.getInt(3));
System.out.println(res.getInt(4));
System.out.println(res.getInt(5));
System.out.println(res.getString(6));
}
pstmt.close();

37 / 57
Java Interview Specific Codes.md 2024-05-28

con.close();
}

55. JDBC - Update


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class Challenge5 {


private static String url="jdbc:mysql://localhost:3306/JDBC_Session";
private static String user="root";
private static String pwd="root";
private static Connection con;
private static PreparedStatement pstmt;
private static ResultSet res;

public static void main(String[] args) throws Exception {


Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, user, pwd);

String sql = "select * from ecommerce where product_price > ?";


pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 2000);
res = pstmt.executeQuery(sql);
while(res.next()) {
System.out.println(res.getInt(1));
System.out.println(res.getString(2));
System.out.println(res.getInt(3));
System.out.println(res.getInt(4));
System.out.println(res.getInt(5));
System.out.println(res.getString(6));
}
pstmt.close();
con.close();
}

56. 1D Array
import java.util.Scanner;

public class ArrayCode1 {


38 / 57
Java Interview Specific Codes.md 2024-05-28

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.println("Enter the count of students");
int n = sc.nextInt();
int arr[] = new int[n];//one dimensional array
//storing the data
for(int i=0;i<arr.length;i++) {
System.out.println("Enter the marks of student no: "+(i+1));
arr[i] = sc.nextInt();
}
System.out.println("###### ----- Marks added ----- ######");
//fetching the data
for(int i=0;i<arr.length;i++) {
System.out.println("The marks of student no: "+(i+1)+" is =
"+arr[i]);
}
}
}

57. 2D Array
import java.util.Scanner;

/* (i) (j)
* class students
* 0 5
* 1 5
* 2 5
*/
public class ArrayCode2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the count of classes: ");
int cls = sc.nextInt();
System.out.println("Enter the count of students: ");
int stu = sc.nextInt();
int arr[][] = new int[cls][stu];//two dimensional array
//storing the marks
for(int i=0;i<arr.length;i++) {
System.out.println("Inside class :"+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("Enter marks of student no: "+(j+1));
arr[i][j] = sc.nextInt();
}
}
//fetching the marks
for(int i=0;i<arr.length;i++) {
System.out.println("Inside class :"+(i+1));
for(int j=0;j<arr[i].length;j++) {
System.out.println("The marks of student no: "+(j+1)+" is:
"+arr[i][j] );

39 / 57
Java Interview Specific Codes.md 2024-05-28

}
}
}
}

58. Method Overloading


class Calculator{
int add(int a, int b) {
return a+b;
}
float add(float a, float 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;
}
float add(int a, float b) {
return a+b;
}
float add(float a, int b) {
return a+b;
}
}

public class MethodOverloadingExmp {


public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 20));
System.out.println(c.add(20.4f, 30.5f));
System.out.println(c.add(10, 20, 30));
}
}

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 Codes.md 2024-05-28

import java.util.Scanner;
public class StringCode12 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string: ");
String str = sc.next();
str = str.toLowerCase();
int vowels_cnt=0;
int cons_cnt=0;
String str2="";
for(int i=0;i<str.length();i++) {
if(str.charAt(i)=='a') {
str2=str2+"@";
}
else if(str.charAt(i)=='e') {
str2=str2+"#";
}
else if(str.charAt(i)=='i') {
str2=str2+"$";
}
else if(str.charAt(i)=='o') {
str2=str2+"%";
}
else if(str.charAt(i)=='u') {
str2=str2+"&";
}
else {
str2=str2+str.charAt(i);
}
}
System.out.println(str2);
}
}

60. Remove the unnecessary spaces in between the strings


import java.util.Scanner;
public class StringCode13 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string: ");
String str = sc.nextLine();
str = str.toLowerCase();

String str2="";
for(int i=0;i<str.length();i++) {
if(str.charAt(i)==' ' && str.charAt(i+1)==' ') {

}
else {
str2=str2+str.charAt(i);

41 / 57
Java Interview Specific Codes.md 2024-05-28

}
}
System.out.println(str2);
}
}

61. Few Built-in methods of Strings Class


public class StringCode6 {
public static void main(String[] args) {
String s1 = "MaHaBharatHA";
System.out.println(s1.toUpperCase());//MAHABHARATHA
System.out.println(s1.toLowerCase());//mahabharatha
System.out.println(s1.charAt(5));//h

//System.out.println(s1.charAt(50));//ArrayIndexOutOfBoundException
System.out.println(s1.indexOf('B'));
System.out.println(s1.indexOf('z'));
System.out.println(s1.startsWith("MaHa"));//true
System.out.println(s1.startsWith("Vaha"));//false
System.out.println(s1.endsWith("ratHA"));//true
System.out.println(s1.endsWith("Vaha"));//false
System.out.println(s1.contains("Bharat"));//true
System.out.println(s1.contains("Vharat"));//false
System.out.println(s1.getClass());
System.out.println(s1.isBlank());
System.out.println(s1.length());
System.out.println(s1.lastIndexOf('a'));
}
}

62. find the longest common prefix string amongst an array of strings
import java.util.Arrays;

public class LongestCommonPrefix {


public static String findPrefix(String[] strs) {
Arrays.sort(strs);
String s1 = strs[0];
String s2 = strs[strs.length-1];
int i = 0;
while(i < s1.length() && i < s2.length()){
if(s1.charAt(i) == s2.charAt(i)){
i++;
} else {
break;
}
}
return s1.substring(0, i);
42 / 57
Java Interview Specific Codes.md 2024-05-28

}
public static void main(String[] args) {
String str[] = {"flower","flow","blight"};
String prefix = findPrefix(str);
System.out.println(prefix);
}
}

63. Pascal's triangle


import java.util.ArrayList;
import java.util.List;
/*
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
*/
public class PascalTriangle {
public static List<List<Integer>> pascalTriangle(int numRows) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> row, pre = null;
for (int i = 0; i < numRows; i++) {
row = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i)
row.add(1);
else
row.add(pre.get(j - 1) + pre.get(j));
}
pre = row;
list.add(row);
}
return list;
}

public static void main(String[] args) {


System.out.println(pascalTriangle(5));
}
}

64. Roman Conversion


public class RomanConversion {
public static int convert(String s) {
int ans = 0, num = 0;
for (int i = s.length() - 1; i >= 0; i--) {
switch (s.charAt(i)) {
43 / 57
Java Interview Specific Codes.md 2024-05-28

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
}

public static void main(String[] args) {


System.out.println(convert("IVX"));
}
}

65. Universal Pattern


import java.util.Scanner;

public class UniversalPat {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n: ");
int n = sc.nextInt();

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 Codes.md 2024-05-28

|| i+j == (n-1) // second big diagonal (right to left)


|| i+j == (n/2) // first small diagonal (top left to
right)
|| j-i == (n/2) // second small diagonal (top right to
left)
|| i-j == (n/2) // third small diagonal (bottom right to
left))
|| i+j == (n-1)+n/2 //fourth small diagonal (bottom left
to right)
)
{
System.out.print("* ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();

for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
System.out.print(i+" ");
}
System.out.println();
}

}
}

66. Pattern-2

45 / 57
Java Interview Specific Codes.md 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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();

for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
System.out.print(j+" ");
}
System.out.println();
}

}
}

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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
int count = 1;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
System.out.print(count+" ");
count++;
}
System.out.println();
}

}
}

46 / 57
Java Interview Specific Codes.md 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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
int count = n*n;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
System.out.print(count+" ");
count--;
}
System.out.println();
}

}
}

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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
int count = 1;
for(int i=1;i<=n;i++) {
count=i;
for(int j=1;j<=n;j++) {
System.out.print(count+" ");
count = count+n;
}
System.out.println();
}

47 / 57
Java Interview Specific Codes.md 2024-05-28

}
}

70. Pattern-6
/*
* @
* @ @
* @ @ @
* @ @ @ @
* @ @ @ @ @
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print("@ ");
}
System.out.println();
}

}
}

71. Patter-7
/*
* * * * * *
* * * * *
* * * *
* * *
* *
*/
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=n;j>=i;j--) { //*
System.out.print("* ");
}
System.out.println();
}

48 / 57
Java Interview Specific Codes.md 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(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print(i+" ");
}
System.out.println();
}

}
}

73. Pattern-9
/*
* 1
* 1 2
* 1 2 3
* 1 2 3 4
* 1 2 3 4 5
*/

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print(j+" ");
}
System.out.println();
}

49 / 57
Java Interview Specific Codes.md 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(System.in);
System.out.println("Enter the value:");
int count=1;
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print(count+" ");
count++;
}
System.out.println();
}

}
}

75. Conditional Statement


/*
* Conditional Statements: These are the statements that are used to
specify a conditional check before the
* execution of a particular statement.
* The conditional statements in programming are:
* 1. if condition
* 2. else if condition
* 3. else condition
*
* if(condition)
* {
* this block of code will execute if the condition inside if is
satisfied
* }
* ----- in-case condition inside if fails then the else if condition will
be checked ----
*
*
* else if(condition)
50 / 57
Java Interview Specific Codes.md 2024-05-28

* {
* 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.
* }
*
*/

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the age: ");
int age = sc.nextInt();

if(age < 18)


{
System.out.println("You are still a minor. Please grow up and
then think of marriage");
}
else if(age > 65)
{
System.out.println("You are a senior citizen. Stop expecting
too much");
}
else
{
System.out.println("You are the most eligible groom/bride");
}
}
}

76. Pattern - 11
/*
* # # # # #
* # - - - #
* # - - - #
* # - - - #
* # # # # #
*/

public class Program{


public static void main(String[] args) {

51 / 57
Java Interview Specific Codes.md 2024-05-28

Scanner sc = new Scanner(System.in);


System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if(i==1 || i==n || j==1 || j==n) {
System.out.print("# ");
}
else {
System.out.print("- ");
}
}
System.out.println();
}

}
}

77. Pattern-12
/*
* #
* # #
* # - #
* # - - #
* # # # # #
*/

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=i;j++) {
if(j==0 || i==j || i==n-1) {
System.out.print("# ");
}
else {
System.out.print("- ");
}
}
System.out.println();
}

}
}

78. Alphabet-A
52 / 57
Java Interview Specific Codes.md 2024-05-28

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if(j==0 || j==n/2 ||
(i==n/2 && j<=n/2) ||
(i==0 && j<=n/2)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

79. Alphabet-B
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
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)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

80. Alphabet-C
53 / 57
Java Interview Specific Codes.md 2024-05-28

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if((j==0 && i!=0 && i!=(n-1)) ||
i==0 && j!=0 && j<n/2||
i==(n-1) && j!=0 && j<n/2) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

81. Alphabet-D
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
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)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

82. Alphabet-E

54 / 57
Java Interview Specific Codes.md 2024-05-28

public class Program{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
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)
|| (i==n/2 && j<n/2)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

83. Alphabet-F
public class Program{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value:");
int n = sc.nextInt();
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)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}

}
}

84. Alphabet-G
public class Program{
public static void main(String[] args) {

55 / 57
Java Interview Specific Codes.md 2024-05-28

Scanner sc = new Scanner(System.in);


System.out.println("Enter the value:");
int n = sc.nextInt();
for(int i=0;i<=n-1;i++) {
for(int j=0;j<=n-1;j++) {
if((j==0 && i!=0 && i!=(n-1)) ||
(i==0 && j!=0 && j<=n/2) ||
(i==n/2 && j>n/4 && j<n/2) ||
(i==(n-1) && j>0 && j<=n/4)||
(j==(n/4) && i>n/2) ||
(j==(n/2) && i>n/2)) {
System.out.print("# ");
}
else {
System.out.print(" ");
}

}
System.out.println();
}

}
}

85. Custom Exception


package com.skill.lync.java.solutions;

import java.util.Scanner;

class OverAgeExpcetion extends Exception{


public String getMessage()
{
return "Invalid Age. Your age is above 60";
}
}
class UnderAgeExpcetion extends Exception{
public String getMessage()
{
return "Invalid Age. Your age is below 18";
}
}
class Customer
{
private int age;

void getData()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the age : ");
age = sc.nextInt();

56 / 57
Java Interview Specific Codes.md 2024-05-28

}
void verify()
{
if(age<18)
{
UnderAgeExpcetion uae = new UnderAgeExpcetion();
System.out.println(uae.getMessage());
}
else if(age>60) {
OverAgeExpcetion oae = new OverAgeExpcetion();
System.out.println(oae.getMessage());
}
else {
System.out.println("Accepted");
}
}
}
public class CustomException {
public static void main(String[] args) {
Customer c = new Customer();
c.getData();
c.verify();
}
}

57 / 57

You might also like