Showing posts with label java interview question. Show all posts
Showing posts with label java interview question. Show all posts

Sunday, March 12, 2023

Java Interview Question

Java Interview Question

1. What is the difference between an abstract class and an interface?

Answer: An abstract class can have both abstract and non-abstract methods, whereas an interface can only have abstract methods. An abstract class can also have constructors, instance variables, and method implementations, whereas an interface cannot.

Abstract Class Example 

public abstract class Vehicles {
   private int numOfWheels;
   
   public Vehicles(int numOfWheels) {
      this.numOfWheels = numOfWheels;
   }
   
   public int getNumOfWheels() {
      return this.numOfWheels;
   }
   
   public abstract void drive();
}

Interface Example

public interface Drivable {
   void drive();
}

2. What is the difference between a HashMap and a Hashtable?

Answer: HashMap is not thread-safe, whereas Hashtable is thread-safe. HashMap allows null values for both keys and values, whereas Hashtable does not allow null keys or values.

Example :

Creating a HashMap and adding elements

HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("John", 25);
myHashMap.put("Ravi", 30);
int value = myHashMap.get("John");

Creating a Hashtable and adding elements

Hashtable<String, Integer> myHashTbl = new Hashtable<>();
myHashTbl.put("John", 25);
myHashTbl.put("Ravi", 30);
int value = myHashTbl.get("John");

3. What is the difference between an inner class and a nested class?

Answer: An inner class is a non-static nested class, whereas a nested class can be either static or non-static. An inner class has access to the instance variables and methods of the enclosing class, whereas a static nested class does not.

Example :

Inner class 

public class OuterClass {

   private int x;
   
   public class InnerClass {
      public void printX() {
         System.out.println(x);
      }
   }

Nested class example

   public static class NestedClass {
      public void printHello() {
         System.out.println("Hello Java-Scholars");
      }
   }
}

4. What is the difference between a StringBuilder and a StringBuffer?

Answer: StringBuilder is not thread-safe, whereas StringBuffer is thread-safe. StringBuilder is faster because it is not synchronized, whereas StringBuffer is slower because it is synchronized.

Example:

Using StringBuilder

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("Java-Scholars");
String result = sb.toString();
Using StringBuffer
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("Java-Scholars");
String result = sb.toString();

5. What is the difference between an ArrayList and a LinkedList?

Answer: ArrayList is implemented as a dynamic array, whereas LinkedList is implemented as a doubly-linked list. ArrayList is faster for random access and iteration, whereas LinkedList is faster for inserting and removing elements.

Example :

Creating an ArrayList and adding elements

ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);

Creating a LinkedList and adding elements

LinkedList<Integer> myList = new LinkedList<Integer>();
myList.add(1);
myList.add(2);

6. What is the difference between a checked and an unchecked exception?

Answer: A checked exception is a type of exception that must be declared in the method signature or caught in a try-catch block. An unchecked exception is a type of exception that does not need to be declared or caught.

Example :

Checked exception

public void myMethod() throws IOException {
   // Code here
}

Unchecked exception

public void myMethod() {
   throw new NullPointerException();
}

Saturday, August 3, 2019

Java Logical Programs | Java Programming Examples

Java features and java logical program is commonly asked in every interview room. before you go for an interview must prepare java programming examples. In IT industries,  every interviewer checking your logic based on java logical programs and java logical code example.

1. Write a java program to find the duplicate vowel and count the duplicate vowel from a given string?

input = "Scholars-Java Blogspot in"
package in.blogspot.scholars.java;

public class RemoveVowelExample {

public static String removeVowels(String input) {

String novowelString = "";

String presentVowel = "";

int vowelCount = 0;

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

// vowel does not present then print

if (!isVowel((input.charAt(i)))) {

novowelString = novowelString + input.charAt(i);

} else {

presentVowel = presentVowel + input.charAt(i);

vowelCount++;

}

}

System.out.println("present vowel = " + presentVowel);

System.out.println("COUNT present vowel into the String = " + vowelCount);

return novowelString;

}

