Fatskills
Practice. Master. Repeat.
Study Guide: All The Useful Java Interview Questions & Answers - Part 2
Source: https://www.fatskills.com/java-programming/chapter/all-the-useful-java-interview-questions-answers-part-2

All The Useful Java Interview Questions & Answers - Part 2

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~39 min read

Java Coding Interview Questions


Q 1. What is interface in java?
An interface in the Java programming language is an abstract type that is used to specify a behaviour that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations.

Q 2. How to declare array in java?
"To declare an array, define the variable type with square brackets:

String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

String[] cars = {""Volvo"", ""BMW"", ""Ford"", ""Mazda""};
To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};"

Q 3. What is polymorphism in java?
Polymorphism is one of the OOPs features that allow us to perform a single action in different ways. For example, let's say we have a class Animal that has a method sound(). Since this is a generic class so we can't give it an implementation like Roar, Meow, Oink etc. We had to give a generic message.

public class Animal{
  ...
  public void sound(){
     System.out.println(""Animal is making a sound"");   
  }
}
Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance) Animal class. We can provide the implementation to the same method like this:

public class Horse extends Animal{
...
   @Override
   public void sound(){
       System.out.println(""Neigh"");
   }
}
and

public class Cat extends Animal{
...
   @Override
   public void sound(){
       System.out.println(""Meow"");
   }
}
As you can see that although we had the common action for all subclasses sound() but there were different ways to do the same action. This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways). It would not make any sense to just call the generic sound() method as each Animal has a different sound. Thus we can say that the action this method performs is based on the type of object."

Q 4. How to convert string to int in java?
"class Scratch{
   public static void main(String[] args){
       String str = ""50"";
       System.out.println( Integer.parseInt( str ));   // Integer.parseInt()
   }
}"

Q 5. How to convert int to string in java?
class Convert 

 public static void main(String args[]) 
 { 
   int a = 786; 
   int b = -986; 
   String str1 = Integer.toString(a); 
   String str2 = Integer.toString(b); 
   System.out.println(""String str1 = "" + str1);  
   System.out.println(""String str2 = "" + str2); 
 } 

Q 6. Why string is immutable in java?
The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of String 'ABC' to 'abc', all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviours.

Q 7. how to convert integer to string in java?
class ABC

 public static void main(String args[]) 
 { 
   int a = 789; 
   int b = 123; 
   String str1 = Integer.toString(a); 
   String str2 = Integer.toString(b); 
   System.out.println(""String str1 = "" + str1);  
   System.out.println(""String str2 = "" + str2); 
 } 

Q 8. How to compile java program?
Open a command prompt window and go to the directory where you saved the java program (MyFirstJavaProgram. java). …
Type 'javac MyFirstJavaProgram. java' and press enter to compile your code

Q 9. How to convert char to string in java?
public class CharToStringExample2{
public static void main(String args[]){
char c='M';
String s=Character.toString(c);
System.out.println(""String is: ""+s);
}}

Q 10. What is wrapper class in java?
Wrapper classes are used for converting primitive data types into objects, like int to Integer etc.

Q 11. How to iterate map in java?
import java.util.Map; 
import java.util.HashMap; 
 
class IterationDemo  

   public static void main(String[] arg) 
   { 
       Map m = new HashMap(); 
     
       // enter name/url pair 
       m.put(""a"", 1); 
       m.put(""b"", 2); 
       m.put(""c"", 3); 
       m.put(""d"", 4); 
         
       // using for-each loop for iteration over Map.entrySet() 
       for (Map.Entry entry : m.entrySet())  
           System.out.println(""Key = "" + entry.getKey() + 
                            "", Value = "" + entry.getValue()); 
   } 

Q 12. How to convert char to int in java?
public class JavaExample{  
  public static void main(String args[]){  
       char ch = '10';
       int num = Integer.parseInt(String.valueOf(ch));
               
       System.out.println(num);
  }
}

Q 13. What is an interface in java?
An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final fields (constants). A class implements an interface by providing code for each method declared by the interface.

