Skip to main content

100 latest Java interview questions and answers. What are most common interview question in java ?

 100 latest Java interview questions, a summary of common interview questions and answers

 


Q1: What is the difference between Java internal classes and subclasses?

 Answer: An inner class means to define a class inside an outer class. The inner class has access rights to the outer class and can access all the variables and methods defined in the class.

 A subclass is a class inherited from a superclass. The subclass can access all the public and protected fields and methods of the superclass.

 

Q2: What are the common access specifiers in Java language and what are their meanings?

 Answer: The access specifier in Java is a keyword used to define the access range before the class name. Common access specifiers include the following categories:

Public: Public, which can be accessed by any Class, Method, and Field in the project.

Protected: Protected, can be accessed by the same or sub-categories, but cannot be accessed from the outside.

Default: By default, it can only be accessed by Class, Method, and Field of the same package.

Private: Private, can only be accessed by this class.

 

Q3: What is the purpose of static methods and static variables?

Answer: Static variables are shared by all instances of the class. Static classes can only access the static variables of the class or call the static methods of the class.

 

Q4: What is data encapsulation and its meaning?

Answer: Encapsulation is used in object-oriented programming to combine attributes and methods in a single unit.

Encapsulation can help programmers follow a modular approach to software development. Each object has its own set of methods and variables, and can perform its functions independently of other objects. In addition, encapsulation also has the purpose of data hiding.

 

Q5: What is a singleton class (singleton class)? And give practical examples of its usage.

Answer: A singleton class can only have one instance, you must create your own unique instance, and you must provide this instance to all other objects.

The best practice for singleton usage scenarios is to connect to the database only due to certain driver restrictions or due to licensing issues.

 

Q6: What is a loop? What are the loops in Java?

 

Answer: Loops are used to repeatedly execute statements in programming. There are three types of loops in Java:

A. For loop

The for loop is used to execute the statement with the specified number of repetitions. When the programmer knows the number of loops, the for loop can be used.

B.While loop

 When the statement meets the condition, it starts to execute repeatedly until the statement no longer meets the condition and exits the loop. In the While loop, check whether the condition is met before executing the statement.

C.. Do while loop

Do while and while loop are basically similar, the only difference is that do while executes the statement first and then checks the condition, which means that the do while loop will execute the statement at least once.

 

Q7: What is an infinite loop? How to declare an infinite loop?

Answer: Infinite loop refers to unconditional execution and infinite operation. The infinite loop can be ended by defining an interrupt statement block.


Q8: What is the difference between continue and break statements?

 Answer: Both break and continue are important keywords in the loop. The break statement ends the entire loop process. The continue statement only ends this loop, not the execution of the entire loop.

 Break

 Continue

 

Q9: What is the difference between double and float variables in Java?

Answer: Float is a single-precision floating-point number, which occupies 4 bytes in memory, and double is a double-precision floating-point number, which occupies 8 bytes in memory.

 

Q10: What does the Final keyword in Java mean? Please give an example

Answer: Final is a keyword in Java, meaning "unchangeable" and "final state". The final class cannot be inherited and has no subclasses. The methods in the final class are final by default and cannot be overridden by the methods of subclasses. , But can be inherited.

The final member variable represents a constant and can only be assigned once, and the value does not change after the assignment. final cannot be used to modify the constructor.

 In the following example, const_val is declared and assigned the constant 100:

 Private Final int const_val=100

 When a method is declared as final, it cannot be overridden by subclasses, and it will be faster than other methods.

 

Q11: Illustrate what is a ternary operator?

 Answer: The ternary operator, also known as the conditional operator, decides which value to assign to the variable based on the Boolean value, which is represented as...? …:…

In the example below, if rank is 1, status=Done, otherwise status=Pending


Q12: How to generate random numbers in Java?

 Answer: Use Math.random() to generate random numbers in the range of 0.1 to 1.0, and then use mathematical methods to generate random numbers that meet the requirements.

 

