Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Java All Questions

The document discusses various Java concepts like: 1. String is immutable in Java to prevent changes to existing String objects. StringBuffer is mutable and allows changes. 2. Static methods cannot be overridden in subclasses but non-static methods can using the @Override annotation. 3. Immutable objects like String are inherently thread-safe while mutable objects require synchronization for thread-safety. 4. The String constant pool stores String literals in the heap to reuse common Strings and reduce memory usage.

Uploaded by

Sridhar Sid
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java All Questions

The document discusses various Java concepts like: 1. String is immutable in Java to prevent changes to existing String objects. StringBuffer is mutable and allows changes. 2. Static methods cannot be overridden in subclasses but non-static methods can using the @Override annotation. 3. Immutable objects like String are inherently thread-safe while mutable objects require synchronization for thread-safety. 4. The String constant pool stores String literals in the heap to reuse common Strings and reduce memory usage.

Uploaded by

Sridhar Sid
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

1. Why String is immutable in Java ?

2. Difference between String and StringBuffer in java?

The String class is immutable. The StringBuffer class is mutable.


2) String is slow and consumes more memory when we concatenate too many strings
because every time it creates new instance. StringBuffer is fast and consumes
less memory when we concatenate t strings.
3) String class overrides the equals() method of Object class. So you can
compare the contents of two strings by equals() method. StringBuffer class
doesn't override the equals() method of Object class.
4) String class is slower while performing concatenation operation. StringBuffer
class is faster while performing concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory

3. Can we overide Static method in Java ?

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.

4. Is string thread safe ?

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.

5. What is String constant pool in java ?

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.

6. How to prevent your class from being subclassed?

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

7. Which two methods are overridden by an Object, intented to be used as key in


Hashmap?

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

8. Difference between List and Set in Java ?

9. How do you make a class immutable in java ?


Declare the class as final so it can't be extended.
Make all of the fields private so that direct access is not allowed.
Don't provide setter methods for variables.
Make all mutable fields final so that a field's value can be assigned only once.

10. Difference between Hashtable and Hashmap in java ?

11. How will you iterate map ?

How do I iterate a Map on a Map?


Using keyset() and value() 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.

12. What is type safety ? How to use it ?

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.

13. Difference between Arraylist and Linkedlist in java ?

14. Difference between checked and unchecked exception in java ?

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.

14. difference between exception and error in java

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.

15. How to convert array to a list ?

16. Difference between Serializable and Externalizable interface in java?

17. Explain Singleton Design Pattern ? write you class to make singleton design
pattern
18. Difference between local and instance variable

19. What is serialization

20. Difference between == and equals in java ?

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.

22. Difference between unique key and primary key ?


The main difference between a primary key vs unique key is that a primary key is a
key that uniquely identifies each record in a table but cannot store NULL values.
In contrast, a unique key prevents duplicate values in a column and can store NULL
values.

23.Difference between method overriding and method overloading in java ?

24. What are types of access specifiers

There are four types of access modifiers available in Java:

Default – No keyword required


Private
Protected
Public

1. Default Access Modifier


When no access modifier is specified for a class, method, or data member – It is
said to be having the default access modifier by default. The data members,
classes, or methods that are not declared using any access modifiers i.e. having
default access modifiers are accessible only within the same package.

2. Private Access Modifier


The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they
are declared.

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.

25.Explain use of this keyword ?


The this keyword in Java is used to refer to the current object. It can be used to
access the current object's fields and methods, and to invoke the current object's
constructor.

26. Explain exception hierarchy ?

Throwable
|
|-- Error
|
|-- Exception
| |
| |-- CheckedException
| |
| |-- RuntimeException

27. What is index and view in database ?

28.Difference between extending thread class and runnable interface ?

29. How can we avoid null pointer exception ?

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 ?

56. Can finally block be used without catch 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.

Here's the general syntax for using a finally block:

try {
// Code that may throw exceptions
} catch (Exception e) {
// Exception handling code (optional)
} finally {
// Code that should always run
}

57. What is garbage collection?

In Java, garbage collection refers to the automatic memory management process by


which the Java Virtual Machine (JVM) automatically reclaims memory occupied by
objects that are no longer in use by the program. Java's garbage collector runs in
the background, periodically scanning the heap for objects that are no longer
reachable or referenced by any part of the program. Once identified, these
unreachable objects are considered garbage and are eligible for removal from
memory.

