Best Programming questions in java

You are currently viewing Best Programming questions in java

Here is a big list of Best Programming questions in java for Job Interviews. As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews.

You can also try out these programs

Part – 1 for Programming questions in java

//Hello.java

class Hello

 {

 public static void main(String args[])

 {

 System.out.println(“Welcome to Java!”);

 }

}

Compile: – javac Hello.java

Run Java: – java Hello

Write a program for object and class in java.

class Rectangle

{

 privateintl,b;

 public void setDimension(intx,int y)

 {

 l=x;

 b=y;

 }

 publicint area()

 {

 return l*b;

 }

 public void display()

 {

 System.out.println(“Length=”+l);

 System.out.println(“Breadth=”+b);

 }

 public static void main(String ac[])

 {

 Rectangle r=new Rectangle();

 r.setDimension(5,10);

 r.display();

 System.out.println(“Area=”+r.area());

 }

}

Programming questions in java

Write a program to explain the concept of this keyword in java.

classThisTest

{

int id;

 String name;

ThisTest(intid,String name)

 {

 this.id = id;

 this.name = name;

 }

void display()

 {

 System.out.println(id+” “+name);

 }

 public static void main(String args[])

 {

 ThisTest s1 = new ThisTest(142,”Shamshad”);

 ThisTest s2 = new ThisTest(452,”John”);

 s1.display();

 s2.display();

 }

}

Programming questions in java

Write a program to explain the concept of super keyword in java.

class Bike

{

int speed=50;

}

class Super extends Bike

{

 int speed=100;

 void display()

 {

System.out.println(super.speed);

 }

 public static void main(String args[])

 {

 Super b=new Super();

 b.display();

 }

}

Programming questions in java

Write a program for overloading in java.

class Overloading

{

void sum(inta,int b)

 {

 System.out.println(a+b);

 }

void sum(double a,double b)

 {

 System.out.println(a+b);

 }

 public static void main(String args[])

 {

 Overloading obj=new Overloading();

 obj.sum(10.5,10.5);

 obj.sum(20,20);

 }

}

Programming questions in java

Part – 2 for Programming questions in java

Write an abstract class program in java.

public abstract class shape

{

public abstract void calculatearea();

}

public class circle extends shape

{

privateintx,y;

privateint radius;

public circle()

{

x=15;

y=15;

radius=10;

}

public void calculatearea ()

{

double area=3.14*(radius*radius);

System.out.println(“area=”+area);

}

}

class test1

{

 public static void main(String arr[])

 {

shape s =null;

s=new circle();

s.calculatearea();

 }

}

Programming questions in java

Write an Interface program in java.

public interface Speaker

{

 public void speak();

}

public class Lecturer implements Speaker

{

 public void speak()

 {

 System.out.println(“Lecturer view”);

 }

}

public class Politician implements Speaker

{

 public void speak()

 {

 System.out.println(“Politician view”);

 }

}

public class Test

{

 public static void main(String arr[])

 {

 Speaker sp=null;

 System.out.println(“sp point to politician”);

 sp=new Politician();

 sp.speak();

 System.out.println(“sp point to Lecturer”);

 sp=new Lecturer();

 sp.speak();

 }

}

Programming questions in java

Write a program for Handling an Exception In java.

classExceptionHandling

{

 public static void main(String arr[])

 {

 try

 {

 int a=Integer.parseInt(arr[0]);

 int b=Integer.parseInt(arr[1]);

 int sum = a/b;

 System.out.println(“Result:”+ sum);

 }

 catch(Exception e)

 {

 System.out.println(e);

 }

 }

}

Programming questions in java

Write a program for a Constructor in java.

class A

{

int a;

public A(int x)

{

a=x;

}

public A()

{

System.out.println(“it is default constructor”);

}

{

System.out.println(“it is funny”);

}

public void display()

{

System.out.println(“a=”+a);

}

public static void main(String arg[])

{

A x=new A();

x.display();

A y=new A(10);

y.display();

}

}