Q13: Give an example of what is the default switch case?

 Answer: In the switch statement, if no case condition matches, it will execute the statement following default.

 In the following example, when the score is neither 1 nor 2, the statement after default will be executed.

 

Q14: What is the base class of all derived classes in Java?

 Answer: java.lang.object

 

Q15: Can the main() method in Java return any data?

 Answer: The main() method in java cannot return any data, and its return type is always void.

 

Q16: What are Java Packages? What is its meaning?

 Answer: In order to organize classes better, Java provides a package mechanism to distinguish the namespace of class names.

 The role of the package:

A. Organize classes or interfaces with similar or related functions in the same package to facilitate the search and use of classes.

B.. Like folders, packages also use a tree-shaped directory storage method. Class names in the same package are different, and the names of classes in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.

C. The package also restricts access rights, and only classes with package access rights can access classes in a package.

 

Q17: We can declare an abstract class, but there is no abstract method?

 Answer: Yes, we can declare an abstract class without any abstract methods, but once a class contains an abstract method, then the class must be declared as abstract.

 

Q18: What is the difference between abstract classes and interfaces in Java?

Answer: The main difference between an abstract class and an interface is that an abstract class can have any range of member data, as well as its own non-abstract methods, but in the interface mode, it can only have static and unmodifiable member data. At the same time, all its methods must be abstract.

An abstract class is an abstraction of a class, and an interface is an abstraction of behavior. An abstract class abstracts the entire class as a whole, including attributes and behaviors, but an interface abstracts part of the class (behavior).

 A class can implement multiple interfaces, but it can only extend one abstract class.

 

Q19: What is the impact of interfaces on the performance of abstract classes?

 Answer: Compared with abstract classes, interface performance is slower. A class can only extend one abstract class, but it can implement many interfaces. As the interface is implemented in the class, it will also bring additional burdens to developers.

 

Q20: When importing a package in Java, will its sub-packages be imported?

 Answer: When importing a package in Java, its sub-packages will not be imported. If necessary, the developer must import it separately. Developers need to import them separately.

 

Q21: Can the main method in a class be declared as private?

 Answer: The main method in Java must be public. If it is private, although it will not fail at compile time, it will fail at runtime.

 

Q22: Can we pass parameters to the function by reference?

 Answer: No, we can only pass values ​​to functions by reference.

 

Q23: How to serialize objects in java?

 Answer: Serialization refers to the process of converting Java objects into byte sequences. Only objects that support the java.io.Serializable interface can be written into the stream, and the class of each serializable object is encoded.

 

Q24: Is try...catch in Java used for exception handling?

 Answer: try is often followed by catch or finally. Any exceptions thrown by try will be caught in catch, and the tasks to be executed before the code terminates are placed in finally.

 

Q25: Is there any way to skip finally when an exception occurs?

 Answer: When an exception occurs in the try, if there is a catch, it will be caught by the catch first, otherwise it will be executed to finally. When an exception occurs, finally will definitely be executed, unless there is a forced termination code at the end of the try: System.exit(0);

 

Q26: When will the constructor of the class be called?

 Answer: Every time new is used to create an object, the constructor is called.

 For example, in the following example, new creates two objects, and the constructor is called twice.

 

Q27: Can a class have multiple constructors?

 Answer: Yes, a class can have multiple constructors with different parameters. The constructor for creating an object depends on the parameters passed when creating the object.

 

Q28: Can we override the static method of a class?

 Answer: We cannot override static methods. Static methods belong to a class rather than a single object, and are resolved at compile time (not at runtime).

 

Q29: In the following example, what is the output?

Answer: The output is:

Displaying from subclass

Displaying from superclass

 

Q30: Is String a Java data type?

 Answer: String is not a primitive data type of Java. When a string is created in Java, an object of the Java.Lang.String class is actually created. This object can use all the built-in methods of the String class.

 