Q 14. How to split string in java?
String string = ""004-034556"";
String[] parts = string.split(""-"");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Q 14. How to read a file in java?
import java.io.*; 
public class Read 

 public static void main(String[] args)throws Exception 
 { 
 File file = new File(""C:\\Users\\LBL\\Desktop\\test.txt""); 
 
 BufferedReader br = new BufferedReader(new FileReader(file)); 
 
 String st; 
 while ((st = br.readLine()) != null) 
   System.out.println(st); 
 } 

Q 15. How to use scanner in java?
import java.util.Scanner;

class classname{
 public methodname(){
   //Scanner declaration
   Scanner s_name = new Scanner(System.in);
   //Use Scanner to take input
   int val = s_name.nextInt();
 }
}

Q 16. How to reverse a number in java?
class Reverse
{
  public static void main(String args[])
  {
     int num=564;
     int reverse =0;
     while( num != 0 )
     {
         reverse = reverse * 10;
         reverse = reverse + num%10;
         num = num/10;
     }

     System.out.println(""Reverse  is: ""+reverse);
  }
}

Q 17. What is instance in java?
Instance variable in Java is used by Objects to store their states. Variables that are defined without the STATIC keyword and are Outside any method declaration are Object-specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.

Q 18. How to convert char array to string in java?
class CharArrayToString
{
  public static void main(String args[])
  {
     // Method 1: Using String object
     char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
     String str = new String(ch);
     System.out.println(str);

     // Method 2: Using valueOf method
     String str2 = String.valueOf(ch);
     System.out.println(str2);
  }
}

Q 19. What is maven in java?
Maven is a powerful project management tool that is based on POM (project object model). It is used for project build, dependency and documentation.

It simplifies the build process like ANT. But it is too much advanced than ANT.

Q 20. What is an array in java?
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the 'Hello World!' application.

Q 21. What is applet in java?
An applet is a special kind of Java program that runs in a Java-enabled browser. This is the first Java program that can run over the network using the browser. An applet is typically embedded inside a web page and runs in the browser.

In other words, we can say that Applets are small Java applications that can be accessed on an Internet server, transported over the Internet, and can be automatically installed and run as apart of a web document.

Q 22. What is method overriding in java?
class Human{
  //Overridden method
  public void eat()
  {
     System.out.println(""Human is eating"");
  }
}
class Boy extends Human{
  //Overriding method
  public void eat(){
     System.out.println(""Boy is eating"");
  }
  public static void main( String args[]) {
     Boy obj = new Boy();
     //This will call the child class version of eat()
     obj.eat();
  }
}

Q 22. How to check java is installed or not?
Click Start
Select Control Panel
Select Programs
Click Programs and Features
The installed Java version(s) are listed

Q 23. How to return an array in java?
import java.util.*;
public class Main
{
public static String[] return_Array() {
      //define string array
      String[] ret_Array = {""Java"", ""C++"", ""Python"", ""Ruby"", ""C""};
     //return string array
     return ret_Array;
  }

public static void main(String args[]) {
     //call method return_array that returns array   
    String[] str_Array = return_Array();
    System.out.println(""Array returned from method:"" + Arrays.toString(str_Array));

   }
}

Q 24. How to generate random number in java?
public static double getRandomNumber(){
   double x = Math.random();
   return x;
}

Q 25. What is generics in java?
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Q 26. What is a constructor in java?
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.

Q 27. How to find the length of an array in java?
class ArrayLengthFinder {
  public static void main(String[] arr) {
     // declare an array
     int[] array = new int[10];
     array[0] = 12;
     array[1] = -4;
     array[2] = 1;
     // get the length of array 
     int length = array.length;
     System.out.println(""Length of array is: "" + length);
  }
}

Q 28. What is overriding in java?
Method overriding is a process of overriding base class method by derived class method with a more specific definition.

Method overriding performs only if two classes have an is-a relationship. It means class must have inheritance. In other words, It is performed between two classes using inheritance relation.

In overriding, method of both classes must have the same name and an equal number of parameters.

Method overriding is also referred to as runtime polymorphism because the calling method is decided by JVM during runtime.

The key benefit of overriding is the ability to define a method that's specific to a particular subclass type.