Programming questions in java

to print Fibonacci series in Java

// Dynamic Programming approach for

// Fibonacci Series

class fibonacci {

          // Function to find the fibonacci Series

          static int fib(int n)

          {

                    // Declare an array to store

                    // Fibonacci numbers.

                    // 1 extra to handle case, n = 0

                    int f[] = new int[n + 2];

                    int i;

                    // 0th and 1st number of

                    // the series are 0 and 1

                    f[0] = 0;

                    f[1] = 1;

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

                              // Add the previous 2 numbers

                              // in the series and store it

                              f[i] = f[i – 1] + f[i – 2];

                    }

                    // Nth Fibonacci Number

                    return f[n];

          }

          public static void

          main(String args[])

          {

                    // Given Number N

                    int N = 10;

                    // Print first 10 term

                    for (int i = 0; i < N; i++)

                              System.out.print(fib(i) + ” “);

          }

}

How to convert LinkedList to Array in Java?

// Java program to convert

// LinkedList to Array

import java.util.*;

public class GFG {

          // Function to convert LinkedList to Array

          public static <T> Object[] convertLinkedListToArray(LinkedList<T> linkedList)

          {

                    // Converting LinkedList to Array

                    Object[] array = linkedList.toArray();

                    return array;

          }

          public static void main(String args[])

          {

                    // Creating linked list

                    LinkedList<String>

                              linkedList = new LinkedList<String>();

                    // Adding elements to the linked list

                    linkedList.add(“G”);

                    linkedList.add(“e”);

                    linkedList.add(“e”);

                    linkedList.add(“k”);

                    linkedList.add(“s”);

                    // Print the LinkedList

                    System.out.println(“Linked list: “

                                                            + linkedList);

                    // Converting LinkedList to Object Array

                    Object[] objArray = convertLinkedListToArray(linkedList);

                    // Convert Object[] to String[]

                    String[] array = Arrays.copyOf(objArray,

                                                                                          objArray.length,

                                                                                          String[].class);

                    // Print the String Array

                    System.out.println(“Array: “

                                                            + Arrays.toString(array));

          }

}

Convert a String to a List of Characters in Java

// Java program to illustrate

// Converting a String to a List

// of Characters

import java.util.*;

// Java program to convert

// a String to a List of Characters

class GFG {

          // Function to convert String

          // to List of Characters

          public static List<Character>

          convertStringToCharList(String str)

          {

                    // Create an empty List of character

                    List<Character> chars = new ArrayList<>();

                    // For each character in the String

                    // add it to the List

                    for (char ch : str.toCharArray()) {

                              chars.add(ch);

                    }

                    // return the List

                    return chars;

          }

          // Driver code

          public static void main(String[] args)

          {

                    // Get the String to be converted

                    String str = “Geek”;

                    // Get the List of Character

                    List<Character>

                              chars = convertStringToCharList(str);

                    // Print the list of characters

                    System.out.println(chars);

          }

}

Part – 3 for Programming questions in java

Final All Permutations of given String Using Recursion and Loop

public class StringPermutations

{

 public static void main(String args[])

 {

 permutation(“123”);

 }

 /* * A method exposed to client to calculate permutation of String in Java.*/

 public static void permutation(String input){

permutation(“”, input);

 }

 /* * Recursive method which actually prints all permutations

* of given String, but since we are passing an empty String

 * as current permutation to start with,

 * I have made this method private and didn’t exposed it to client. */ private static void permutation(String perm, String word) {

 if (word.isEmpty())

 {

 System.err.println(perm + word);

}

else

 {

 for (int i = 0; i &lt; word.length(); i++)

 {

 permutation(perm + word.charAt(i), word.substring(0, i) + word.substring(i + 1, word.length()));

 }

 }

 }

 }

 Output: 123 132 213 231 312 321