Here's how garbage collection works in Java:

Memory Allocation: When Java programs create objects using the new keyword, memory
is allocated from the heap to store those objects.

Reference Tracking: Java maintains a record of references to objects. If an object


is referenced by a variable, parameter, or another object, it is considered
reachable and is not eligible for garbage collection. However, if there are no
references to an object, it becomes unreachable and eligible for garbage
collection.

58. Difference between Array and vector ?

59. Why dont we have destructors in Java ?

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.

60. What is object and how it is stored in Java ?

Object contains all the non-static data member of the class.


Object stores in Heap. Static data member stores in Class Area. Reference variable
stores in Stack. Method (static or non-static) stores in Method Area. Read more on
Java Memory Model

61.Explain JDK, JRE and JVM in java ?

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.

62. Why char array is preterred to store password than


Strings ?

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.

64. What is class path in java ?

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.

65.Is java completely object oriented ?

66. What makes java platform independent?

67. What is dynamic polymorphism?


68.What is multiple inheritance in java?

69.is multiple inheritance supported in java ?

70. What is a wrapper class in java ?

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.

72.Write a program to remove duplicates from an array ?

73. Program to reverse a string without using any api?

74. What deisgn patterns you have used in your app?

75. What are the tools you have used to improve the performance of your application
?

76. How you optimize the code for jobc

77. What are the differences between C++ and Java ?

78. List the features of the Java Programming language ?

79. What is a ClassLoader ?

A classloader in Java is a subsystem of the Java Virtual Machine (JVM) that is


responsible for loading Java classes into memory when a program is executed.
Classloaders are responsible for finding and loading class files, which are the
binary files that contain the compiled code for Java classes.

80. What are the Memory Allocations available in Java?

The Java Memory Allocation is divided into the following sections :


Heap ⇒ contains Objects (may also include reference variables)
Stack ⇒ contains methods, local variables, and reference variables.
Code ⇒ contains your bytecode (. class (after compilation) files in java)
Static ⇒ contains Static data/methods.

81. What are the differences between Heap and Stack


Memory in Java?

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.

83. Can you implement pointers in a Java Program

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.

84. Differentiate between instance and local variables?

Local variable is accessible to all the objects of the class. Instance variable has
different copies for different objects.

85. Can you call a constructor of a class inside another constructor?

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.

86. How does the size of ArrayList grow dynamically?

In Java, an ArrayList increases in size dynamically by using an array as its


underlying data structure. When an ArrayList is created, it is initialized with an
initial size and an initial capacity, which is the maximum number of elements it
can hold

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.

88. Why is Java, not a pure object-oriented language?

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?

Variables declared within a method are local variables. An instance variable is


declared inside a class but outside of any method or block. Static variables are
declared inside a class but outside of a method starting with a keyword static

90. What are Composition and Aggregation

91. What do you mean by data encapsulation


Data encapsulation, also known as data hiding, is a mechanism that hides the
implementation details of a class from the user. The user can only perform a
limited number of operations on the hidden members of the class by executing
methods.

92. What is the IS-A ' relationship in OOPs Java

In Java, we have two types of relationship:


Is-A relationship: Whenever one class inherits another class, it is called an IS-A
relationship.
Has-A relationship: Whenever an instance of one class is used in another class, it
is called HAS-A relationship.

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.

94. Why is synchronization necessary

Synchronization can be used to protect any shared resource, including objects,


variables, and methods. It is important to use synchronization whenever multiple
threads are trying to access the same resource.
Here are some examples of when synchronization is necessary in Java:
When multiple threads are trying to update the same object at the same time.
When multiple threads are trying to read from the same file at the same time.
When multiple threads are trying to write to the same file at the same time.
When multiple threads are trying to access the same database at the same time.

95. What are shallow copy and deep copy in Java

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

98. Does Java work as a "pass by value" or "pass by reference" phenomenon ?

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.

99. What is the difference between systems.out, System.err, and System.in?

The main difference between System.out and System.err is that System.err is


typically used for error messages, while System.out is used for general output.
This means that when you print an error message to System.err, it will usually be
displayed in red text, while output printed to System.out will be displayed in
black text.
System.in is used to read input from the console. This can be done using the
System.in.read() method, which reads a single character from the console. You can
also use the System.in.readLine() method, which reads a line of text from the
console

100. What is the purpose of generics?

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.

101.In what situations is the "super" keyword used?

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().

You might also like