Java All Questions
Java All Questions
Static methods in Java cannot be overridden. This is because static methods are not
associated with the instance of a class, but with the class itself. Therefore, when
a subclass inherits a static method from its parent class, it cannot modify the
behavior of the static method in any way.
Immutable objects are by default thread-safe because their state can not be
modified once created. Since String is immutable in Java, it's inherently thread-
safe.
String pool is a storage space in the Java heap memory where string literals are
stored. It is also known as String Constant Pool or String Intern Pool. It is
privately maintained by the Java String class. By default, the String pool is
empty.
You can prevent a class from being subclassed by using the final keyword in the
class's declaration. Similarly, you can prevent a method from being overridden by
subclasses by declaring it as a final method
For the key to work correctly, it must have properly overridden the equals() and
hashCode() methods so that the state change for a key object does not change the
hash code of the object. For example, if two objects are equal using the equals()
method of the Object class, then the hashCode() method should give the same value
for these two objects.
An overriding method has the same name, number, and type of parameters, and return
type as the method that it overrides. An overriding method can also return a
subtype of the type returned by the overridden method
keyset(): A keySet() method of HashMap class is used for iteration over the keys
contained in the map. It returns the Set view of the keys. values(): A values()
method of HashMap class is used for iteration over the values contained in the map.
Type Safety in Java. The Java language, by design, enforces type safety. It implies
that Java prevents the programs from accessing memory in inappropriate ways by
controlling the memory access of each object. Java does this by using objects
(instantiated from classes) to perform operations.
Checked exceptions happen at compile time when the source code is transformed into
an executable code. Unchecked exceptions happen at runtime when the executable
program starts running.
In Java, both errors and exceptions are subclasses of the Throwable class.
Throwable is the root class of all exceptions and errors in Java. It is used to
indicate that some abnormal situation has occurred.
Errors and exceptions are both problems that can occur in a Java program. However,
there are some key differences between the two.
Errors are typically caused by problems with the system, such as running out of
memory or a hardware failure. There is not much that you can do to prevent errors
from occurring. However, you can try to reduce the likelihood of errors occurring
by using good programming practices, such as checking for null pointers and
handling files carefully.
17. Explain Singleton Design Pattern ? write you class to make singleton design
pattern
18. Difference between local and instance variable
In Java, the == operator compares the references of two objects, while the equals()
method compares the values of two objects. The == operator checks if two objects
refer to the same memory location, while the equals() method checks if two objects
have the same value.
To put it simply, the == operator checks if two objects are the same object, while
the equals() method checks if two objects have the same value.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because
private means “only visible within the enclosing class”.
protected means “only visible within the enclosing class and any subclasses”
3. Protected Access Modifier
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is made
public, to access it in p2. The method display in class A is protected and class B
is inherited from class A and this protected method is then accessed by creating an
object of class B.
Throwable
|
|-- Error
|
|-- Exception
| |
| |-- CheckedException
| |
| |-- RuntimeException
To avoid NullPointerExceptions, you need to take care that all objects are
initialized with a legitimate value (that is not null), before using them. Any
operation performed on a null reference variable results in NullPointerException.
30.00PS concepts
31. Difference between Abstraction and encapsulation ? how you use it in your
project
32. When to use abstract class and interface in java ?
33. Difference between abstract class and interface ?
34. Difference between Exception and errors ?
35. Difference between throw, throws and finally
36. What is class ?
37. What is an object ?
38. Difference between class and object ?
39. What is method overloading
40. What is method overriding
41.What is a thread
42. File handling in Java ?
43. Purpose of static method and static variable ?
44. Difference between continue and break
45. What is final keyword in java?
46. What is JIT compiler ?
47. What is WORA concept in java ?
48. Purpose of default constructor ?
49. What is class loader in java ?
50. What is inheritance
51. What is object cloning
52. What is method overriding
53. Static binding and dynamic binding
54. What is interface
55. What is exception handling in java ?
Yes, the finally block in Java can be used without a catch block. The finally block
is used to execute code that should always run, regardless of whether an exception
is thrown or not. It's typically used to release resources, such as closing files
or database connections, to ensure proper cleanup, regardless of whether an
exception occurs.
try {
// Code that may throw exceptions
} catch (Exception e) {
// Exception handling code (optional)
} finally {
// Code that should always run
}
Memory Allocation: When Java programs create objects using the new keyword, memory
is allocated from the heap to store those objects.
Java does not have destructors because it uses garbage collection to manage memory.
Garbage collection is a process that automatically reclaims memory that is no
longer being used by objects. This means that developers do not need to explicitly
call a destructor to clean up an object when it is no longer needed.
1. JDK
Java Development Kit aka JDK is the core component of Java Environment and provides
all the tools, executables, and binaries required to compile, debug, and execute a
Java Program. JDK is a platform-specific software and that’s why we have separate
installers for Windows, Mac, and Unix systems. We can say that JDK is the superset
of JRE since it contains JRE with Java compiler, debugger, and core classes.
2. JVM
JVM is the heart of Java programming language. When we execute a Java program, JVM
is responsible for converting the byte code to the machine-specific code. JVM is
also platform-dependent and provides core java functions such as 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. This independence from hardware
and the operating system makes java program write-once-run-anywhere.
3. JRE
JRE is the implementation of JVM. It provides a platform to execute java programs.
JRE consists of JVM, Java binaries, and other classes to execute any program
successfully. JRE doesn’t contain any development tools such as Java compiler,
debugger, JShell, etc. If you just want to execute a java program, you can install
only JRE. You don’t need JDK because there is no development or compilation of java
source code is required. Now that we have a basic understanding of JDK, JVM, and
JRE, let’s look into the difference between them.
With a char[] , because these are primitives types we are acting on, we could
overwrite the array with any value, meaning we can avoid having sensitive data
present in memory once we are done processing it. Additionally, strings in Java are
reserved in a special area in heap memory called the String Constant Pool.
63. How many objects are created in JVM when a string type variable is assigned
using new keyword?
When a string type variable is assigned using the new keyword in Java, 2 objects
are created.
The first object is created in the String Literal Pool. The String Literal Pool is
a special storage area in the Java heap. When a string is created and if the string
already exists in the pool, the reference of the existing string will be returned,
instead of creating a new object and returning its reference.
The second object is created in the Java heap. The Java heap is a memory area where
all objects are created. When a new object is created, the JVM allocates memory for
the object in the heap and returns a reference to the object.
The classpath is an environment variable in Java that tells the Java Virtual
Machine (JVM) where to find the classes it needs to run a program. The classpath
can include directories, JAR files, and ZIP files. The JVM will search the
classpath in order, looking for the classes it needs.
A wrapper class in Java is a class that encapsulates a primitive data type and
provides a number of methods to interact with it. The eight wrapper classes in Java
are:
Boolean, Byte, Character, Double, Float, Integer, Long, and Short.
Wrapper classes are useful for a number of reasons. First, they allow primitive
data types to be used in collections, such as ArrayList and HashMap. Second, they
provide methods for converting primitive data types to and from strings. Third,
they provide methods for performing mathematical operations on primitive data
types.
71. Can a java file have more than one public class?
No, a Java file can only have one public class. The public class must also have the
same name as the Java file. This is because the Java compiler needs to know which
class is the entry point for the program.
75. What are the tools you have used to improve the performance of your application
?
The stack is generally smaller in size than the heap because it is used for storing
small, temporary variables and data, while the heap is used for storing larger
objects.
82. Define Copy Constructor in Java
A copy constructor in a Java class is a constructor that creates an object using
another object of the same Java class. That's helpful when we want to copy a
complex object that has several fields, or when we want to make a deep copy of an
existing object.
Pointers are not supported in Java. This is because pointers can be dangerous if
used incorrectly. For example, if a pointer is used to access memory that has been
freed, the program can crash. Additionally, pointers can be used to create security
vulnerabilities. For example, a pointer could be used to access private data.
Local variable is accessible to all the objects of the class. Instance variable has
different copies for different objects.
Yes, you can call a constructor of a class inside another constructor in Java. This
is called constructor chaining. It is a technique that allows you to reuse code and
avoid redundancy in the initialization of objects.
The calling of the constructor can be done in two ways: By using this() keyword: It
is used when we want to call the current class constructor within the same class.
By using super() keyword: It is used when we want to call the superclass
constructor from the base class.
87. Difference between static methods, static variables, and static classes in
Java?
Static variables: A static variable is a variable that is declared with the static
keyword. This means that there is only one copy of the variable for the entire
class, rather than each instance having its own copy. Static variables are often
used to store constants or other values that are shared across all instances of a
class.
Static methods: A static method is a method that is declared with the static
keyword. This means that the method can be called without creating an instance of
the class. Static methods are often used to perform utility functions that are not
specific to any particular instance of a class.
Static classes: A static class is a class that is declared with the static keyword.
This means that the class can only be nested inside another class. Static classes
are often used to group related classes together or to provide a namespace for
utility functions.
Java is not considered a pure object-oriented programming language. The main reason
is it supports primitive type values. For an object-oriented programming language,
data should be represented in the form of objects. As Java uses primitive data
types, it is not considered a pure object-oriented programming language.
89. What do you understand about an instance variable and a local variable?
93. How is the creation of a String using new different from that of a literal
When we create a String object using the new() operator, it always creates a new
object in heap memory. On the other hand, if we create an object using String
literal syntax e.g. “Baeldung”, it may return an existing object from the String
pool, if it already exists.
Shallow Copy:
A shallow copy creates a new object and then copies the non-static fields of the
current object to the new object. If the field is a reference to an object, the
reference is copied, not the actual object itself. As a result, both the original
and copied objects share the same references to the objects they point to.
Deep Copy:
A deep copy, on the other hand, creates a new object and then recursively copies
all the fields of the current object, including any nested objects. In other words,
it duplicates both the top-level structure and all the internal objects that the
original object references.
96. Write a Java Program to print Fibonacci Series using
Recursion
97. Write a Java Program to find the factorial of a given
number
Technically, Java is always pass by value, because even though a variable might
hold a reference to an object, that object reference is a value that represents the
object's location in memory. Object references are therefore passed by value.
Generics in Java provide a way to create classes, interfaces, and methods that
operate on a parameterized type. The primary purpose of generics is to enable
stronger type checking at compile time and to provide compile-time safety by
detecting and preventing type mismatches and type-related errors.
Type Safety
Code Reusability
Collections Framework: Generics are extensively used in the Java Collections
Framework to create type-safe collections, such as ArrayList<T>, HashMap<K, V>,
LinkedList<E>, etc. Using generics in collections ensures that only elements of the
specified type can be added to or retrieved from the collection, providing type
safety and eliminating the need for explicit type casting.
The super keyword in Java is used to access the parent class or superclass of a
subclass. It's often used to access the superclass's members, such as methods or
fields, that have been overridden in the subclass. For example, the super keyword
can be used to call the superclass'.s method from within the subclass using
super.methodName().