在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:learning-zone/java-interview-questions开源软件地址:https://github.com/learning-zone/java-interview-questions开源编程语言:Java 100.0%开源软件介绍:Java, J2EE, JSP, Servlet, Hibernate Interview QuestionsClick if you like the project. Pull Request are highly appreciated. Table of Contents
Q. What are the types of Exceptions? Explain the hierarchy of Java Exception classes?Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Types of Java Exceptions 1. Checked Exception: The classes which directly inherit Hierarchy of Java Exception classes Example: import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class CustomExceptionExample {
public static void main(String[] args) throws MyException {
try {
processFile("file.txt");
} catch (MyException e) {
processErrorCodes(e);
}
}
private static void processErrorCodes(MyException e) throws MyException {
switch(e.getErrorCode()){
case "BAD_FILE_TYPE":
System.out.println("Bad File Type, notify user");
throw e;
case "FILE_NOT_FOUND_EXCEPTION":
System.out.println("File Not Found, notify user");
throw e;
case "FILE_CLOSE_EXCEPTION":
System.out.println("File Close failed, just log it.");
break;
default:
System.out.println("Unknown exception occured," +e.getMessage());
e.printStackTrace();
}
}
private static void processFile(String file) throws MyException {
InputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION");
} finally {
try {
if(fis !=null) fis.close();
} catch (IOException e) {
throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION");
}
}
}
} Q. What is the difference between aggregation and composition?Aggregation: We call aggregation those relationships whose objects have an independent lifecycle, but there is ownership, and child objects cannot belong to another parent object. Example: Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes public class Organization {
private List employees;
}
public class Person {
private String name;
} Composition: We use the term composition to refer to relationships whose objects don’t have an independent lifecycle, and if the parent object is deleted, all child objects will also be deleted. Example: Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. public class Car {
//final will make sure engine is initialized
private final Engine engine;
public Car(){
engine = new Engine();
}
}
class Engine {
private String type;
}
Note: "final" keyword is used in Composition to make sure child variable is initialized. Q. What is difference between Heap and Stack Memory in java?Java Heap Space Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application. Java Stack Memory Stack in java is a section of memory which contains methods, local variables and reference variables. Local variables are created in the stack. Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. Difference
Q. What is JVM and is it platform independent?Java Virtual Machine (JVM) is a specification that provides runtime environment in which java bytecode(.class files) can be executed. The JVM is the platform. The JVM acts as a "virtual" machine or processor. Java's platform independence consists mostly of its Java Virtual Machine (JVM). JVM makes this possible because it is aware of the specific instruction lengths and other particularities of the platform (Operating System). The JVM is not platform independent. Java Virtual Machine (JVM) provides the environment to execute the java file(. Class file). So at the end it's depends on kernel and kernel is differ from OS (Operating System) to OS. The JVM is used to both translate the bytecode into the machine language for a particular computer and actually execute the corresponding machine-language instructions as well. Q. What is JIT compiler in Java?The Just-In-Time (JIT) compiler is a component of the runtime environment that improves the performance of Java applications by compiling bytecodes to native machine code at run time. Java programs consists of classes, which contain platform-neutral bytecodes that can be interpreted by a JVM on many different computer architectures. At run time, the JVM loads the class files, determines the semantics of each individual bytecode, and performs the appropriate computation. The additional processor and memory usage during interpretation means that a Java application performs more slowly than a native application. The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time. The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it. Q. What is Classloader in Java? What are different types of classloaders?The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. Types of ClassLoader a) Bootstrap Class Loader: It loads standard JDK class files from rt.jar and other core classes. It loads class files from jre/lib/rt.jar. For example, java.lang package class. b) Extensions Class Loader: It loads classes from the JDK extensions directly usually c) System Class Loader: It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options. Q. Java Compiler is stored in JDK, JRE or JVM?JDK: Java Development Kit is the core component of Java Environment and provides all the tools, executables and binaries required to compile, debug and execute a Java Program. JVM: JVM is responsible for converting Byte code to the machine specific code. JVM is also platform dependent and provides core java functions like memory management, garbage collection, security etc. JVM is customizable and we can use java options to customize it, for example allocating minimum and maximum memory to JVM. JVM is called virtual because it provides an interface that does not depend on the underlying operating system and machine hardware. JRE: Java Runtime Environment provides a platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. Q. What is the difference between factory and abstract factory pattern?The Factory Method is usually categorised by a switch statement where each case returns a different class, using the same root interface so that the calling code never needs to make decisions about the implementation. For example credit card validator factory which returns a different validator for each card type. public ICardValidator GetCardValidator (string cardType)
{
switch (cardType.ToLower())
{
case "visa":
return new VisaCardValidator();
case "mastercard":
case "ecmc":
return new MastercardValidator();
default:
throw new CreditCardTypeException("Do not recognise this type");
}
} Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern. Q. What are the methods used to implement for key Object in HashMap?1. equals() and 2. hashcode() Class inherits methods from the following classes in terms of HashMap
Q. What is difference between the Inner Class and Sub Class?Nested Inner class can access any private instance variable of outer class. Like any other instance variable, we can have access modifier private, protected, public and default modifier. class Outer {
class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
} A subclass is class which inherits a method or methods from a superclass. class Car {
//...
}
class HybridCar extends Car {
//...
} Q. Can we import same package/class two times? Will the JVM load the package twice at runtime?We can import the same package or same class multiple times. The JVM will internally load the class only once no matter how many times import the same class. Q. Distinguish between static loading and dynamic class loading?Static Class Loading: Creating objects and instance using class TestClass {
public static void main(String args[]) {
TestClass tc = new TestClass();
}
} Dynamic Class Loading: Loading classes use Class.forName (String className); Q. What is the difference between transient and volatile variable in Java?Transient: The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type. public transient int limit = 55; // will not persist
public int b; // will persist Volatile: The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. public class MyRunnable implements Runnable {
private volatile boolean active;
public void run() {
active = true;
while (active) {
}
}
public void stop() {
active = false;
}
} Q. How many types of memory areas are allocated by JVM?JVM is a program which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM perform some particular types of operations:
Types of Memory areas allocated by the JVM: 1. Classloader: Classloader is a subsystem of JVM that is used to load class files. Q. What will be the initial value of an object reference which is defined as an instance variable?The object references are all initialized to Q. How can constructor chaining be done using this keyword?Java constructor chaining is a method of calling one constructor with the help of another while considering the present object. It can be done in 2 ways –
// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp() {
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x) {
// calls constructor 3
this(10, 20);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y) {
System.out.println(10 + 20);
}
public static void main(String args[]) {
// invokes default constructor first
new Temp();
}
} Ouput:
// Java program to illustrate Constructor Chaining to
// other class using super() keyword
class Base
{
String name;
// constructor 1
Base() {
this("");
System.out.println("No-argument constructor of base class");
}
// constructor 2
Base(String name) {
this.name = name;
System.out.println("Calling parameterized constructor of base");
}
}
class Derived extends Base
{
// constructor 3
Derived() {
System.out.println("No-argument constructor of derived");
}
// parameterized constructor 4
Derived(String name) {
// invokes base class constructor 2
super(name);
System.out.println("Calling parameterized constructor of derived");
}
public static void main(String args[]) {
// calls parameterized constructor 4
Derived obj = new Derived("test");
// Calls No-argument constructor
// Derived obj = new Derived();
}
} Output:
Q. Can you declare the main method as final?Yes. We can declare main method as final. But, In inheritance concept we cannot declare main method as final in parent class. It give compile time error. The main method has to be public because it has to be called by JVM which is outside the scope of the package and hence would need the access specifier-public. public class Test {
public final static void main(String[] args) throws Exception {
System.out.println("This is Test Class");
}
}
class Child extends Test {
public static void main(String[] args) throws Exception {
System.out.println("This is Child Class");
}
} Output
Q. What is the difference between the final method and abstract method?Final method is a method that is marked as final, i.e. it cannot be overridden anymore. Just like final class cannot be inherited anymore. Abstract method, on the other hand, is an empty method that is ought to be overridden by the inherited class. Without overriding, you will quickly get compilation error. Q. What is the difference between compile-time polymorphism and runtime polymorphism?There are two types of polymorphism in java:
Example of static Polymorphism Method overloading is one of the way java supports static polymorphism. Here we have two definitions of the same method add() which add method would be called is determined by the parameter list at the compile time. That is the reason this is also known as compile time polymorphism. class SimpleCalculator
{
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class Demo
{
public static void main(String args[]) {
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}
} Output:
Runtime Polymorphism (or Dynamic polymorphism) It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, thats why it is called runtime polymorphism. class ABC {
public void myMethod() {
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC {
public void myMethod() {
System.out.println("Overriding Method");
}
public static void main(String args[]) {
ABC obj = new XYZ();
obj.myMethod();
}
} Output:
全部评论
专题导读
上一篇:LaunchCodeEducation/techjobs-console-java: Assignment for the Java skill track a ...发布时间:2022-06-23下一篇:xuanfenglv/java: java后台开发发布时间:2022-06-23热门推荐
热门话题
阅读排行榜
|
请发表评论