Q 29. How to create a file in java?
Open a text file, save it with extension .java.

Q 30. What is an instance variable in java?
Instance variable in Java is used by Objects to store their states. Variables that are defined without the STATIC keyword and are Outside any method declaration are Object-specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.

Q 31. How to iterate hashmap in java?
import java.util.Map; 
import java.util.HashMap; 
 
class IterationDemo  

   public static void main(String[] arg) 
   { 
       Map g = new HashMap(); 
     
       // enter name/url pair 
       g.put(""1"":""One""); 
        g.put(""2"":""Two"");       
       // using for-each loop for iteration over Map.entrySet() 
       for (Map.Entry entry : g.entrySet())  
           System.out.println(""Key = "" + entry.getKey() + 
                            "", Value = "" + entry.getValue()); 
   } 

Q 32. How to split a string in java?
public class JavaExample{
  public static void main(String args[]){
    String s = "" ,ab;gh,bc;pq#kk$bb"";
    String[] str = s.split(""[,;#$]"");
        
    //Total how many substrings? The array length
    System.out.println(""Number of substrings: ""+str.length);
        
    for (int i=0; i < str.length; i++) {
        System.out.println(""Str[""+i+""]:""+str[i]);
    }
  }
}

Q 33. How to sort array in java?
public class InsertSort {
 public static void main (String [] args) {
  int [] array = {10,20,30,60,70,80,2,3,1};
  int temp;
  for (int i = 1; i < array.length; i++) {
   for (int j = i; j > 0; j--) {
    if (array[j] < array [j - 1]) {
     temp = array[j];
     array[j] = array[j - 1];
     array[j - 1] = temp;
    }
   }
  }
  for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
  }
 }
}

Q 34. Why main method is static in java?
Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class. In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.

Q 35. How to reverse a string in java word by word?
import java.util.*;
class ReverseString
{
 public static void main(String args[])
 {
   String original, reverse = """";
   Scanner in = new Scanner(System.in);

   System.out.println(""Enter a string to reverse"");
   original = in.nextLine();

   int length = original.length();

   for (int i = length - 1 ; i >= 0 ; i--)
     reverse = reverse + original.charAt(i);

   System.out.println(""Reverse of the string: "" + reverse);
 }
}

Q 36. How to convert string to date in java?
String string = ""January 2, 2010"";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(""MMMM d, yyyy"", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2010-01-02

Q 37. How to read a string in java?
Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.print(""Enter a string: "");
String str= sc.nextLine(); //reads string.

Q 38. How to convert string to integer in java?
String string1 = ""100"";
String string2 = ""50"";
String string3 = ""20"";

int number1 = Integer.decode(string1);
int number2 = Integer.decode(string2); 
int number3 = Integer.decode(string3); 

System.out.println(""Parsing String \"""" + string1 + ""\"": "" + number2);
System.out.println(""Parsing String \"""" + string2 + ""\"": "" + number2);
System.out.println(""Parsing String \"""" + string3 + ""\"": "" + number3);

Q 39. How to sort arraylist in java?
import java.util.*;
public class ArrayListOfInteger  {