How to check if two String are Anagram in Java

import java.util.Arrays;

 /** * Java program – String Anagram Example.

 * This program checks if two Strings are anagrams or not */

 public class AnagramCheck {

/* * One way to find if two Strings are anagram in Java. This method

* assumes both arguments are not null and in lowercase.

* * @return true, if both String are anagram */

public static boolean isAnagram(String word, String anagram){

 if(word.length() != anagram.length()){

 return false;

 }

 char[] chars = word.toCharArray();

for(char c : chars){

 int index = anagram.indexOf(c);

if(index != -1){

 anagram = anagram.substring(0,index) + anagram.substring(index +1, anagram.length());

 }

else

{

return false;

 }

 }

 return anagram.isEmpty();

 }

/* * Another way to check if two Strings are anagram or not in Java * This method assumes that both word and anagram are not null and lowercase

* @return true, if both Strings are anagram. */

 public static boolean iAnagram(String word, String anagram){

 char[] charFromWord = word.toCharArray();

 char[] charFromAnagram = anagram.toCharArray(); Arrays.sort(charFromWord);

 Arrays.sort(charFromAnagram);

 return Arrays.equals(charFromWord, charFromAnagram);

}

 public static boolean checkAnagram(String first, String second){

char[] characters = first.toCharArray();

 StringBuilder sbSecond = new StringBuilder(second);

for(char ch : characters){

 int index = sbSecond.indexOf(“” + ch);

if(index != -1){

sbSecond.deleteCharAt(index);

 }

else

{

 return false;

 }

 }

 return sbSecond.length()==0 ? true : false;

 }

 }

Java Program to Print Spiral Pattern of Numbers

public class GFG {

    public static void printSpiral(int size)

    {

        // Create row and col

        // to traverse rows and columns

        int row = 0, col = 0;

        int boundary = size – 1;

        int sizeLeft = size – 1;

        int flag = 1;

        // Variable to determine the movement

        // r = right, l = left, d = down, u = upper

        char move = ‘r’;

        // Array for matrix

        int matrix[][] = new int[size][size];

        for (int i = 1; i < size * size + 1; i++) {

            // Assign the value

            matrix[row][col] = i;

            // switch-case to determine the next index

            switch (move) {

            // If right, go right

            case ‘r’:

                col += 1;

                break;

            // if left, go left

            case ‘l’:

                col -= 1;

                break;

            // if up, go up

            case ‘u’:

                row -= 1;

                break;

            // if down, go down

            case ‘d’:

                row += 1;

                break;

            }

            // Check if the matrix

            // has reached array boundary

            if (i == boundary) {

                // Add the left size for the next boundary

                boundary += sizeLeft;

                // If 2 rotations has been made,

                // decrease the size left by 1

                if (flag != 2) {

                    flag = 2;

                }

                else {

                    flag = 1;

                    sizeLeft -= 1;

                }

                // switch-case to rotate the movement

                switch (move) {

                // if right, rotate to down

                case ‘r’:

                    move = ‘d’;

                    break;

                // if down, rotate to left

                case ‘d’:

                    move = ‘l’;

                    break;

                // if left, rotate to up

                case ‘l’:

                    move = ‘u’;

                    break;

                // if up, rotate to right

                case ‘u’:

                    move = ‘r’;

                    break;

                }

            }

        }

        // Print the matrix

        for (row = 0; row < size; row++) {

            for (col = 0; col < size; col++) {

                int n = matrix[row][col];

                System.out.print((n < 10) ? (n + ” “)

                                          : (n + ” “));

            }

            System.out.println();

        }

    }

    // Driver Code

    public static void main(String[] args)

    {

        // Get the size of size

        int size = 5;

        // Print the Spiral Pattern

        printSpiral(size);

    }

}

Output

1 2 3 4 5

16 17 18 19 6

15 24 25 20 7

14 23 22 21 8

13 12 11 10 9