public static boolean isVowel(char c) {

// check input each character from input string

// 5 vowels checking with your each input character String

String vowels = "auioe";

for (int i = 0; i < 5; i++) {

if (c == vowels.charAt(i))

return true;

}

return false;

}
public static void main(String[] args) {

// enter input string

String input = "Scholars-Java Blogspot in";

String removeVowels = removeVowels(input.toLowerCase());

System.out.println("final non vowel String = " + removeVowels);

}

}
Output:

present vowel = oaaaooi
COUNT present vowel into the String = 7
final non vowel String = schlrs-jv blgspt n

2. Write a java program to find/check the duplicate character and count the duplicate character from the given string?

input: "javaScholars"
package in.blogspot.scholars.java;

public class duplcateCharacterFromStringExample {

public static void main(String[] args) {

String str = "javaScholars";

int count = 0;

// store each lower case character into char Arrays

char[] input = str.toLowerCase().toCharArray();

System.out.println("Duplicate Characters are = ");

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

for (int j = i + 1; j < str.length(); j++) {

if (input[i] == input[j]) {
System.out.print(input[j] + " ");
count++;
break;
}
}
}
if (count > 0)

System.out.println("\nDuplicate character COUNT from String = " + count);

else

System.out.println("No Duplicate = " + str);

}

}
Output:

Duplicate Characters are =
a a s
Duplicate Character COUNT from String= 3

3. Write a java program to check/find the given string anagram or not?

input = "javaS";
input2 = "Vjasa ";
package in.blogspot.scholars.java;

import java.util.Arrays;

public class AnagramOrNotExample {


public static void main(String[] args) {


// If the same length of both an exact match each character to each other

// is known as Anagram

// 1. madam or mmaad or madma

String input = "javaS";

String input2 = "Vjasa ";

// remove space may contain

String str1 = input.replaceAll("\\s", "");

String str2 = input2.replaceAll("\\s", "");

// check

boolean status = true;

// check length equal or not

if (str1.length() != str2.length()) {

status = false;

} else {

// make lower case both

// convert string in each character and add into arrays

char[] ch = str1.toLowerCase().toCharArray();

char[] ch2 = str2.toLowerCase().toCharArray();

// sort ascending order

Arrays.sort(ch);

Arrays.sort(ch2);

// check string one of each character to another String of each

status = Arrays.equals(ch, ch2);

// if true

if (status) {

System.out.println("is anagram : " + input + "==" + input2);

}

// if false

if (status == false) {

System.out.println("is NOT anagram : " + input + "==" + input2);

}

}

}

}
Output:
is anagram : javaS==Vjasa

4. Write a java program to find/check given mobile number fancy number or not?

input = "9788865456"
package in.blogspot.scholars.java;

public class FancyNumberExample {

public static void main(String[] args) {

// 1. 987/321

// 2. 123/789

// 3. 111/999

String input = "9788865456";

int[] arr = new int[input.length()];

for (int i = 0; i < input.length(); i++) {
// string to char and char to int arrays
arr[i] = Character.getNumericValue((input.charAt(i)));
}
int count = 1;
for (int i = 0; i < arr.length - 1; i++)
{
// consecutive equal no, ascending order sequence sequence, descending sequence
if (arr[i + 1] == arr[i] || arr[i + 1] - arr[i] == 1 || arr[i] - arr[i + 1] == 1)
{
count++;
}
}
// If more than two continue the same number then fancy no. otherwise NOT
if (count > 2)

System.out.println("count = " + count + " Number is fancy ::" + input);

else

System.out.println("count= " + count + " Number is NOT fancy ::" + input);

}
}
Output: 

count = 8 Number is fancy ::9788865456

5. Write a java program to swap two numbers without using 3 variables?

input value1 = 20
input value2 = 10
package in.blogspot.scholars.java;