    public static void main(String args[]){
       ArrayList arraylist = new ArrayList();
       arraylist.add(11);
       arraylist.add(2);
       arraylist.add(7);
       arraylist.add(3);
       /* ArrayList before the sorting*/
       System.out.println(""Before Sorting:"");
       for(int counter: arraylist){
            System.out.println(counter);
        }

       /* Sorting of arraylist using Collections.sort*/
       Collections.sort(arraylist);

       /* ArrayList after sorting*/
       System.out.println(""After Sorting:"");
       for(int counter: arraylist){
            System.out.println(counter);
        }
    }
}

Q 40. How to find the length of a string in java?
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class.

In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.

The length() method counts the total number of characters in a String.

Q 41. What is data type in java?
Data type in java specifies the type of value a variable in java can store.

Q 42. What is hashmap in java?
HashMap is a Map-based collection class that is used for storing Key & value pairs, it is denoted as HashMap or HashMap. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).

Q 43. What is stream in java?
A Stream in Java can be defined as a sequence of elements from a source. Streams supports aggregate operations on the elements. The source of elements here refers to a Collection or Array that provides data to the Stream.

Stream keeps the ordering of the elements the same as the ordering in the source. The aggregate operations are operations that allow us to express common manipulations on stream elements quickly and clearly.

Q 44. How to convert double to string in java?
public class D2S{
public static void main(String args[]){
double d=1.2222222;
String s=Double. toString(d);
System. out. println(s);
}}

Q 45. How to declare an array in java?
int arr[]=new int[10];

Q 46. How to replace a character in a string in java?
String replace(char oldChar, char newChar): It replaces all the occurrences of a oldChar character with newChar character. For e.g. 'pog pance'.replace('p', 'd') would return dog dance.

Q 47. What is lambda expression in java?
A lambda expression (lambda) describes a block of code (an anonymous function) that can be passed to constructors or methods for subsequent execution. The constructor or method receives the lambda as an argument. Consider the following example:

System.out.println('Hello')
This example identifies a lambda for outputting a message to the standard output stream. From left to right, () identifies the lambda's formal parameter list (there are no parameters in the example), -> indicates that the expression is a lambda, and System.out.println('Hello') is the code to be executed.

Q 48. What is microservices java?
Microservices are a form of service-oriented architecture style (one of the most important skills for Java developers) wherein applications are built as a collection of different smaller services rather than one whole app.

Q 49. What is jsp in java?
A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content.

The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.

The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML, though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents.

Q 50. What is the use of constructor in java?
A constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it's not a method as it doesn't have a return type. In short constructor and method are different(More on this at the end of this guide). People often refer constructor as special type of method in Java.

A constructor has same name as the class and looks like this in java code.

Q 51. How to convert list to array in java?
The best and easiest way to convert a List into an Array in Java is to use the .toArray() method.

Likewise, we can convert back a List to Array using the Arrays.asList() method.

The examples below show how to convert List of String and List of Integers to their Array equivalents.

Convert List to Array of String
import java.util.ArrayList;
import java.util.List;

public class ConvertArrayListToArray {
   public static void main(String[] args) {
       List itemList = new ArrayList();
       itemList.add(""item1"");
       itemList.add(""item2"");
       itemList.add(""item3"");

       String[] itemsArray = new String[itemList.size()];
       itemsArray = itemList.toArray(itemsArray);

       for(String s : itemsArray)
           System.out.println(s);
   }
}"

Q 52. How many ways to create object in java?
There are five different ways to create an object in Java:

Java new Operator
Java Class. newInstance() method
Java newInstance() method of constructor
Java Object. clone() method
Java Object Serialization and Deserialization

Q 53. Why java is becoming functional (java 8)?
Java 8 adds functional programming through what are called lambda expressions, which is a simple way of describing a function as some operation on an arbitrary set of supplied variables.

Q 54. Which inheritance is not supported in java?
Multiple inheritance is not supported in Java.

Q 55. How to convert double to int in java?
double d=1.2
int i=int(d)

Q 56. How to get ASCII value of char in java?
char character = 'a';    
int ascii = (int) character;
In your case, you need to get the specific Character from the String first and then cast it.

char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.

Q 57. How to declare a string array in java?
String[] array = new String[] {"a", "b"};

Q 58. What is marker interface in java?
An empty interface in Java is known as a marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behaviour with respect to the interface implemented. If you look carefully on marker interface in Java e.g. Serializable, Cloneable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. In simplest Marker interface indicate, signal or a command to Compiler or JVM.

- > Practically we can create an interface like a marker interface with no method declaration in it but it is not a marker interface at all since it is not instructing something to JVM that provides some special behaviour to the class when our program is going to execute.

For example Serializable, Cloneable etc..are marker interfaces

When my program gets executed, JVM provides some special powers to my class which has implemented the Marker Interfaces.

Q 59. How to take multiple string input in java using a scanner?
class MyClass {
   public static void main(String[ ] args) {
       Scanner a = new Scanner(System.in);
       //Scanner b = new Scanner(System.in);       
       System.out.println (a.nextLine());
       System.out.println(a.nextLine());
   }
}

Then type this way:
a
b

Q 60. How to concatenate two strings in java?
s3=s1+s2 where s1 and s2 are java strings.

Q 61. How to convert string to char array in java?
public class StringToCharArrayExample{  
public static void main(String args[]){  
String s1=""hello"";  
char[] ch=s1.toCharArray();  
for(int i=0;i System.out.print(ch[i]);  
}  
}}  

Q 62. What is type casting in java?
The process of converting the value of one data type (int, float, double, etc.) to another data type is known as typecasting.

Q 63. How to sort a string in java?
import java.util.Arrays;

public class Test
{
   public static void main(String[] args)
   {
       String original = ""edcba"";
       char[] chars = original.toCharArray();
       Arrays.sort(chars);
       String sorted = new String(chars);
       System.out.println(sorted);
   }
}

Q 64. How to input string in java?
import java.util.*;  
class Inp
{  
public static void main(String[] args)  
{  
Scanner sc= new Scanner(System.in); //System.in is a standard input stream  
System.out.print(""Enter a string: "");  
String str= sc.nextLine();              //reads string   
System.out.print(""You have entered: ""+str);             
}  
}  

Q 65. How to import scanner in java?
import java.utils.Scanner
Scanner sc=new Scanner();

Q 66. How to remove special characters from a string in java?
class New  
{  
public static void main(String args[])   
{  
String str= ""This#string%contains^special*characters&."";   
str = str.replaceAll(""[^a-zA-Z0-9]"", "" "");  
System.out.println(str);  
}  
}  

Q 67. How to find string length in java?
To figure the length of a string in Java, you can utilize an inbuilt length() technique for the Java string class.

In Java, strings are objects made utilizing the string class and the length() strategy is an open part technique for this class. Along these lines, any factor of type string can get to this strategy utilizing the . (dot) administrator.

The length() technique tallies the all outnumber of characters in a String.

Q 68. How to add elements in array in java?
Convert array to arraylist. Then elements can be added.

Q 69. What is exception handling in java?
Exception Handling in Java is a way to keep the program running even if some fault has occurred. An exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object-oriented way to handle exception scenarios, known as Java Exception Handling.

Q 70. How to scan string in java?
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print(""Enter your name: "");
String name = in.nextLine();
System.out.println(""Name is: "" + name);
in.close();

Q 71. When to use comparable and comparator in java with example?
In case one wants a different sorting order then he can implement comparator and define its own way of comparing two instances. If sorting of objects needs to be based on natural order then use Comparable whereas if your sorting needs to be done on attributes of different objects, then use Comparator in Java.

Q 72. How to create jar file in java?
The basic format of the command for creating a JAR file is:

jar cf jar-file input-file(s)
The options and arguments used in this command are:

The c option indicates that you want to create a JAR file
The f option indicates that you want the output to go to a file rather than to stdout
jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the 'input-files' are directories, the contents of those directories are added to the JAR archive recursively.
The c and f options can appear in either order, but there must not be any space between them.

Q 73. How to call a method in java?
To call a method in Java, write the method's name followed by two parentheses () and a semicolon; The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method.

Q 74. What is the difference between next () and nextline () in java?
next() can read the input only till space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line \n).