Q31: In the following example, how many String objects are created in total?

 Answer: A total of two java.Lang.String objects are created. s1 and s3 are references to the same object.

 

Q32: Why is String in Java called Immutable?

 Answer: In Java, the string object is immutable. Once the value is assigned, it cannot be changed. If it is changed, a new object will be created.

 In the following example, str is a string object with the value "Value One":

When a new value is assigned, a new String object will be created and the reference will be moved to the new object. :

 

Q33: What is the difference between array and vector?

 Answer: An array is a combination of data of the same primitive type, which is static in nature, while a vector is dynamic in nature and can accommodate data of different data types.

 

Q34: What is multithreading?

Answer: Multithreading is a programming concept that can perform multiple tasks concurrently in a single program. The stack sharing of multiple threads in the same process helps to improve the performance of the program.

 

Q35: Why use Runnable Interface in ava?

 Answer: The Runnable interface is used to implement multithreaded applications in Java. The Java.Lang.Runnable interface is implemented by a class that supports multithreading.

 

Q36: What are the two ways to achieve multithreading in Java?

 Answer:

 1. Through the use of Java.Lang.Runnable Interface, through the Run () method to enable multi-threading.

B. Write a class that extends Java.Lang.Thread class.

 

Q37: When the data needs to be changed a lot, which is the better choice of String or StringBuffer?

 Answer: StringBuffers are dynamic in nature. We can change the value of StringBuffer objects, but String is immutable. Every time data changes, a new String object is created, which increases additional overhead. Therefore, in the case of a lot of data changes, StringBuffer Is a better choice.

 

Q38: What is the purpose of using break after each switch statement?

 Answer: Switch can use break to interrupt after executing this statement. If break is not used, then it will execute all situations again.

 

Q39: How to complete garbage collection in Java?

 Answer: In Java, when an object is not referenced, garbage collection will occur, and the object will be automatically destroyed, calling the System.gc() method or Runtime.gc() method.

 

Q40: Can the code be executed before the Main() method?

 Answer: If we want to execute a statement before the object is created when the class is loaded, we can use a static code block in the class, so that even before the object is created in the main method, the statements in this static code block will be executed once when the class is loaded .

 

Q41: Can a class be both a parent class and a child class at the same time? Please give an example?

 Answer: If an inheritance hierarchy is used, then this class may be both the parent class of one class and the subclass of another class. The continental class in the following example is both the subclass of the world class and the parent class of the country class.

 

Q42: If there is no constructor defined in the class, how will the objects of the class be created?

 Answer: Even if the class does not define an explicit constructor, the object will execute an implicit constructor when it is created, and the constructor has no parameters.

 

Q43: In multi-threading, how to ensure that resources will not be used by multiple threads at the same time?

 Answer: In multithreading, you can control access to resources shared between multiple threads by using the concept of synchronization. Using the synchronized keyword, we can ensure that only one thread can use shared resources for a period of time.

 

Q44: Can we call the constructor of the class multiple times for the object?

 Answer: When using new to create an object, the constructor is automatically called. After the object is created, the constructor can no longer be called.

 

Q45: The two classes classA and classB are in the same package. Can the private members of classA be accessed by objects of classB?

 Answer: The private members of a class are inaccessible outside the scope of the class, even in the same package and cannot be accessed by any other class.

 

Q46: Can methods with the same name be defined in the same class?

 Answer: You can define a method with the same name, but the number and types of its parameters are different. Which method is called depends on the parameters passed.

 For example, in the following class, we have two printing methods with the same name but different parameters. Based on the parameters, the appropriate parameters will be called:

 

Q47: How to make a copy of a Java object?

 Answer: Using cloning, we can create a copy with the actual state of the object. Clone() is a method of Cloneable interface, so you need to implement Cloneable interface to copy objects.

 