public class SwapTwoNumberExample {

public void swapTwoVariable() {
// test cases
// 1. value1 = 20, value2 = 20
// 2. value1 = 10, value2 = 20
// 3. value1 = 20, value2 = 10

int value1 = 20, value2 = 10;
System.out.println(" value1 " + value1 + "\n value2 " + value2);
if (value2 == value1) {
System.out.println(" Not required to SWAP");
}
if (value2 > value1) {
value1 = value1 + value2;

value2 = value1 - value2;
value1 = value1 - value2;
System.out.println(" SWAP IS : \n value1 " + value1 + "\n value2 " + value2);
}
if (value2 < value1)
{
{
value2 = value1 + value2;
value1 = value2 - value1;
value2 = value2 - value1;
System.out.println(" SWAP IS :\n value1 " + value1 + "\n value2 " + value2);
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwapTwoNumberExample calling = new SwapTwoNumberExample();
calling.swapTwoVariable();
}
}
Output:

value1 20
value2 10
SWAP IS :
value1 10
value2 20

6. Write a java program to reverse number?

input = 4537
package in.blogspot.scholars.java;

public class ReverseStringNumberExample {

public void numberReverse(int num) {

int reverse = 0;

while (num != 0) {

reverse = reverse * 10;

reverse = reverse + num % 10;

// System.out.println(reverse);

num = num / 10;

}

System.out.println("Reverse number = " + reverse);
}

public static void main(String[] args) {

// TODO Auto-generated method stub

ReverseStringNumberExample revStr = new ReverseStringNumberExample();

//input number

revStr.numberReverse(4537);
}

}
Output: 

Reverse number = 7354

7. Write a java program to reverse a string without using the reverse () method?

input = "Java Scholars";
package in.blogspot.scholars.java;

public class ReverseStringNumberExample {

// Reverse String

public void stringreverse() {

String str = "Java Scholars";

String s = "";

//int i;

int length = str.length();

for (i = length - 1; i >= 0; i--) {

s = s + str.charAt(i);

}

System.out.println("reverse string = " + s);

System.out.println();

}

public static void main(String[] args) {

// TODO Auto-generated method stub

ReverseStringNumberExample revStr = new ReverseStringNumberExample();

revStr.stringreverse();
}
}
Output: 

reverse string = sralohcS ava

8. Write a java program to print pyramid pattern of stars?

row input: 5
package in.blogspot.scholars.java;

import java.io.IOException;

public class StarTringleExample {

public static void printtriangle(int rows) {

// spaces

int s = 2 * rows - 2;

// outer loop to handle the number of rows

// rows in this case

for (int i = 0; i < rows; i++)
{
// inner loop to handle number spaces
// values changing according to the requirement
for (int j = 0; j < s; j++)
{
// print spaces
System.out.print(" ");
}
// Decrementing space after each loop
s = s - 1;
// inner loop to handle the number of columns

// values changing according to the outer loop
for (int j = 0; j <= i; j++)
{
// print stars
System.out.print("*" + " ");
}
// new line for each row
System.out.println();
}
}
public static void main(String[] args) throws Exception
{
/ / input rows
printtriangle(5);
}
}
Output:

        *       
       * *
      * * *
     * * * *
    * * * * *

9. Write a java program to the print stars pattern and print the number patterns in reverse order?

input row = 5
package in.blogspot.scholars.java;

import java.io.IOException;

public class StarTringleExample {

public static void starsreversenum(int rows) throws NumberFormatException, IOException {

int i, j, a = 1;

for (i = 1; i = rows; i++)
{
a = ((i * (i + 1)) + 1) / 2;
for (j = 1; j = i; j++)
{
System.out.print((a--) + "*");
}
System.out.println();
}
}
}
public static void main(String[] args) throws Exception {
// rows input
StarTringleExample.starsreversenum(5);
}
}
}
Output:
 
1*  
3*2*  
6*5*4*  
10*9*8*7*  
15*14*13*12*11*

10. Write a java program to check the given number Palindrome number or not? or palindrome example in java?

input = 23432
output = 23432
package in.blogspot.scholars.java;