Q 75. what is mvc in java?
MVC Pattern represents the Model-View-Controller Pattern. This example is utilized to isolate the application's interests. Model - Model speaks to an item or JAVA POJO conveying information. It can likewise have a rationale to refresh regulator if its information changes.

Q 76. How to iterate a map in java?
for (Map.Entry entry : hm.entrySet()) {
   Integer key = entry.getKey();
   String value = entry.getValue();

}

Q 77. What is the diamond problem in java?
The 'diamond problem' is an uncertainty that can emerge as a result of permitting various legacy. It is a significant issue for dialects (like C++) that take into account numerous legacy of the state. In Java, nonetheless, numerous legacy doesn't take into account classes, just for interfaces, and these don't contain state.

Q 78. How to swap two strings in java?
String a = ""one"";
String b = ""two"";

a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());

System.out.println(""a = "" + a);
System.out.println(""b = "" + b);

Q 79. How to convert string to date in java in yyyy-mm-dd format?
String start_dt = ""2011-01-01"";
DateFormat formatter = new SimpleDateFormat(""yyyy-MM-DD""); 
Date date = (Date)formatter.parse(start_dt);
SimpleDateFormat newFormat = new SimpleDateFormat(""MM-dd-yyyy"");
String finalString = newFormat.format(date);