Q48: What are the benefits of using inheritance?

 Answer: The main advantage of using inheritance is the reusability of code, because inheritance enables subclasses to reuse the code of their parent class. Polymorphism (scalability) is another benefit, allowing the introduction of new features without affecting existing derived classes.

 

Q49: What is the default access specifier for class variables and methods?

 Answer: The default access specifier for variables and methods is protected, that is, variables and classes can be used in any other class in the same package.

 

Q50: Give an example of using pointers in Java classes.

 Answer: There are no pointers in Java.

 

Q51: How to restrict a class from being inherited?

 Answer: Use the keyword Final.

 In the following example, the Stone class cannot be inherited.

 

Q52: What is the access scope of the access specifier?

 Answer:

 

Q53: What is the difference between stack and queue?

 Answer: The main difference between a stack and a queue is that the stack is based on the "Last In First Out (LIFO)" principle, while the queue is based on the FIFO (First In First Out) principle.

 

Q54: How do we prohibit serialization of variables in Java?

 Answer: If you want certain variables not to be serialized, you can use the keyword transient in the declaration. For example, the following variable trans_var is a temporary variable and cannot be serialized:

 

Q55: How do we use primitive data types as objects?

 Answer: Java advocates "everything is an object". Reference data types can be instantiated as objects, but basic data types cannot become objects. In response to this shortcoming, a wrapper class is set in JAVA. For example, Integer is the primitive data type int. Packaging category.

 

Q56: What types of exceptions will be encountered during compilation?

 Answer: The checked exception can be caught when the program is compiled. In order to successfully compile the code, the exception will be handled by try...catch.

 

Q57: Please describe the different states of threads.

 Answer: Threads in Java are often in one of the following states

 NEW: Created an object of the Thread class (or its subclasses) through the New keyword

RUNNABLE: This situation refers to the object of the Thread class called the start () method, the thread is in the ready state.

RUNNING: The thread has obtained the CPU and is in a running state.

DEAD: A thread in the RUNNING state becomes the DEAD state after executing the run method.

BLOCKED: This state refers to the thread in the RUNNING state. For some reason, such as calling the sleep method, waiting for user input, etc., the current CPU is given up to other threads.


Q58: After defining the explicit constructor of the class, can I still use the default constructor?

 Answer: If an explicit constructor is not defined, then Java will provide a default parameterless constructor, but if an explicit constructor is defined, the default constructor can no longer be called.

 

Q59: There can be two methods, their method names and parameters are the same, but the return value types are different?

Answer: The same method means that the method name, parameters and return type are the same, so two methods with different return types can coexist.

 

Q60: What is the output of the following code?

Answer: The output is 4

 

Q61: A Java class is successfully compiled without executing main(). Is this statement correct?

Answer: Correct. Although the Java compiler stipulates that the entry point of the program is staticmain, it can still be compiled without main(), but it cannot be run.

 

Q62: Can we call non-static methods in static methods?

Answer: Non-static methods are classified by objects and have object-level scope, so if you want to call non-static methods in static methods, you must first create objects of the class, and then use object references to call these methods.

 

Q63: In order to run a Java program, what are the two environment variables that must be set?

 Answer: PATH variable and CLASSPATH variable.

 

Q64: Can variables in Java be used without initialization?

Answer: Java does not assign default values ​​to variables, so if the variables are not initialized, the program will fail to compile and give an error message.

 

Q65: Can a class in Java inherit multiple classes?

 Answer: Java does not support multiple inheritance.

 

Q66: In Java, can the constructor be different from the class name?

 Answer: No, the Java constructor must be the same as the class name. If it is different, it will be treated as a normal function.

 

Q67: What are the outputs of Round (3.7) and Ceil (3.7)?

 Answer: Both of them output 4. Round() follows rounding, and Ceil() follows rounding up.

 

Q68: Can goto be used to go to a specific line in Java?

 Answer: No, there is no goto keyword in Java.

 

Q69: Can a thread that has died be started again?

Answer: No.

 

Q70: Are the declarations of the following categories correct?

