Java Code Examples for Interview
In this article, we have presented Basic Java Interview Questions with answers. You must practice these questions as the starting points for Coding Interviews.
Practice more Java questions:
- Java Interview Questions: with detailed answers Book
- Learn Java in one day: Practical approach for Coding Interview Book
- 50+ Java Interview Questions: Predict the Output
- 30+ Advanced Java Interview Questions: Descriptive
Try out these Basic Java Interview Questions:
When was Java released?
- 1996
- 2000
- 1995
- 2011
Answer: 1995
Java was first released in 23 May 1995 as a part of Sun Microsystem's Java platform.
What is the most common application of Java?
- Desktop applications
- Client Server web applications
- Web Servers
- Scripts
Answer: Client Server web applications
Client Server web applications is the most common application of Java. Over 9M programmers use Java actively for these applications. Java was marketed as a cross platform programming language and hence, was the driving force.
As of March 2022, what is the latest version of Java?
- Java 8
- Java SE
- Java 21
- Java 17
Answer: Java 17
Java 17 is the latest version which was released in October 2021. There are 3 long term supported versions of Java namely Java 8, Java 11 and Java 18.
Who owns Java?
- Sun Microsystems
- Oracle
- Microsoft
Answer: Oracle
As of 2022, Oracle owns Java. Java was originally developed and owned by Sun Microsystems who had the copyright on the name "Java" as well.
In 2009, Oracle acquired Sun Microsystems for $7.4B and Java came under Oracle.
Who was the core designer of Java?
- Mike Sheridan
- Patrick Naughton
- James Gosling
- Graydon Hoare
Answer: James Gosling
James Gosling is the core designer of Java who was the driving force behind the first release of Java in 1995. Mike Sheridan and Patrick Naughton were involved in the Java project from the beginning which started in 1991.
James Gosling left Oracle in 2010.
What is the Java controversy between Oracle and Google?
Anroid which is a major project of Google internally leveraged the codebase of Java. Even though most of the code has been rewritten by Google developers to suit their usecase, the API remains same as Java.
As Java was modified without the permission of Oracle who owns Java, Oracle registered a legal case against Google. The case continued for over a decade and is in active state. The major points are:
- If API can be copyrighted, then Google has done copyright infringement regarding Oracle's Java. It is in active discussion if API can be copyrighted but no conclusion has been formed.
- 2 rulings were in favor of Google and 1 was in favor of Oracle.
Name two environment variables that should be set to run Java programs.
The two environment variables are:
- PATH
- CLASSPATH
These should be set to compile and run the Java programs.
Is Java a OOP language?
- Yes
- No
Answer: No
Java is not a pure Object Oriented Programming Language. This is because Java supports 8 primitive data types like Int, float, char and others which does not fit in the definition of OOP.
Hence, Java is not a pure OOP language.
What is wrapper class in Java?
Wrapper class in Java is a class that is used to convert a primitive datatype to an object. For example, if the primitive data type in "int", then the corresponding wrapper class in "Integer".
A wrapper class is used as follows;
public class Code { public static void main(String args[]) { int data = 1; Integer wrapperData = Integer.valueOf(data); } }
What is package in Java?
Package is a collection of classes, interfaces, libraries and JAR files which enables code reuse. It enables access protection and prevents naming conflicts.
Example of using a package in Java:
package examplePackage; public class Code { public static void main(String args[]) { System.out.println("Java Interview"); } }
How to compile and run a Java program with a package?
If a Java program with filename "Code.java" and class name "Code" is within a package named "OG", then the compilation command will be:
javac -d directory Code.java
directory is the path of the package. It is this location where the compiled file will be placed.
To run the compiled class, use the following command:
java OG.Code
If there was no specific package, then the command to run the compiled class would be:
java Code
Can a constructor return a value?
In Java, a contructor cannot return a value explicitly.
Implicitly, a constructor in Java can update the current Class instance and in this way, it can stimulate the behaviour of returning a value.
What is super keyword in Java?
Super keyword is a reference keyword in Java that is used to refer to the immediate parent class. It can be used to invoke the parent class constructor with super() and refer to the parent class instance variable or method.
What is this keyword in Java?
this keyword is a reference keyword in Java like super keyword. this keyword is used to refer to the current class instance variable, method and constructor.
Example use of this keyword:
public int setData(int data) { this.data = data; return this.data; }
What is the life cycle of a thread in Java?
The five stages of the life cycle of a thread in Java are:
- New Born State
- Runnable State
- Running State
- Blocked State
- Dead State
What is the life cycle of a Java applet?
The five stages of the life cycle of an applet in Java are:
- Initialization
- Start
- Stop
- Destroy
- Paint
What are the types of access specifiers in Java?
The four types of access specifiers in Java are:
- Public Access Specifier
- Private Access Specifier
- Protected Access Specifier
- Default Access Specifier
Following image summarizes the differences:
What are the types of constructors in Java?
There are two types of constructors in Java:
- Parameterized Constructors: accept the parameters
- Default Constructors: does not accept the parameters
Which package is used to find the size of an object in Java?
Answer: java.lang.instrument.Instrumentation
Instrumentation package in Java is used to instrument any Java code and get details of it. It is a common analysis technique which is natively supported in Java using the package. In short, in this technique, we insert code to the original code to track changes and performance. As changes are inserted, the original code remains unimpacted and hence, it is a good analysis tool.
To import this package, we need to use this:
import java.lang.instrument.Instrumentation;
We have to create a Java class named ObjectSize to implement this. We can create a sizeof() function as follows:
public static long sizeof(Object o) { return instrumentation.getObjectSize(o); }
Which keyword is used to make resources thread-safe ?
- wait
- sleep
- synchronized
- notify
Answer: synchronized
synchronized keyword is used to attain a lock on a resource, and make it thread-safe.
The threads go into which state if they do not get the desired resource ?
- resumed
- active
- terminated
- waiting
Answer: waiting
The thread goes into waiting state, if it does not get its desired resource.
What is Static Initialization Block in Java?
A static block in a program is a set of statements which are executed by the JVM (Java Virtual Machine) before the main method. Java does not care if this block is written after the main() method or before the main() method, it will be executed before the main method() regardless.
public class Sample { static{ System.out.println("Hello World"); System.exit(0); } }
Note:
This code is working only on java versions up to 1.6. A newer version of Java does not support this feature anymore. We have to include the main method in our class with the static block.
What are the different types of control statements in Java?
Java has 3 different types of control statements:
-
Selection statements: These statements give the option of choosing a different path of execution of a program depending on the result of a test condition. The expressions in this group are if, if-else and switch statement.
-
Iteration statements: These statements allow repeated evaluation of a statement or a block of statements if the test condition is satisfied. This group contains a statement such as a while, do-while, for and for-each.
-
Jump statements: These statements make the program control jump to another part of the program forward or backward directions with or without a test condition. The statements in this group are break, break label, continue.
What are the different types of References in Java?
There are 4 types of reference in Java Language:
- Strong Reference
- Weak Reference
- Soft Reference
- Phantom Reference
What is Soft Reference in Java?
Soft References are a special kind of reference, which slightly changes the default behavior of the Garbage Collector, allowing the GC to maintain objects without strong references until the Java Virtual Machine runs out of memory. In this last case, the Garbage Collector will try to save the application scanning the memory and deleting all the soft references.
Code snippet of Soft Reference in Java:
import java.lang.ref.* // ... Object obj = new Object(); // New Soft Reference to obj object SofReference<Object> softRef = new SoftReference<Object>(obj);
Strings are immutable in Java. What are the advantages?
The advantages of having Strings as immutable in Java includes:
- Caching
- Hashcode Caching
- Better Performance
- Synchronization
- Security
What is Anonymous class?
Java Anonymous inner class is an inner class without a name and for which only a single object is created. It works just like the local class, all restrictions remain the same for its members.
You can declare the following inside an anonymous class.
- Property (fields)
- Methods (Only instance methods), even if they do not implement any methods of the supertype.
- Instance initializer
- Local classes
What is Double brace initialization?
Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization.First brace is creation of an anonymous inner class.Second brace is an initialization block. When you use the initialization block for an anonymous inner class it becomes java double brace initialization.
Let us see its implementation:
/*Here we will create a list in which the elements are stored with the help of double brace initialization.*/ import java.util.*; public class Main{ public static void main(String[] args){ List <Integer> list = new ArrayList<>() {{ // Double Brace Initialization add(56); add(67); add(90); add(78); add(35); }}; // print the list System.out.println(list); } }
Output:
[56, 67, 90, 78, 35]
What is encapsulation?
The wrapping up of data and functions(that operate on the data) into a single unit (called class) is known as encapsulation
The only way to access the data is provided by the function (that are combined along with the data). These functions are called member functions or methods in Java. The data cannot be accessed directly.If you want to read a dataitem in an object(an instance of class), you call a member function in the object.It will read the item and return the value to you.You can't access the data directly.The data is hidden, so it is safe from accidental alteration.Data and its functions are said to be encapsulated into a single entity.
How to create a directory in Java?
To create a directory:
- Create the object of the File class by passing the path of the directory, as a parameter (String) to the constructor of the File class
- call the mkdir() method using the above created file object
Example of Java code to create a directory using mkdir() method.
import java.io.File; public class CreateDirectory{ public static void main(String args[]){ //creating a File object File file = new File(F:\\program); //creating the directory boolean bool = file.mkdir(); if(bool){ System.out.println("Directory created successfully"); }else{ System.out.println("Directory not created"); } } }
How to delete non empty Folders Recursively in Java?
In Java, we cannot delete folder that are not empty. The workaround is to delete all files first using delete() utility and then, recursively delete empty folders using delete() utility starting from the inner most folders.
delete() function can be used recursively to delete non-empty folders/ directory. We can define a recursive function named recursiveDelete() which will:
- check if the current location is a file or folder
- If it is a file, then it will be deleted
- If it is an empty folder, it will be deleted
- If it is not an empty folder, it will go through all objects within the folder and apply the function recursively
Follow this function carefully:
import java.io.File; public class DeleteFolderRecursively { public static void main(String[] args) { String folder = "F:\\program"; //delete folder recursively recursiveDelete(new File(folder)); } public static void recursiveDelete(File file) { //to end the recursive loop if (!file.exists()) return; //if directory, go inside and call recursively if (file.isDirectory()) { for (File f : file.listFiles()) { //call recursively recursiveDelete(f); } } //call delete to delete files and empty directory file.delete(); System.out.println("Deleted file/folder: "+file.getAbsolutePath()); } }
With this article at OpenGenus, you must have a good practice of basic Java Interview questions.
Source: https://iq.opengenus.org/basic-java-interview-questions/
0 Response to "Java Code Examples for Interview"
Post a Comment