Q 80. What is getname in java with example?
import java.io.*; 
 
public class solution { 
   public static void main(String args[]) 
   { 
 
       // try-catch block to handle exceptions 
       try { 
 
           // Create a file object 
           File f = new File(""new.txt""); 
 
           // Get the Name of the given file f 
           String Name = f.getName(); 
 
           // Display the file Name of the file object 
           System.out.println(""File Name : "" + Name); 
       } 
       catch (Exception e) { 
           System.err.println(e.getMessage()); 
       } 
   } 

getName returns the name of the file.

Q 81. What is bufferreader in java?
The Java.io.BufferedReader
class peruses text from a character-input stream, buffering characters to accommodate the proficient perusing of characters, clusters, and lines. Following are the significant focuses on BufferedReader − The cradle size might be determined, or the default size might be utilized.

Q 82. How to create a package in java?
To make a bundle, you pick a name for the bundle (naming shows are talked about in the following area) and put a bundle articulation with that name at the head of each source record that contains the sorts (classes, interfaces, lists, and explanation types) that you need to remember for the bundle.

Q 83. What is aggregation in java?
The case of Aggregation is Student in School class when School shut, Student despite everything exists and afterwards can join another School or something like that. In UML documentation, a structure is signified by a filled precious stone, while conglomeration is indicated by an unfilled jewel, which shows their undeniable distinction regarding the quality of the relationship.

Q 84. How to use switch case in java?
int amount = 9;

switch(amount) {
   case     0 : System.out.println(""amount is  0""); break;
   case     5 : System.out.println(""amount is  5""); break;
   case    10 : System.out.println(""amount is 10""); break;
   default    : System.out.println(""amount is something else"");
}

Q 85. What is recursion in java?
Recursion is simply the strategy of settling on a capacity decision itself. This method gives an approach to separate entangled issues into straightforward issues which are simpler to settle.

Q 86. How to print array in java?
System.out.println(Arrays.toString(a));

Q 87. What is autoboxing and unboxing in java?
Autoboxing
is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Q 88. A java constructor returns a value, but what?
Java constructor does not return any values.

Q 89. What is method overloading in java?
Method Overloading is a feature that allows a class to have more than one method having the same name if their argument lists are different. It is similar to constructor overloading in Java, that allows a class to have more than one constructor having different argument lists.

Q 90. How to create an array of objects in java?
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

Q 91. When to use abstract class and interface in java?
Java provides four types of access specifiers that we can use with classes and other entities.

These are:

1. Default: Whenever a specific access level is not specified, then it is assumed to be 'default'. The scope of the default level is within the package.

2. Public: This is the most common access level and whenever the public access specifier is used with an entity, that particular entity is accessible throughout from within or outside the class, within or outside the package, etc.

3. Protected: The protected access level has a scope that is within the package. A protected entity is also accessible outside the package through inherited class or child class.

4. Private: When an entity is private, then this entity cannot be accessed outside the class. A private entity can only be accessible from within the class.

Q 92. How to create singleton class in java?
Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private so that you can restrict the creation of the object. Provide a static method to get an instance of the object, wherein you can handle the object creation inside the class only. In this example, we are creating an object by using a static block.

public class MySingleton {

   private static MySingleton myObj;
    
   static{
       myObj = new MySingleton();
   }
    
   private MySingleton(){
    
   }
    
   public static MySingleton getInstance(){
       return myObj;
   }
    
   public void testMe(){
       System.out.println(""Hey.... it is working!!!"");
   }
    