Insert picture description here

Answer: Incorrect, abstract class cannot be declared as Final.

 

Q71: Does every machine need JDK to run Java programs?

 Answer: JDK is a Java development kit, it is not necessary, but JRE is necessary.

 

Q72: What is the difference between Equals() and ==?

 Answer: In Java, the == operation compares whether the values ​​of two variables are equal. For a reference variable, it means whether the addresses of the two variables stored in the heap are the same, that is, whether the contents of the stack are the same.

 Whether the two variables represented by the equals operation are references to the same object, that is, whether the contents of the heap are the same

 In the following example, equals() returns true, and the == operator returns false:

 

Q73: Can a method defined in a Java class be implemented using other language codes, such as C language?

 Answer: Yes, in the case of native development, we can define public static methods in Java classes, but do not execute them, and then implement them in another language (such as C).

 

Q74: How to define destructor in Java?

 Answer: There is no need to define a destructor in a Java class. It has its own garbage collection mechanism, which will be executed automatically when the object is no longer referenced.

 

Q75: Can a variable in Java be both a local variable and a static variable?

 Answer: No. Defining local variables as static variables will cause compilation errors.

 

Q76: Can there be static methods in Interface?

 Answer: Static methods in Interface are meaningless. Static methods cannot be overridden in classes. The methods in Interface are abstract by default, so they can only be implemented in classes that implement Interface.

 

Q77: In the class that implements the interface, can we change the value of the variable defined in the interface?

 Answer: No, most of the variables defined in the interface are by default unchangeable constants such as public, static, and final.

 

Q78: The garbage collection mechanism in Java can ensure that the program will never exceed the memory?

 Answer: Even if Java provides automatic garbage collection, there is no guarantee that the program will not exceed memory, because Java objects are created faster than garbage collection.

 

Q79: Can main() have a return type other than void?

 Answer: No, main() must return void for the program to execute successfully.

 

Q80: After garbage collection, can the object be triggered again and used?

 Answer: No, once the object is recycled, it no longer exists on the stack and cannot be accessed and referenced again.

 

Q81: In Java thread programming, which method must be implemented by all threads?

 Answer: Run() is a method of the Runnable interface and must be implemented by all threads.

 

Q82: How to control the database connection in the program, and only one thread can connect to the database at a time?

 Answer: Use the concept of synchronization to implement it. Put the database-related code in the method of the synchronized keyword in the hs synchronized keyword so that only one thread can access it at a time.

 

Q83: What should I do if the programmer manually throws an exception?

 Answer: In order to deal with manually thrown exceptions, we can use the throw keyword, and catch and handle the exception in catch.

 

Q84: How to realize that a class does not allow other classes (or even derived classes) to create its objects?

 Answer: Declare the constructor of this class as private, so it will not be accessed by other classes.

 

Q85: How are objects stored in Java?

 Answer: Each object gets memory space from the stack when it is created. After being destroyed by the garbage collector, its space will be released and reallocated to other objects.

 

Q86: How to determine the actual size of the object on the stack?

 Answer: In Java, there is no way to determine the exact size of an object.

 

Q87: Which of the following classes will allocate more memory?

 Type A: Three methods, four variables, no objects

 Type B: five methods, three variables, no objects

 Answer: No memory is allocated before the object is created, so neither of these two classes allocate memory.

 

Q88: What will happen if the exception is not handled in the program?

 Answer: If there is no exception handling, the program will be aborted and the statement after the exception is thrown will not be executed.

 

Q89: If a class is defined and multiple constructors are defined, is it possible to call another constructor in one constructor?

 Answer: If a class has multiple constructors, you can use this() to call another constructor in one constructor.

 

Q90: What is an anonymous class?

 Answer: Anonymous classes are classes that cannot have names. They cannot be quoted. They can only be declared with the New statement when they are created.

 In the following example, we define an anonymous class:

 

