Java Interview Questions-Core Faq - 2
Please click on the questions to see the answers
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
Break statement: If a particular condition is satisfied then break statement exits you out from a particular loop or switch case etc.
Continue statement: When the continue statement is encountered in a code, all the actions up till this statement are executed again without execution of any statement after the continue statement.
A while loop will check the condition first before executing the content.
Before entering inside the while loop, while loop check the condition first and then execute the code inside the loop code
The do while loop executes the content of the loop once before checking the condition of the while.
In do..while loop, your condition is at the end of the loop block, and makes sure to execute the loop code at least one time.
The if statement is used to select among two alternatives only. It uses a boolean expression to decide which alternative should be executed. While the switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.
We can't operate float or double values using switch case, but we can do using if else statements. A switch statement works much faster than equivalent if-else ladder. It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object. That means, Factory Method is used to create one product only but Abstract Factory is about creating families of related or dependent products.
Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories. The Factory Method creates objects through inheritance where the Abstract Factory creates objects through composition.
Factory Method pattern hides the construction of single object whereas Abstract factory method hides the construction of a family of related objects.
Prefix: increments the current value and then passes it to the function.
Above code return 6 because the value of i is incremented, and the value of the expression is the new value of i.
Postfix: passes the current value of i to the function and then increments it.
Above code return 6 because the value of i is incremented, but the value of the expression is the original value of i
The java.lang.Object is a super class of any class by default. Also Object class is a superclass for all interfaces by default. The following methods are inherited from Object in every class.
- equals(Object o)
- wait(long millis, int nanos)
- wait(long millis)
The object cloning is a way to create exact copy of an object. The clone() method provides this functionality. Every object has also a clone method which can be used to copy the object. For this purpose, clone() method of Object class is used to clone an object.
No. It is by default loaded internally by the Java Virtual Machine. You can use it without fully qualified names.
For example, System.out.println() method .
System is really the java.lang.System class. This class has a public static field called "out" which is an instance of the java.io.PrintStream class. So when we write System.out.println(), we're really calling the println() method of the out field of the java.lang.System class.
Native methods allow you to use code from other languages such as C or C++ in your java code. That is, code that does not run in the JVM. They are usually used to interface with system calls or libraries written in other programming languages.
Native code features:
- Hardware access and control.
- Use of legacy software that hasn't or cannot be ported to Java.
- Using native code to perform time-critical tasks.
Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
A Locale object represents a specific geographical, political, or cultural region. A locale object may includes user's language, country, and any special variant preferences that user needs.
Locale Class Declaration:
The word implements means implementation, when interface is meant to declare just to provide interface not for implementation. Only a class can do this. You can't implement an interface from another interface. It specifies what needs to be implemented. But interfaces use inheritance, so you can extend an interface and define a subinterface that can require additional methods.
In Java multiple inheritance is not permitted. You can only extend a single class. It was excluded from the language as a design decision, primarily to avoid circular dependencies. You can achieve it with the help of interface but not with class.
More about.... Why Java doesn’t support multiple inheritance?
Yes, you can have classes inside interfaces. Specifying a class inside an interface ties that class directly to that interface. Users which use that interface will have access to that class and all the functionality that it provides.
Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class. If there is a situation, inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface.
Interface is like a blueprint of any class, where you declare your members. Any class that implement that interface is responsible for its definition. Having private or protected members in an interface doesn't make sense conceptually. Only public members matter to the code consuming the interface. The public access specifier indicates that the interface can be used by any class in any package.
The compiler provides a default constructor if no other constructors are available in the class which initialises all the instance variables to their default values. This default constructor will call the no-argument constructor of the superclass.
There are 4 types of java access modifiers. The access specifiers are listed according to their restrictiveness order.
- default (when no access specifier is specified)
There are two popular approaches. One is to provide a clone method Or a copy factory.
In Java, there are no destructors also there is no syntax for destructors in java. Objects are destructed but there is no destructor. The Java Virtual Machine handles that for you. Java garbage collector takes care of “collecting garbage” which is what a destructor is basically in languages like C++. We cannot predict when an object is destroyed. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector.
Runtime data area in JVM can be divided as follow:
- Method Area : Storage area for compiled class files.
- Heap : Storage area for Objects.
- Java stack: Storage are for local variables, results of intermediate operations.
- PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined.
- Native method stacks : Helps in executing native methods( methods written in languages other than java).
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance.
More about..... String comparison in Java
Yes, you can. An Abstract class means the definition of the class is not complete and hence cannot be instantiated. Even though it does not have abstract method, it is an indicator that the class is available for inheritance. Also, declaring a method abstract means that subclasses have to provide an implementation for that method.
Before the release of Java 8, by default, all methods in an interface are declared as public, abstract. It will never be static. With Java 8, interfaces can have static methods. They can also have concrete instance methods, but not instance fields.
No, you cannot override private method, because the method is called private so that no class extending from that class has any access to the private method. Private methods are not visible to sub classes.
Overriding depends on having an instance of a class. A static method is not associated with any instance of a class so the concept is not applicable. You however can declare same static method with same signature in child classes, but that would not be considered as runtime polymorphism (override of methods).
Since java5 the best way to do it is to use an enum:
More about....... Singleton in Java
The java.lang.instrument.Instrumentation class provides a nice way to get the size of a Java Object, but it requires you to define a premain and run your program with a java agent.
The best way to test private methods is to use reflection. The following patterns will let you do pretty much anything related to the private methods. It is important to know that you can't change private static final variables through reflection.
The java.lang.Class.getDeclaredMethod() method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
You cannot cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does.
More about..... Boxing and Unboxing
It's an object-based representation of a process. Similar to the Thread class, which represents a thread.
The hashCode method returns a hash code value for the object. The hashCode() method should ideally return the same int for any two objects that compare equal and a different int for any two objects that don't compare equal. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
More about..... Why do I need to override the equals and hashCode methods in Java?
super() is used to call super class constructor, whereas this() used to call constructors in the same class. Interesting thing about this and super is that, they can be used as both method and variable.
The java.lang.Class.forName(String className) method returns the Class object associated with the class or interface with the given string name. It is used to load the class and it also provides a new way for creating the instance of a class without using the "new" operator. Also, we can use newInstance() to get the instance.
You can use final keyword to the method for avoid overriding in a subcalss. Similarly one can use final at class level to prevent creating subclasses. Apart from final methods there are two more techniques which you can use to prevent a method from being overridden in Java. Private and Static modifier in Java, then you may be knowing that private method is not accessible in subclass, which means they cannot be overridden as well, because overriding happens at child class.
- Java Interview Questions-Core Faq - 1
- Java Interview Questions-Core Faq - 3
- Important features of Java
- What is the difference between JDK and JRE?
- What gives Java its 'write once and run anywhere' nature?
- What is JVM and is it platform independent?
- What is Just-In-Time (JIT) compiler?
- What is the garbage collector in Java?
- What is NullPointerException in Java
- Difference between Stack and Heap memory in Java
- How to set the maximum memory usage for JVM?
- What is numeric promotion?
- Why do we need Generic Types in Java?
- What does it mean to be static in Java?
- What are final variables in Java?
- How Do Annotations Work in Java?
- How do I use the ternary operator in Java?
- What is instanceof keyword in Java?
- How ClassLoader Works in Java?
- What are fail-safe and fail-fast Iterators in Java
- What are method references?
- "Cannot Find Symbol" compile error
- Difference between system.gc() and runtime.gc()
- How to convert TimeStamp to Date in Java?
- Does garbage collection guarantee that a program will not run out of memory?
- How setting an Object to null help Garbage Collection?
- How do objects become eligible for garbage collection?
- How to calculate date difference in Java
- Difference between Path and Classpath
- Is Java "pass-by-reference" or "pass-by-value"?
- Difference between static and nonstatic methods java
- Why Java does not support pointers?
- What is package in Java?
- What are wrapper classes?
- What is singleton class in Java?
- Difference between Java Local Variable, Instance Variable and a Class Variable?
- Can a top level class be private or protected in java
- Are Polymorphism , Overloading and Overriding similar concepts?
- How to Use Locks in Java
- Why Multiple Inheritance is Not Supported in Java
- Why Java is not a pure Object Oriented language?
- Why can't a Java class be declared as static?
- Difference between Abstract class and Interface in Java
- Why do I need to override the equals and hashCode methods in Java?
- Why does Java not support operator overloading?
- What’s meant by anonymous class in Java?
- Static Vs Dynamic class loading in Java
- Why am I getting a NoClassDefFoundError in Java?
- How to generate random integers within a specific range in Java
- What's the meaning of System.out.println in Java?
- What is the purpose of Runtime and System class?
- What is finally block in Java?
- What is difference between final, finally and finalize?
- What is try-with-resources in java?
- What is a stacktrace?
- What is the meaning of immutable in terms of String?
- What are different ways to create a string object in Java?
- Difference between String and StringBuffer/StringBuilder in Java
- What is the difference between creating String as new() and literal?
- How do I convert String to Date object in Java?
- How do I create a Java string from the contents of a file?
- What actually causes a StackOverflow error in Java?
- Why is char preferred over String for storage of password in Java
- What is I/O Filter and how do I use it in Java?
- Serialization and Deserialization in Java
- Understanding transient variables in Java
- What is Externalizable in Java?
- What is the purpose of serialization/deserialization in Java?
- What is the Difference between byte stream and Character streams
- How to append text to an existing file in Java
- Read/convert an InputStream to a String in Java
- What is the difference between Reader and InputStream in Java
- Introduction to Java threads
- What is synchronization Java?
- Static synchronization Vs non static synchronization in Java
- Java Thread Deadlock Tutorial
- What is Daemon thread in Java
- Difference between implements Runnable and extends Thread in Java
- What is the volatile keyword in Java
- What are the basic interfaces of Java Collections Framework
- What are the differences between ArrayList and Vector in Java
- What is the difference between ArrayList and LinkedList?
- What is the difference between List and Set in Java
- Difference between HashSet and HashMap in Java
- Difference between HashMap and Hashtable in Java?
- How does the hashCode() method of java works?
- Difference between capacity() and size() of Vector in Java