   public static void main(String a[]){
       MySingleton ms = getInstance();
       ms.testMe();
   }
}

Q 93. What is a static method in java?
Java Programming Java8Object Oriented Programming. The static keyword is used to create methods that will exist independently of any instances created for the class. Static methods do not use any instance variables of any object of the class they are defined in.

Q 94. Explain the exception handling mechanism of Java.
Exception class inherits from the Throwable class in java. Java has a try-catch mechanism for handling exceptions without them being generated as errors.

public class Exception_Handling { 
   String gender; 
   Exception_Handling(String s){ 
       gender=s; 
   } 
    void Check_Gender(String s) throws GenderException{ 
       if (gender!="Male" || gender!="Female") 
           throw new GenderException("Gender Invalid"); 
       else 
       System.out.println("Gender valid"); 
       } 
   public static void main(String args[]){ 
       Exception_Handling n=new Exception_Handling("None"); 
       try{ 
           n.Check_Gender("Female"); 
       }catch (Exception e){ 
           System.out.println("Exception : "+e); 
       } 
   } 
   } 
class GenderException extends Exception{ 
   GenderException(String s){ 
       super(s); 
   } 

Q 95. When do we use the Array list?
Whenever there is a need for random access of elements in java we use ArrayList. Get and set methods provide really fast access to the elements using the array list.

Q 96. What is the use of generics in Java?
Generics allow classes and interfaces to be a type for the definition of new classes in java which enables stronger type checking. It also nullifies the probability of type mismatch of data while insertion.

Q 97. What is an iterator?
An iterator is a collection framework functionality which enables sequential access of elements. The access can be done in one direction only. Java supports two types of iterators:

1. Enumeration Iterator

2. List Iterator

Q 98. What is a hashmap?
Hashmap is a collection framework functionality which is used for storing data into key-value pairs. To access data we need the key. A hashmap uses linked lists internally for supporting the storage functionality.

Q 99. What is a stack?
A stack is a data structure that supports LAST IN FIRST OUT methodology. The element pushed last is at the top of the stack. A stack supports the following functionality:

Push-operation to push an element into the stack
Pop-operation to push an element out of the stack
Peek-An option to check the top element

Q 100. What is a treemap?
Treemap is a navigable map interpretation in java which is built around the concepts of red and black trees. The keys of a treemap are sorted in ascending order by their keys.

Q 101. What is a vector?
A vector is an ArrayList like data structure in java whose size increases as per the demands. Moreover, it also supports some legacy functions not supported by collections.
You should also know that a vector is more suitable to work with threads, unlike collection objects.

Q 102. What is the difference between ArrayList and vector?
An ArrayList is not suitable for working in a thread based environment. A vector is built for thread-based executions. ArrayList does not support legacy functions whereas a vector has support for legacy functions.

Learn in Demand Skills for free on GL Academy

Q 103. Write a program to calculate the factorial of a number in java.
import java.util.Scanner; 

public class star { 
    public static void main(String[] args) { 
        Scanner sc=new Scanner(System.in); 
        int fact=1; 
        int n=sc.nextInt(); 

        for (int i=1;i<=n;i++) 
        fact=fact*i; 

        System.out.println(fact); 

       } 

Q 104. Write a program to check if a number is prime.
import java.util.Scanner; 
public class star { 
    public static void main(String[] args) { 
        Scanner sc=new Scanner(System.in); 
        int n=sc.nextInt(); 
        int count=0; 
        for (int i=1;i<=n;i++) 
        { 
            if (n%i==0) 
            count++; 
        } 
        if (count==2) 
        System.out.println("Prime"); 
        else 
        System.out.println("Not Prime"); 
       } 

Q 105. Write a program to convert decimal numbers to binary.
import java.util.Scanner; 

class star 

public static void main(String arg[])    
{    
   Scanner sc=new Scanner(System.in); 
   System.out.println("Enter a decimal number"); 
   int n=sc.nextInt(); 
   int  bin[]=new int[100]; 
   int i = 0; 
   while(n > 0) 
   { 
   bin[i++] = n%2; 
      n = n/2; 
   } 
  System.out.print("Binary number is : "); 
   for(int j = i-1;j >= 0;j--) 
  { 
      System.out.print(bin[j]); 
  } 

Q 106. Write a program to convert decimal numbers to octal.
import java.util.Scanner; 
class star 

 public static void main(String args[]) 
 { 
   Scanner sc = new Scanner( System.in ); 
   System.out.print("Enter a decimal number : "); 
   int num =sc.nextInt(); 
   String octal = Integer.toOctalString(num); 
   System.out.println("Decimal to octal: " + octal); 
 } 

Q 107. Which utility function can be used to extract characters at a specific location in a string?
The charAt() utility function can be used to achieve the above-written functionality.

Q 108. How to get the length of a string in java?
Length of string in java can be found using the .length() utility.

Q 109. Which of the following syntax for defining an array is correct?
-  Int []=new int[];
-  int a[]=new int[];
-  int a[] =new int [32]

int a[]=new int[32] is the correct method.

Q 110. What will this return 3*0.1 == 0.3? true or false?
This is one of the really tricky questions and can be answered only if your concepts are very clear. The short answer is false because some floating-point numbers can not be represented exactly.

Q 111. Write a program to do bubble sort on an array in java.
import java.util.Scanner; 
class star 

 public static void main(String args[]) 
 { 
   int arr[] =new int [10]; 
   Scanner sc = new Scanner( System.in ); 
   System.out.println("Enter size of array"); 
   int n=sc.nextInt(); 
   System.out.print("Enter an arry : "); 
   for (int i=0;i        arr[i]=sc.nextInt(); 
   for (int i=0;i    { 
       for (int j=0;j        { 
           if (arr[j]>arr[j+1]) 
           { 
               int t=arr[j]; 
               arr[j]=arr[j+1]; 
               arr[j+1]=t; 
           } 
       } 
   } 
for (int i=0;i    { 
       System.out.println(arr[i]); 
   } 
 } 

Q 112. Write a program to generate the following output in java?
*
**
****
*****
******
public class star { 
    public static void main(String[] args) { 
        int i; 
        int count=1; 
       for (i=1;i<=5;i++){ 
           for (int j=1;j<=i;j++) 
               System.out.print("*"); 
           System.out.println(" "); 

       } 


Q 113. Write a program to generate the following output.
****
***
**
*
public class star { 
    public static void main(String[] args) { 
        int i; 
        int count=1; 
       for (i=5;i>=1;i--){ 
           for (int j=1;j<=i;j++) 
               System.out.print("*"); 
           System.out.println(" "); 

       } 


Q 114. Write a program in java to remove all vowels from a string.
import java.util.Scanner; 

public class star { 
    public static void main(String[] args) { 
        Scanner sc=new Scanner(System.in); 
        String n=sc.nextLine(); 
        String n1=n.replaceAll("[AEIOUaeiou]", ""); 
        System.out.println(n1); 

        } 
       } 

Q 115. Write a program in java to check for palindromes.
String str, rev = ""; 
     Scanner sc = new Scanner(System.in); 

     System.out.println("Enter a string:"); 
     str = sc.nextLine(); 

     int length = str.length(); 

     for ( int i = length - 1; i >= 0; i-- ) 
        rev = rev + str.charAt(i); 

     if (str.equals(rev)) 
        System.out.println(str+" is a palindrome"); 
     else 
        System.out.println(str+" is not a palindrome"); 

Q 116. What is the underlying mechanism in java's built-in sort?
Java's built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works best in most real-life scenarios and has no extra space requirements.

Q 117. Which utility function is used to check the presence of elements in an ArrayList?
hasNext() is used for the presence of the next element in an ArrayList.

Q 118. How to remove an element from an array?
To remove an element from an array we have to delete the element first and then the array elements lying to the right of the element are shifted left by one place.

Q 119. Difference between a = a + b and a += b?
The += operator implicitly cast the result of addition into the type of the variable used to hold the result. When you add two integral variables e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If the result of the addition is more than the maximum value of a then a + b will give a compile-time error but a += b will be ok as shown below
byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok

 

Also see:

All The Useful Java Interview Questions & Answers - Part 1
All The Useful Java Interview Questions & Answers - Part 3