Q91: Can the size of an array be changed after it is declared?

 Answer: The array is static, once the size is specified, it cannot be changed.

 

Q92: There are multiple classes in the application, but only one main() can it?

 Answer: Yes, the main() method is the entry method of a Java application. The code always starts from the main method of a specific class.

 

Q93: If I want to keep the object's data for future use, what is the best way to do it?

 Answer: Use serialization.

 

Q94: What is a partial class?

 Answer: If we define a new class in a specific block of Java, then this class is called a local class, which is available in the local scope and not available outside of the defined block.

 

Q95: Both String and StringBuffer represent String objects. Can these two objects be compared with each other?

 Answer: No.

 

Q96: What APIs does Java provide for collection operations?

 Answer: Java provides Collection API, which can be applied to a set of objects. Important classes supported by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

 

Q97: Can Java's type conversion convert all other classes to Boolean types?

 Answer: No, other primitive types cannot be converted to Boolean types, nor can Boolean types be converted to other primitive data types.

 

Q98: Does the method's rewriting allow different return types?

 Answer: Method rewriting requires that the name and parameters of the method of the subclass must be the same as the method covered, and the return type can be different but must be a subclass of the method covered.

 

Q99: What is the base class of all exception classes?

 Answer: Java.Lang.throwable.

 

Q100: What is the calling sequence of constructors in inheritance?

 Answer: In the case of inheritance, when creating a new object of a derived class, first call the constructor of the parent class, and then call the constructor of the derived class.

 

The above is a compilation of 100 Java programmer interview questions and answers. I hope that students can understand and master this knowledge based on learning the technology. 

Comments

Popular posts from this blog

Defination of the essential properties of operating systems

Define the essential properties of the following types of operating sys-tems:  Batch  Interactive  Time sharing  Real time  Network  Parallel  Distributed  Clustered  Handheld ANSWERS: a. Batch processing:-   Jobs with similar needs are batched together and run through the computer as a group by an operator or automatic job sequencer. Performance is increased by attempting to keep CPU and I/O devices busy at all times through buffering, off-line operation, spooling, and multi-programming. Batch is good for executing large jobs that need little interaction; it can be submitted and picked up later. b. Interactive System:-   This system is composed of many short transactions where the results of the next transaction may be unpredictable. Response time needs to be short (seconds) since the user submits and waits for the result. c. Time sharing:-   This systems uses CPU scheduling and multipro-gramming to provide economical interactive use of a system. The CPU switches rapidl

What is a Fair lock in multithreading?

  Photo by  João Jesus  from  Pexels In Java, there is a class ReentrantLock that is used for implementing Fair lock. This class accepts optional parameter fairness.  When fairness is set to true, the RenentrantLock will give access to the longest waiting thread.  The most popular use of Fair lock is in avoiding thread starvation.  Since longest waiting threads are always given priority in case of contention, no thread can starve.  The downside of Fair lock is the low throughput of the program.  Since low priority or slow threads are getting locks multiple times, it leads to slower execution of a program. The only exception to a Fair lock is tryLock() method of ReentrantLock.  This method does not honor the value of the fairness parameter.

How do clustered systems differ from multiprocessor systems? What is required for two machines belonging to a cluster to cooperate to provide a highly available service?

 How do clustered systems differ from multiprocessor systems? What is required for two machines belonging to a cluster to cooperate to provide a highly available service? Answer: Clustered systems are typically constructed by combining multiple computers into a single system to perform a computational task distributed across the cluster. Multiprocessor systems on the other hand could be a single physical entity comprising of multiple CPUs. A clustered system is less tightly coupled than a multiprocessor system. Clustered systems communicate using messages, while processors in a multiprocessor system could communicate using shared memory. In order for two machines to provide a highly available service, the state on the two machines should be replicated and should be consistently updated. When one of the machines fails, the other could then take‐over the functionality of the failed machine. Some computer systems do not provide a privileged mode of operation in hardware. Is it possible t