By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Java Interview Questions: Basics
Q 1. What are the basics of Java? Java is a object-oriented general-purpose programming language. It is a popular programming language because of it's easy-to-use syntax. The basics of Java include understanding what Java is, how to install Java and Java IDE, variables and data types in Java, Operators in Java, Arrays, Functions, Flow Control Statements, and basic programs. To learn the basics of Java, you can take up a Java for Beginners Course and understand the concepts required for you to build a successful career in Java Programming.
Q 2. Why is string immutable in Java? String is immutable in Java to ensure that the value of the string does not change. Java uses string literals, if there are multiple variables that refer to one object and the value of the object is changed, it would affect all reference variables. Hence, strings are immutable in Java.
Q 3. Why pointers are not used in Java? Java doesn't allow using pointers. Pointers are not used in Java to ensure that it is more secure and robust.
Q 4. Is Java 100% object oriented language? No. Java is not a 100% object oriented language. It follows some principles of object oriented language, but not all.
Q 5. What are the features of Java? The main features of Java include: multithreaded, platform independent, simple, secure, architecture neutral, portable, robust, dynamic, high-performance, and interpreted.
Q 6. What is API in Java? In Java, API stands for Application Programming Interface. It is a software that allows two applications to talk to each other. It is a list of classes that is part of a JDK or Java Development Kit and includes interfaces, packages, classes, fields, methods and constructors.
Q 7. What is Java? Java is a general-purpose programming language that is class-based, object-oriented and is very popular. It's one of the most popular programming languages in the world.
Java is a programming language that is originally developed by James Gosling at Sun Microsystems.
While the developers were drinking coffee and brainstorming names for their programming language, they chose to name it Java back in 1995. It does not have any full form.
For Beginners
Q. 1. Hello World in Java:
public class FileName { public static void main(String args[]) { System.out.println("Hello World!"); } }
Q 2. How to install Java? Install Java through command prompt so that it can generate necessary log files to troubleshoot the issue.
Go to java.com and click on the Free Java Download button.
Click on the Save button and save Java software on the Desktop
Verify that Java software is saved on the desktop.
Open Windows Command Prompt window.
Windows XP: Click Start -> Run -> Type: cmd
Windows Vista and Windows 7: Click Start -> Type: cmd in the Start Search field. cd (for example Downloads or Desktop etc.)
IRun the installer and follow onscreen instructions.
Q 3. How to reverse a string in Java? "String str = ""Hello""; String reverse(String str){ StringBuilder sb = new StringBuilder(); sb.append(str); sb.reverse(); return sb.toString(); }"
Q 4. What is thread in Java? Threads allow a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main program.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class MyClass extends Thread { public void run() { System.out.println("This code is running in a thread"); } }
Q 5. How to take input in Java? "Scanner in = new Scanner(System.in); System.out.print(""Please enter hour 1: ""); int hour1 = in.nextInt(); System.out.print(""Please enter hour 2: ""); int hour2 = in.nextInt(); System.out.print(""Please enter minute 1: ""); int min1 = in.nextInt(); System.out.print(""Please enter minute 2: ""); int min2 = in.nextInt();"
Q 6. How to set path in Java? Windows 10 and Windows 8
In Search, search for and then select: System (Control Panel) Click the Advanced system settings link. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK. Reopen Command prompt window, and run your java code. Mac OS X To run a different version of Java, either specify the full path or use the java_home tool:
% /usr/libexec/java_home -v 1.8.0_73 - exec javac -version
Solaris and Linux
To find out if the path is properly set: In a terminal windows, enter: % java -version This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set. Determine which java executable is the first one found in your PATH In a terminal window, enter: % which java
Q 7. What is enumeration in Java? Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is public, static and final by default. Even though enumeration defines a class type and have constructors, you do not instantiate an enum using new. Enumeration variables are used and declared in much a same way as you do a primitive variable.
Q 8. What is inheritance in Java? The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from another class.
Child Class: The class that extends the features of another class is known as child class, sub class or derived class.
Parent Class: The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.
Q 9. How to compare two strings in Java? "// These two have the same value new String(""test"").equals(""test"") // --> true
// ... but they are not the same object new String(""test"") == ""test"" // --> false
// ... neither are these new String(""test"") == new String(""test"") // --> false
// ... but these are because literals are interned by // the compiler and thus refer to the same object ""test"" == ""test"" // --> true "
Q 10. What is abstraction in Java? Objects are the building blocks of Object-Oriented Programming. An object contains some properties and methods. We can hide them from the outer world through access modifiers. We can provide access only for required functions and properties to the other programs. This is the general procedure to implement abstraction in OOPS.
Q 11. What is encapsulation in java? The idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.
However if we setup public getter and setter methods to update (for example void setName(String Name ))and read (for example String getName()) the private data fields then the outside class can access those private data fields via public methods.
Q 12. What is collection in java? Collections are like containers that group multiple items in a single unit. For example, a jar of chocolates, list of names, etc.
Collections are used in every programming language and when Java arrived, it also came with few Collection classes - Vector, Stack, Hashtable, Array.
Q 13. What is api in java? Java application programming interface (API) is a list of all classes that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. These pre-written classes provide a tremendous amount of functionality to a programmer.
Q 14. How to initialize array in java? "int[] arr = new int[5]; // integer array of size 5 you can also change data type String[] cars = {""Volvo"", ""BMW"", ""Ford"", ""Mazda""};"
Q 15. How to take input from user in java? "import java.util.Scanner; Scanner console = new Scanner(System.in); int num = console.nextInt(); console.nextLine() // to take in the enter after the nextInt() String str = console.nextLine();"
Q 16. What is static in java? In Java, a static member is a member of a class that isn't associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.
Q 17. What is package in java? A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:
Built-in Packages (packages from the Java API) User-defined Packages (create your own packages)
Q 18. How to sort an array in java? "import java. util. Arrays; Arrays. sort(array);"
Q 19. What is an abstract class in java? A class that is declared using the 'abstract' keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods.
Q 20. What is method in java? A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
Q 21. How to check java version? Execute java -version on a command prompt/terminal.
Q 22. What is a class in java? A class- the basic building block of an object-oriented language such as Java- is a template that describes the data and behaviour associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behaviour associated with a class or object is implemented with methods.
Q 23. What is core java? 'Core Java' is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE. Also, note that they're talking about a set of libraries rather than the programming language.
Q 24. How to enable java in chrome? In the Java Control Panel, click the Security tab Select the option Enable Java content in the browser Click Apply and then OK to confirm the changes Restart the browser to enable the changes
Q 25. What is string in java? String is a sequence of characters, for e.g. 'Hello' is a string of 5 characters. In java, string is an immutable object which means it is constant and cannot be changed once it has been created.
Q 26. What is exception in java? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible 'somethings' to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.
Q 27. Why multiple inheritance is not supported in java? Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but can extend only one class. Multiple inheritance is not supported because it leads to a deadly diamond problem.
Q 28. How to take string input in java? "import java.util.Scanner; // Import the Scanner class
class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println(""Enter username"");
String userName = myObj.nextLine(); // Read user input System.out.println(""Username is: "" + userName); // Output user input } }"
Q 29. What is singleton class in java? The singleton design pattern is used to restrict the instantiation of a class and ensures that only one instance of the class exists in the JVM. In other words, a singleton class is a class that can have only one object (an instance of the class) at a time per JVM instance.
Q 30. What is 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. This section discusses arrays in greater detail.
Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array.
An array of 10 elements. Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
Q 31. What is garbage collection in java? Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification. Although there are many JVMs, Oracle's HotSpot is by far the most common. It offers a robust and mature set of garbage collection options.
Q 32. Why we need encapsulation in java? Encapsulation in Java is a mechanism of wrapping the code and data (variables)acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class.
Q 33. What is jvm in java? A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes what is required in a JVM implementation.
Q 34. What is java programming? Java is a powerful general-purpose programming language. It is used to develop desktop and mobile applications, big data processing, embedded systems, and so on. According to Oracle, the company that owns Java, Java runs on 3 billion devices worldwide, which makes Java one of the most popular programming languages.
Q 35. How hashmap works internally in java? HashMap in Java works on hashing principles. It is a data structure which allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap.
Q 36. Who invented java? Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle) and released in 1995 as a core component of Sun Microsystems' Java platform.
Q 37. How to execute a java program? Open a command prompt window and go to the directory where you saved the java program (HelloWorld. java). … Type 'javac HelloWorld. java' and press enter to compile your code. Now, type ' HelloWorld ' to run your program. You will be able to see the result printed on the window.
Q 38. How to get input from user in java? "import java.util.Scanner; // Import the Scanner class
Q 39. What is bytecode in java? Bytecode is the compiled format for Java programs. Once a Java program has been converted to bytecode, it can be transferred across a network and executed by Java Virtual Machine (JVM). Bytecode files generally have a .class extension.
Q 40. How to set classpath in java? Select Start, select Control Panel, double click System, and select the Advanced tab. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK.
Q 41. How to connect database in java? Install or locate the database you want to access. Include the JDBC library. Ensure the JDBC driver you need is on your classpath. Use the JDBC library to obtain a connection to the database. Use the connection to issue SQL commands.
Q 42. What is enum in java? An enum is a special 'class' that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma.
Q 43. How to uninstall java? Click Start Select Settings Select System Select Apps & features Select the program to uninstall and then click its Uninstall button Respond to the prompts to complete the uninstall
Q 44. How to find duplicate characters in a string in java? "public class Example { public static void main(String argu[]) { String str = ""beautiful beach""; char[] carray = str.toCharArray(); System.out.println(""The string is:"" + str); System.out.print(""Duplicate Characters in above string are: ""); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (carray[i] == carray[j]) { System.out.print(carray[j] + "" ""); break; } } } } }"
Q 45. How to take character input in java? "import java.util.Scanner; public class CharacterInputExample1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(""Input a character: ""); // reading a character char c = sc.next().charAt(0); //prints the character System.out.println(""You have entered ""+c); } } "
Q 46. how to read string in java? "import java.util.Scanner; // Import the Scanner class
Q 47. How to round off numbers in java? "import java.lang.Math; // Needed to use Math.round()
class Program { public static void main( String args[] ) { double num1 = 74.65; System.out.println(Math.round(num1));
float num2 = 1337.345523f; System.out.println(Math.round(num2)); } }"
Q 48. How to get current date in java? "DateFormat df = new SimpleDateFormat(""dd/MM/yy HH:mm:ss""); Date dateobj = new Date(); System.out.println(df.format(dateobj));"
Q 49. What is dao in java? Dao is a simple java class which contains JDBC logic. The Java Data Access Object (Java DAO) is an important component in business applications. Business applications almost always need access to data from relational or object databases and the Java platform offers many techniques for accessing this data.
Q 50. What is awt in java? The Abstract Window Toolkit (AWT) is Java's original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the Java Foundation Classes (JFC) - the standard API for providing a graphical user interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME profiles. For example, Connected Device Configuration profiles require Java runtimes on mobile telephones to support the Abstract Window Toolkit.
Q 51. What is framework in java? Frameworks are large bodies (usually many classes) of prewritten code to which you add your own code to solve a problem in a specific domain. Perhaps you could say that the framework uses your code because it is usually the framework that is in control. You make use of a framework by calling its methods, inheritance, and supplying 'callbacks', listeners, or other implementations of the Observer pattern.
Q 52. How to update java? Manually updating Java on Windows is typically done through the Java Control Panel.
Windows 10: Type 'java' into the Windows/Cortana search box, located in the lower left-hand corner of your screen. When the pop-out menu appears select Configure Java, located in the Apps section.
Q 53. How to run java program in command prompt? execute java
Q 54. What is variable in java? A Java variable is a piece of memory that can contain a data value. A variable thus has a data type. Data types are covered in more detail in the text on Java data types. Variables are typically used to store information which your Java program needs to do its job.
Q 55. What is the difference between java and javascript? The main differences between JavaScript and Java are:
1. JavaScript is used for Front End development while java is used for Back End Development. i.e.
JavaScript is responsible for the dynamic behaviour of a webpage. Mainly, JavaScript handles events, cookies, ajax (Asynchronous JavaScript and XML), etc. in a website. JavaScript is the heart of a Dynamic User Interface of a Web Page while Java is the best programming language for software engineers and can be used with JSP (Java Server pages) for handling back end.
2. Java Script is dynamically typed language and Java is Statically typed language: i.e
In JavaScript, datatype of one variable can be changed:
var string = 'hello world'; string = 4; document.write(string); //OUTPUT IS 4 document.write( ) will now print '4′ on the browser.
But in Java, the datatype of one variable cannot be changed and Java shows the error.
int number = 45; number = 'hello world'; //ERROR!!!!!!!
3. JavaScript is a scripting language while Java is a programming language:
Like other languages, Java also needs a compiler for building and running the programs while JavaScript scripts are read and manipulated by the browser.
4. Java and JavaScript are very different in their SYNTAX.
For example:
Hello World Program in JAVA:
public class hello { public static void main(String[] args) { System.out.println("Hello World"); } } Hello World Program in JavaScript:
5. Both languages are Object Oriented but JavaScript is a Partial Object Oriented Language while Java is a fully Object Oriented Langauge. JavaScript can be used with or without using objects but Java cannot be used without using classes.
Q 56. How to count the number of occurrences of a character in a string in java? "import java.util.HashMap;
public class EachCharCountInString { private static void characterCount(String inputString) { //Creating a HashMap containing char as a key and occurrences as a value HashMap charCountMap = new HashMap(); //Converting given string to char array char[] strArray = inputString.toCharArray(); //checking each char of strArray for (char c : strArray) { if(charCountMap.containsKey(c)) { //If char 'c' is present in charCountMap, incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c)+1); } else { //If char 'c' is not present in charCountMap, //putting 'c' into charCountMap with 1 as it's value charCountMap.put(c, 1); } } //Printing inputString and charCountMap System.out.println(inputString+"" : ""+charCountMap); } public static void main(String[] args) { characterCount(""Java J2EE Java JSP J2EE""); characterCount(""All Is Well""); characterCount(""Done And Gone""); } }"
Q 57. how to read excel file in java? "FileInputStream fis = new FileInputStream(new File(""WriteSheet.xlsx""));
XSSFWorkbook workbook = new XSSFWorkbook(fis); XSSFSheet spreadsheet = workbook.getSheetAt(0); Iterator < Row > rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) { row = (XSSFRow) rowIterator.next(); Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) { Cell cell = cellIterator.next();
switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "" \t\t ""); break;
case Cell.CELL_TYPE_STRING: System.out.print( cell.getStringCellValue() + "" \t\t ""); break; } } System.out.println(); } fis.close();"
Q 58. What is a method in java? Functions are also known as methods in java.
Q 59. How to read csv file in java? "public static void readDataLineByLine(String file) { try { // Create an object of filereader // class with CSV file as a parameter. FileReader filereader = new FileReader(file); // create csvReader object passing // file reader as a parameter CSVReader csvReader = new CSVReader(filereader); String[] nextRecord; // we are going to read data line by line while ((nextRecord = csvReader.readNext()) != null) { for (String cell : nextRecord) { System.out.print(cell + ""\t""); } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } "
Q 60. How to check java version in windows? type java -version on command prompt.
Q 61. What is public static void main in java? This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it's not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public. Let's see what happens if we define the main method as non-public.
When java runtime starts, there is no object of the class present. That's why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won't be static, JVM would not be able to call it because there is no object of the class is present.
Java programming mandates that every method provide the return type. Java main method doesn't return anything, that's why it's return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give compilation error as an unexpected return value.
Q 62. Why we use interface in java? It is used to achieve total abstraction. Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance . It is also used to achieve loose coupling. Interfaces are used to implement abstraction.
Q 63. What is the purpose of serialization in java? Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization.
Q 64. What is functional interface in java? A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.
Q 65. What is this keyword in java? The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Q 66. How was java initially named? The language was at first called Oak after an oak tree that remained external Gosling's office. Later the task passed by the name Green and was at last renamed Java, from Java , a coffee brand, the coffee from Indonesia.
Q 67. How to remove duplicate elements from array in java? "public class Change { public static int removeDuplicate(int[] arrNumbers, int num) { if(num == 0 || num == 1) { return num; } int[] arrTemporary = new int[num]; int b = 0; for(int a = 0; a < num - 1; a++) { if(arrNumbers[a] != arrNumbers[a + 1]) { arrTemporary[b++] = arrNumbers[a]; } } arrTemporary[b++] = arrNumbers[num - 1]; for(int a = 0; a < b; a++) { arrNumbers[a] = arrTemporary[a]; } return b; } public static void main(String[] args) { int[] arrInput = {1, 2, 3, 3, 4, 5, 5, 6, 7, 8}; int len = arrInput.length; len = removeDuplicate(arrInput, len); // printing elements for(int a = 0; a < len; a++) { System.out.print(arrInput[a] + "" ""); } } } "
Q 68. What is difference between throw and throws in java? Throw is a keyword which is used to throw an exception explicitly in the program inside a function or inside a block of code. Throws is a keyword used in the method signature used to declare an exception which might get thrown by the function while executing the code.
Q 69. What is classpath in java? The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)
Q 70. Why is Java Platform Independent? At the time of compilation, the java compiler converts the source code into a JVM interpretable set of intermediate form, which is termed as byte code. This is unlike the compiled code generated by other compilers and is non-executable. The java virtual machine interpreter processes the non-executable code and executes it on any specific machine. Hence the platform dependency is removed.
Q 71. What is Method overloading? Why is it used in Java? Method overriding is a process in which methods inherited by child classes from parent classes are modified as per requirement by the child class. It's helpful in hierarchical system design where objects share common properties.
Example: Animal class has properties like fur colour, sound. Now dog and cat class inherit these properties and assign values specific to them to the properties.
class Animal { void sound(){ } } class Cat extends Animal{ void sound(){ System.out.println("Meow"); } }
class Dog extends Animal{ void sound(){ System.out.println("Bark"); } }
public class OverRide{ public static void main(String args[]){ Cat c=new Cat(); c.sound();
Dog d=new Dog(); d.sound(); } }
Q 72. What is Method overloading? Why is it used in Java? If multiple functions in a class have the same name but different function definitions it is called method overloading. It is used to make a java function serve multiple purposes making the code cleaner and API less complex. Example:
println() prints any data type passed to it as a string.
public class Add_Overload { void add(int x, int y){ System.out.println(x+y); } void add(double x, double y){ System.out.println(x+y); } void add(double x, int y){ System.out.println(x+y); } public static void main(String args[]){ Add_Overload a= new Add_Overload(); a.add(10,20); a.add(20.11,11.22); a.add(20.11,2);
}
Q 73. Why is Java Robust? Java is termed as robust because of the following features: - Lack of pointers: Java does not have pointers which make it secure - Garbage Collection: Java automatically clears out unused objects from memory which are unused - Java has strong memory management. - Java supports dynamic linking.
Q 74. Why is Java Secure? Java does not allow pointers. Pointers give access to actual locations of variables in a system. Also, java programs are bytecode executables that can run only in a JVM. Hence java programs do not have access to the host systems on which they are executing, making it more secure. Java has its own memory management system, which adds to the security feature as well.
Q 75. What is the difference between JDK, JRE, and JVM? JDK is a software environment used for the development of Java programs. It's a collection of libraries that can be used to develop various applications. JRE (Java Runtime Environment) is a software environment that allows Java programs to run. All java applications run inside the JRE. JVM (java virtual machine) is an environment that is responsible for the conversion of java programs into bytecode executables. JDK and JRE are platform-dependent whereas JVM is platform-independent.
Q 76. What are the features of Java? Java is a pure Object Oriented Programming Language with the following features: - High Performance - Platform Independent - Robust - Multi-threaded - Simple - Secure
Q 77. Does Java Support Pointers? Pointers are not supported in java to make it more secure.
Q 78. Why are Static variables used in Java? Static methods and variables are used in java to maintain a single copy of the entity across all objects. When a variable is declared as static it is shared by all instances of the class. Changes made by an instance to the variable reflect across all instances.
public class static_variable {
static int a; static int b; static_variable(){ a=10; } int calc_b(){ b=a+10; return b; } void print_val(){ System.out.println(this.b); } public static void main(String args[]){ static_variable v=new static_variable(); v.calc_b(); v.print_val(); static_variable v1=new static_variable(); v1.print_val(); } }
Q 79. What are static methods, static variables, and static blocks? Static methods are methods that can be called directly inside a class without the use of an object. Static variables are variables that are shared between all instances of a class. Static blocks are code blocks that are loaded as the class is loaded in memory.
Q 80. What's the use of static methods? Static methods are used when there is no requirement of instantiating a class. If a method is not going to change or overridden then it can be made static.
Q 81. What's the use of static variables? Static variables are used for maintaining a common state of certain data which is modifiable and accessible by all instances of a class.
Q 82. What are the interfaces? An interface is a collection of constants, static methods, abstract methods, and default methods. Methods in an interface do not have a body.
Q 83. How is Abstraction achieved in Java? Abstraction is achieved in Java by the use of abstract class and abstract methods.
Q 84. Why are strings immutable in Java? Strings in java are frequently used for hashmap keys. Now if someone changes the value of the string it will cause severe discrepancies. Hence strings are made immutable.
Q 85. What are wrapper classes in Java? Wrapper classes are a functionality supported by java to accept primitive data types as inputs and then later convert those into string objects so that they can be compared to other objects.
Q 86. Can interfaces in Java be inherited? Yes, interfaces can be inherited in java. Hybrid inheritance and hierarchical inheritance are supported by java through inheritable interfaces.
Q 87. Are static methods allowed in a Java interface? Yes, static methods are allowed in java interfaces. They are treated as default methods so they need not be implemented.
Q 88. How is garbage collection done in Java? Java has an automatic built-in garbage collection mechanism in place. Apart from the built-in mechanism, manual initiation of garbage collection can also be done by using the gc() of system class.
Q 89. Can there be two main methods in a class? Yes, there can be two main methods. This also means that the main method is overloaded. But at the time of execution, JVM only calls the original main method and not the overloaded main method.
Q 90. Can private variables be inherited? Private variables have a class-specific scope of availability. They can only be accessed by the methods of the class in which they are present. Hence when the class is inherited, private variables are not inherited by the subclass.
Q 91. Can the size of an array be increased after declaration? The size of a java array cannot be increased after declaration. This is a limitation of Java arrays.
Q 92. What is the size of the below array in memory? int a[]=new int[10]; Each int block takes a size of 4 bytes and there are 10 such blocks in the array. Hence, the size the array takes in memory is 40 bytes.
Q 93. How many data types does java support? Java supports 8 primitive data types, namely byte, short, int, long, float, double, char, boolean.
Q 94. How to find out the ASCII value of a character in java? int c=char('A') would give the ASCII value of A in java.
Q 95. How to get a string as user input from the console? We have to instantiate an input reader class first. There are quite a few options available, some of which are BufferedReader, InputStreamReader Scanner. Then the relative functionality of the class can be used. One of the most prevalently used is nextLine() of Scanner class.
Q 96. How to check the size of strings? The size of strings in java can be checked by using the length() function.
Q 97. How can we sort a list of elements in Java? The built-in sorting utility sort() can be used to sort the elements. We can also write our custom functions but it's advisable to use the built-in function as its highly optimized.
Q 98. If we sort a list of strings how would be the strings arranged?
The strings would be arranged alphabetically in ascending order.
Q 99. The difference between throw and throws in Java? Throw is used to actually throw an instance of java.lang.Throwable class, which means you can throw both Error and Exception using throw keyword e.g.
throw new IllegalArgumentException("size must be multiple of 2")
On the other hand, throws is used as part of method declaration and signals which kind of exceptions are thrown by this method so that its caller can handle them. It's mandatory to declare any unhandled checked exception in throws clause in Java. Like the previous question, this is another frequently asked Java interview question from errors and exception topic but too easy to answer.
Q 100. Can we make an array volatile in Java? Yes, you can make an array volatile in Java but only the reference which is pointing to an array, not the whole array. What I mean, if one thread changes the reference variable to points to another array, that will provide a volatile guarantee, but if multiple threads are changing individual array elements they won't be having happens before guarantee provided by the volatile modifier.
Q 101. Can I store a double value in a long variable without casting? No, you cannot store a double value into a long variable without casting because the range of double is more than long and we need to type cast. It's not difficult to answer this question but many developer get it wrong due to confusion on which one is bigger between double and long in Java.
Q 102. Which one will take more memory, an int or Integer? An Integer object will take more memory as Integer is an object and it stores metadata overhead about the object but int is a primitive type, so it takes less space.
Q 103. The difference between nested static class and top-level class? A public top-level class must have the same name as the name of the source file, there is no such requirement for a nested static class. A nested class is always inside a top-level class and you need to use the name of the top-level class to refer nested static class e.g. HashMap.Entry is a nested static class, where HashMap is a top-level class and Entry is nested, static class.
Q 104. What is the use of the final keyword? The final keyword is used to declare the final state of an entity in java. The value of the entity cannot be modified at a later stage in the application. The entity can be a variable, class, object, etc. It is used to prevent unnecessary modifications in a java application.
Q 105. What's the difference between deep copy and shallow copy? Shallow copy in java copies all values and attributes of an object to another object and both objects reference the same memory locations.
Deep copy is the creation of an object with the same values and attributes of the object being copied but both objects reference different memory locations.
Q 106. What's the use of default constructor? The default constructor is a constructor that gets called as soon as the object of a class is declared. The default constructor is un-parametrized. The generic use of default constructors is in the initialization of class variables.
class ABC{ int i,j; ABC(){ i=0; j=0; } } Here ABC() is a default constructor.
Q 107. What is object cloning? Object cloning is the process of creating an exact copy of an object of a class. The state of the newly created object is the same as the object used for cloning. The clone() method is used to clone objects. The cloning done using the clone method is an example of a deep copy.
Q 108. Why are static blocks used? They serve the primary function of initializing the static variables. If multiple static blocks are there they are executed in the sequence in which they are written in a top-down manner.
Q 109. What is the use of this keyword in java? This keyword is used to reference an entity using the current object in java. It's a multi-purpose keyword which serves various functionalities
Q 110. What's the difference between String and String Builder class in java? Strings are immutable while string Builder class is mutable. The string builder class is also synchronized.
Q 111. How to calculate the size of an object? The size of an object can be calculated by summing the size of the variables of the class the object is instantiated from. If a class has an integer, a double variable defined in it then the size of the object of the class is size(int)+size(double). If there is an array, then the size of the object would be the length of array*size of data type of array.
Q 112. What's the difference between == and .equals()? '==' is an operator, whereas .equals() is a function. '==' checks if the references share the same location, whereas .equals() checks if both object values are the same on evaluation.
Java Interview Questions: Advanced
Q 1. What is serialization in java? Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization.
Q 2. What is synchronization in java? Synchronization is a process of handling resource accessibility by multiple thread requests. The main purpose of synchronization is to avoid thread interference. At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronization keyword in java creates a block of code referred to as a critical section.
Q 3. What is spring in java? The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE (Enterprise Edition) platform.
Q 4. How to create immutable class in java? Declare the class as final so it can't be extended. Make all fields private so that direct access is not allowed. Don't provide setter methods for variables. Make all mutable fields final so that its value can be assigned only once. Initialize all the fields via a constructor performing the deep copy. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
Q 5. What is servlet in java? A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
Q 6. What is xname class in java? An Expanded Name, comprising of a (discretionary) namespace name and a nearby name. XName examples are changeless and might be shared.
Q 7. Can static methods reference non-static variables? Yes, static methods can reference non-static variables. It can be done by creating an object of the class the variable belongs to.
Q 8. How do static blocks get executed if there are multiple static blocks? Multiple static blocks are executed in the sequence in which they are written in a top-down manner. The top block gets executed first, then the subsequent blocks are executed.
Q 9. Can we override static methods? Static methods cannot be overridden because they are not dispatched to the object instance at run time. In their case, the compiler decides which method gets called.
Q 10. Which class do all classes inherit from in java? All classes in java inherit from the Object class which is the superclass of all classes.
Q 11. What is classloader? ClassLoader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.
Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using '-cp' or '-classpath' switch. It is thus also known as Application classloader.
Q 12. The difference between Serializable and Externalizable in Java? Serializable interface is used to make Java classes serializable so that they can be transferred over a network or their state can be saved on disk, but it leverages default serialization built-in JVM, which is expensive, fragile and not secure. Externalizable allows you to fully control the Serialization process, specify a custom binary format and add more security measure.
Q 13. Can we use String in the switch case? We can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detailed answer for more explanation and discussion.
Q 14. What are object serialization and deserialization? The use of java.io.Serializable to convert an object into a sequence of bytes is known as object serialization. Deserialization is the process of recovering back the state of the object from the byte stream.
Q 15. The difference between checked and unchecked exception in Java? A checked exception is checked by the compiler at compile time. It's mandatory for a method to either handle the checked exception or declare them in their throws clause. These are the ones which are a subclass of Exception but doesn't descend from RuntimeException. The unchecked exception is the descendant of RuntimeException and not checked by the compiler at compile time. This question is now becoming less popular and you would only find this with interviews with small companies, both investment banks and startups are moved on from this question.
Q 16. Is ++ operator is thread-safe in Java? No, it's not a thread-safe operator because it involves multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.
Q 17. Which class contains the clone method? Cloneable or Object? java.lang.Cloneable is a marker interface and doesn't contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it's implemented in C or C++ or any other native language.
Also see:
All The Useful Java Interview Questions & Answers - Part 2
All The Useful Java Interview Questions & Answers - Part 3
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.