public class PolindromeNumberStringExample {



public void polindromeNum(int num) {

int temp, check = 0, remain;


temp = num;

if (num == 0)

System.out.println("please enter the number bigger than zero");

else

while (num > 0) {

remain = num % 10;

// System.out.println("remain " + remain);

check = check * 10 + remain;

// System.out.println("check " + check);

num = num / 10;

// System.out.println("num " + num);

}

System.out.println(check);

if (check == temp) {

System.out.println("Given number " + temp + " is Palindrome");

} else {

System.out.println("Given number " + temp + " is Not Palindrome");

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

PolindromeNumberStringExample calling = new PolindromeNumberStringExample();

// input number

calling.polindromeNum(23432);

}

}
Output: 

Given number 23432 is Palindrome

11. Write a java program to check the given String Palindrome or not? or palindrome string example in java?

input = "Nitin"
package in.blogspot.scholars.java;


public class PolindromeNumberStringExample {


public void polindromeString(String input) {

String str = "";

int len = input.length();

if ((input == null) && (input.equals("")))

System.out.println("please enter the String value");

else

for (int i = len - 1; i >= 0; i--) {

str = str + input.charAt(i);

}

if (input.equalsIgnoreCase(str)) {

System.out.println("The string is palindrome =" + input);

} else {

System.out.println("The string is not palindrome." + input);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

PolindromeNumberStringExample calling = new PolindromeNumberStringExample();

// input string

calling.polindromeString("Nitin");

}

}
Output:

The string is palindrome =Nitin

12. Write a java program to find the duplicate number element and duplicate number element count from Array?

input:
int[] arr ={ 4, 2, 4, 5, 2, 3, 1, 1 }
package in.blogspot.scholars.java;

public class DuplicateElementFromArrayExample {

public static void duplicateCount(int arr_size, int[] arr) {

int i, j;

int count = 0;

System.out.println("Repeated/Duplicate Integer elements are :");

for (i = 0; i < arr_size; i++)
{
for (j = i + 1; j < arr_size; j++)
{
if (arr[i] == arr[j])
{
count++;
System.out.print(arr[j] + " ");
}
}
}
System.out.println("\n No. of duplicates Integer element COUNT :" + count);
}
public static void main(String[] args)
{
int arr[] = { 4, 2, 4, 5, 2, 3, 1, 1 };
int arr_size = arr.length;
duplicateCount(arr_size, arr);
}
}
Output:

Repeated/Duplicate Integer elements are :
4 2 1
No. of duplicates Integer element COUNT :3

13. Write a java program to find the duplicate string element and duplicate string element count from Array?

input: 
String[] str = { "abc", "adc", "aMc", "aec", "adc", "abc" }
package in.blogspot.scholars.java;

public class DuplicateElementFromArrayExample {

public static void strCount(int Str_len, String[] str) {

int i, j;

int count = 0;

System.out.println("Repeated/Duplicate String elements are :");

for (i = 0; i < Str_len; i++)
{
for (j = i + 1; j < Str_len; j++)
{
if (str[i] == str[j])
{
count++;
System.out.print(str[i] + " ");
}
}
}
System.out.println("\n No. of duplicates String element COUNT :" + count);
}
public static void main(String[] args)
{
String[] str = { "abc", "adc", "aMc", "aec", "adc", "abc" };
int Str_len = str.length;
strCount(Str_len, str);
}
}
Output:

Repeated/Duplicate String elements are :
abc adc
No. of duplicates String element COUNT :2

14. Write a java program to find the prime number? or prime number example in java?

input: 4
package in.blogspot.scholars.java;

public class PrimeNoExample {

public static void main(String[] args) {


// prime no greater than 1 and divisible by itself

int inputnum = 4, flag = 0;

int m = inputnum / 2;

if (inputnum == 0 ||inputnum == 1) {

System.out.println(inputnum + "= not prime no.");


} else {


for (int i = 2; i <= m; i++)
{
if (inputnum % i == 0)
{
System.out.println(inputnum + "= not prime no.");
flag = 1;
break;
}
}
}
if (flag == 0)
{
System.out.println(inputnum + " is prime no.");
}
}
}
Output:

4 is not prime no.

15. Fibonacci Series in java? or Fibbonaci series example in java?

input : 10
package in.blogspot.scholars.java;

public class FibbonaciSeriesExamplescalling {

public void fibonacci() {

/*
* series of numbers in which each number ( Fibonacci number ) is the sum of the
* two preceding numbers.
*
*
*
* The simplest is the series 1, 1, 2, 3, 5, 8, etc
*
*
*
*/

int input = 10, s1 = 0, s2 = 1, s3 = 0;

System.out.print(s1 + "," + s2);

for (int i = 0; i < input; i++)
{
s3 = s1 + s2;
System.out.print("," + s3);
s1 = s2;
s2 = s3;
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
FibbonaciSeriesExamplescalling = new FibbonaciSeriesExample();
calling.fibonacci();
}
}
Output:

0,1,1,2,3,5,8,13,21,34,55,89