[go: up one dir, main page]

0% found this document useful (0 votes)
1 views20 pages

Java Questions

Uploaded by

Duggi vamshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

Java Questions

Uploaded by

Duggi vamshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Basics of JAVA

1)What is JDK?
2)Which is the latest version of JAVA?
3)Explain the advantages of JAVA?
4)Explain JAVAC and JAVA Commands and which folder they are available?
5)What is signature of main method?
6)Explain keyword?list some keywords in JAVA?
7)Explain identifiers in JAVA?
8)Explain about Literals?
9)Explain why JAVA is platform independent?
10)Is JVM platform independent?
11)Explain the difference between compliler and interpreter?
13)What is Rule and Convention?
14)Explain about JRE?
15)explain variables in JAVA and Different types of Variables?
16)Mention all the primitive datatypes in java?
17)Explain about primitive variables?
18)Explain Reference variables?
19)What is String in java?
20)Explain Methods in JAVA and why we use Methods?
21)Write the general Syntax for a method?
22)What is the Default execution method in java?
23)Can we Execute Java Program without main method?
24)Can we Compile Java Program without main method?

ANSWERS:
1) JDK stands for Java Development Kit. It is a software development kit used by Java
developers to develop, compile, debug, and run Java applications.

2) As of my last update in January 2022, Java 17 was the latest version. However, there might
be newer versions released since then.

3) Advantages of Java include platform independence, object-oriented programming support,


robustness, security, and ease of use due to its simple syntax and extensive standard library.

4) JAVAC is the Java compiler, used to compile Java source code into bytecode. The JAVA
command is used to execute Java applications. Both commands are available in the bin folder
of the JDK installation directory.

5) The signature of the main method in Java is: `public static void main(String[] args)`

6) Keywords in Java are reserved words that have predefined meanings and cannot be used as
identifiers. Some keywords in Java include `class`, `public`, `static`, `void`, `if`, `else`, `for`,
`while`, `break`, `continue`, `return`, etc.

7) Identifiers in Java are names given to classes, variables, methods, and other program
components. They must adhere to certain rules such as starting with a letter, underscore, or
dollar sign, and can consist of letters, digits, underscores, and dollar signs.
8) Literals in Java represent fixed values in the source code. They can be of various types such
as integer literals, floating-point literals, character literals, string literals, boolean literals, etc.

9) Java is platform independent because of its bytecode execution. Java source code is
compiled into bytecode, which can be executed on any platform with a Java Virtual Machine
(JVM), making Java applications platform-independent.

10) JVM (Java Virtual Machine) is platform-dependent because it is specific to each operating
system. However, once a JVM is installed on a particular platform, Java bytecode can be
executed on that platform, providing platform independence at the application level.

11) A compiler translates the entire source code of a program into machine code before
execution, while an interpreter translates and executes code line by line.

13) Rules are mandatory guidelines that must be followed in programming, while conventions
are recommended practices that improve code readability and maintainability.

14) JRE (Java Runtime Environment) is a set of software tools used for developing Java
applications. It includes the JVM, libraries, and other necessary components to run Java
applications.

15) Variables in Java are containers used to store data. There are different types of variables in
Java, including instance variables, class variables (static variables), local variables, and
parameters.

16) Primitive data types in Java include byte, short, int, long, float, double, char, and boolean.

17) Primitive variables hold data of primitive data types directly, without referencing any objects.
They store the actual values.

18) Reference variables in Java hold references (memory addresses) to objects. They do not
directly contain the data; instead, they point to the memory location where the data is stored.

19) String in Java is a class that represents a sequence of characters. It is widely used for
manipulating textual data.

20) Methods in Java are blocks of code that perform a specific task. They allow code reuse,
modular programming, and abstraction of functionality.

21) General syntax for a method in Java:


```java
<access_modifier> <return_type> <method_name>(<parameter_list>) {
// Method body
}
```

22) The default execution method in Java is the `main` method.

23) No, a Java program cannot be executed without a `main` method. It is the entry point for the
execution of Java applications.
24) Yes, a Java program can be compiled without a `main` method. The presence of a `main`
method is not required during the compilation phase.

Object Oriented Programing

Class and Object

25)Explain what is an Object?


26)Explain What is a Class?
27)Explain Members of a Class?
28)Explain Static Members and Non Static Members of a class?
29)List the Difference between Static and NonStatic Members?
30)Explain About Global variables?
31)Explain How can you access Static Global Variables and NonStatic Global Variables of a
class?
32)What will be the Default values for Global Variables,Reference Variables,Boolean variable?
33)Explain the difference between local and Global Variables?
34)How can You Declare Constant variables in java?
35)Can we just declare a final global variable?
36)Explain About Static Blocks and NonStatic Blocks?
37)When does Static Block get Executed and how many times Static Blocks will be Executed in
one Execution cycle?
38)When does a Non Static Block get Executed and How many times Non Static Blocks will be
Executed in one Execution cycle?
39)What Does a Method Return type Signify?
40)Can we develop a method without Return type?
41)What is the datatype of the reference variable in java?
42)Explain about Constructors and Different types of Constructors?
43)What is the default Constructor?
44)What is Constructor overloading ?Why do we use it?
45)what is this() calling statement?why do we use it?
46)what is Recursion?
47)Recursion while constructor overloading will result in compile time or run time error?
48)what is "this" keyword?
49)Explain the use of this Keyword?
50)Explain about Has-A Relationship?

ANSWERS:
25) An object in programming refers to a particular instance of a class. It is a concrete entity that
has a unique identity, state, and behavior.

26) A class in programming is a blueprint or template for creating objects. It defines the
properties (attributes) and behaviors (methods) that objects of that type will have.
27) Members of a class refer to the various components within a class, including fields
(variables), methods, constructors, and nested classes.

28) Static members of a class belong to the class itself rather than any specific instance of the
class. Non-static members, on the other hand, are associated with individual instances of the
class.

29) Differences between static and non-static members include:


- Static members are shared among all instances of the class, whereas non-static members
belong to individual instances.
- Static members are accessed using the class name, while non-static members are accessed
using object references.
- Static members are initialized once when the class is loaded, while non-static members are
initialized each time an instance is created.

30) Global variables are variables that are declared outside of any method, constructor, or block
in a class. They are accessible to all methods within the class.

31) Static global variables are accessed using the class name, while non-static global variables
are accessed using object references.

32) Default values:


- Global variables: Depends on the data type.
- Reference variables: null.
- Boolean variables: false.

33) Local variables are declared within a method, constructor, or block and have local scope,
meaning they can only be accessed within that particular block of code. Global variables, on the
other hand, are declared at the class level and can be accessed by all methods within the class.

34) Constant variables in Java are declared using the `final` keyword. They must be initialized at
the time of declaration and cannot be reassigned.

35) Yes, a final global variable can be declared.

36) Static blocks are used for static initialization of a class and are executed when the class is
loaded into memory. Non-static blocks are used for initialization of instance variables and are
executed each time an instance of the class is created.

37) Static blocks are executed when the class is loaded, and they are executed only once per
class, regardless of how many instances of the class are created.

38) Non-static blocks are executed each time an instance of the class is created, and they are
executed as many times as there are instances of the class.

39) The return type of a method specifies the type of value that the method returns to the caller.

40) Yes, methods can be declared without a return type. In Java, such methods are called
"void" methods, meaning they do not return any value.

41) The datatype of a reference variable in Java depends on the type of object it refers to.
42) Constructors are special methods used for initializing objects. Different types of constructors
include default constructors, parameterized constructors, and copy constructors.

43) The default constructor is a constructor with no parameters. If no constructor is explicitly


defined in a class, Java provides a default constructor automatically.

44) Constructor overloading refers to the ability to define multiple constructors for a class, each
with a different parameter list. It allows objects to be initialized in different ways depending on
the arguments passed.

45) `this()` is a calling statement used to invoke one constructor from another constructor within
the same class. It is used to reuse constructor code or to provide different constructors with
different parameter lists.

46) Recursion is a programming technique where a function calls itself directly or indirectly to
solve a problem.

47) Recursion with constructor overloading may result in compile-time errors if the compiler
cannot determine which constructor to call based on the provided arguments.

48) In Java, the `this` keyword is a reference to the current object within a method or
constructor.

49) The `this` keyword is used to differentiate between instance variables and parameters with
the same name, to invoke one constructor from another within the same class, and to pass the
current object as an argument to other methods.

50) Has-A relationship in Java refers to the relationship between two classes where one class
"has" or contains an instance of another class as one of its members. It is typically implemented
using composition, where one class owns another class's object as a part of its state.

Inheritance

51)Explain Inheritance and different types of inheritance?


52)Explain the use of extends keyword?
53)Does java support multiple inheritance?justify?
54)Explain about Diamond Ambiguity problem?
55)Explain super() calling Statement and "super" keyword?
56)What is the difference between this() and super() calling statement?
57)What is the difference between this and super keywords?
58)Explain what is Constructor chaining?

ANSWERS:
Sure, let's dive into each of these concepts:

51) **Inheritance and Different Types**:


- **Inheritance** in object-oriented programming is a mechanism where a new class, called
the subclass or derived class, is created based on an existing class, called the superclass or base
class. The subclass inherits the properties and behaviors (methods) of the superclass.
- **Types of Inheritance**:
1. **Single Inheritance**: A subclass inherits from only one superclass.
2. **Multilevel Inheritance**: A subclass inherits from another subclass.
3. **Hierarchical Inheritance**: Multiple subclasses inherit from a single superclass.
4. **Multiple Inheritance**: A subclass inherits from more than one superclass (Java doesn't
support this directly).

52) **Use of `extends` Keyword**:


- In Java, the `extends` keyword is used to indicate that a class is inheriting properties and
behaviors from another class.
- Example: `class SubClass extends SuperClass { ... }`

53) **Java Support for Multiple Inheritance**:


- Java does not support multiple inheritance of classes, meaning a class cannot extend multiple
classes. This is done to avoid the diamond problem and to maintain simplicity and avoid
ambiguity in the language.

54) **Diamond Ambiguity Problem**:


- The diamond problem arises in languages that support multiple inheritance. It occurs when a
subclass inherits from two classes, both of which inherit from a common superclass. This creates
ambiguity in the subclass regarding which superclass method to inherit.
- Java avoids this problem by not supporting multiple inheritance.

55) **`super()` Calling Statement and `super` Keyword**:


- `super()` is a calling statement used to invoke the superclass constructor from the subclass
constructor. It must be the first statement in the subclass constructor if used.
- `super` keyword is used to refer to the superclass instance variables and methods from the
subclass.

56) **Difference between `this()` and `super()` Calling Statement**:


- `this()` is used to invoke a constructor of the same class, whereas `super()` is used to invoke a
constructor of the superclass.

57) **Difference between `this` and `super` Keywords**:


- `this` keyword is a reference to the current instance of the class.
- `super` keyword is a reference to the superclass, used to access members of the superclass.

58) **Constructor Chaining**:


- Constructor chaining refers to the process of calling one constructor from another constructor
within the same class or in the superclass hierarchy.
- This allows for code reusability and helps in initializing objects efficiently.
Polymorphism

59)Explain method overloading with a real time example?


60)why do we need method Overloading?
61)explain method overriding with real time examples?
62)can we override Static methods?
63)Explain about TypeCasting?
64)Explain Primitive Casting?
65)Explain Auto widening and Explicit Narrowing?
66)Explain Auto upcasting and Explicit Downcasting?
67)can we Achieve Object Casting without inheritance?justify
68)Can we Achieve Downcasting without upcasting?Justify
69)Explain About Polymorphism?
70)Explain Different types of polymorphism?
71)When Does Java throws Class Cast Exception?
72)Explain the use of instanceOf Operator?

ANSWERS:
59) Method overloading is when multiple methods in a class have the same name but different
parameters. This allows you to define multiple methods with the same name as long as their
parameter lists are different.

Example:
```java
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}
```
Here, the `add` method is overloaded with two versions: one that takes two integers and another
that takes two doubles.

60) Method overloading allows for more intuitive method naming and helps in code readability.
It also enhances code reusability by allowing the same method name to perform different
operations based on the input parameters.

61) Method overriding occurs when a subclass provides a specific implementation of a method
that is already defined in its superclass.
Example:
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}
```
Here, `Dog` overrides the `sound` method of its superclass `Animal`.

62) No, static methods cannot be overridden in Java because they belong to the class, not to the
instance of the class.

63) Typecasting is the process of converting one data type into another.

64) Primitive casting involves converting one primitive data type into another primitive data
type.

65) Auto widening (implicit casting) occurs when a data type with smaller size is converted to a
data type with larger size automatically by the compiler. Explicit narrowing (explicit casting) is
when a data type with larger size is explicitly converted to a data type with smaller size.

66) Auto upcasting is when an object of a subclass is automatically promoted to the reference
type of its superclass. Explicit downcasting is when you manually cast an object from a
superclass type to a subclass type.

67) No, object casting requires some form of inheritance relationship between classes because
casting implies converting an object reference from one class to another, which is only
meaningful if there's an "is-a" relationship between the classes involved.

68) No, downcasting cannot be achieved without upcasting. Upcasting establishes the inheritance
relationship necessary for downcasting to be meaningful and safe. Attempting to downcast
without first upcasting would result in a compilation error or a runtime exception.

69) Polymorphism refers to the ability of a method to do different things based on the object that
it is acting upon.

70) There are two types of polymorphism in Java: compile-time polymorphism (method
overloading) and runtime polymorphism (method overriding).
71) Java throws a ClassCastException when you try to cast an object to a type that it is not an
instance of during runtime.

72) The `instanceof` operator is used to test whether an object is an instance of a particular class
or interface. It returns true if the object is an instance of the specified type; otherwise, it returns
false. It is often used in conjunction with conditional statements to determine the type of an
object before performing certain operations.

Abstraction
** can we initialize final global variables in static and non-static blocks?
73)explain about Abstract methods?
74)what is an Abstract class?
75)Explain why we cannot Instantiate an Abstract class?
76)What is the rule to be followed by the Subclass of an Abstract class?
77)Can abstract Class inherit from another abstract class?
78)Is abstract class 100% abstract ?explain?
79)Explain an interface in java?
80)what is the difference between Abstract class and interface?
81)Does Abstract class have Constructors?if yes why?
82)Do interfaces have constructors?
83)can we instantiate an interface?
84)Explain about implements keyword in java?
85)Can an interface inherit from another interface?
86)Explain Abstraction,Steps to achieve Abstraction and its advantages?
87)Can we develop final methods in interface?
88)Can we develop a final abstract class?
89)can we Develop a static method in abstract class?
90)can we just declare a variable in interface without initializing?

ANSWERS:
Sure, here are the answers to your questions:

73) **Explain about Abstract methods?**


- Abstract methods are methods declared without any implementation in an abstract class or
interface. They serve as placeholders for methods that must be implemented by subclasses or
classes that implement the interface. Subclasses or implementing classes are required to
provide a concrete implementation for these methods.

74) **What is an Abstract class?**


- An abstract class in Java is a class that cannot be instantiated on its own and may contain
abstract methods, concrete methods, or both. Abstract classes are meant to be extended by
subclasses, which provide implementations for the abstract methods.
75) **Explain why we cannot Instantiate an Abstract class?**
- We cannot instantiate an abstract class because it may contain one or more abstract
methods which do not have a body. Therefore, an abstract class is incomplete and cannot be
instantiated until all its abstract methods are implemented by a subclass.

76) **What is the rule to be followed by the Subclass of an Abstract class?**


- The rule to be followed by a subclass of an abstract class is that it must either provide
concrete implementations for all the abstract methods in the abstract class or itself be declared
as abstract.

77) **Can abstract Class inherit from another abstract class?**


- Yes, an abstract class can inherit from another abstract class. This allows for hierarchical
organization of abstract classes, where each level may provide more specific behavior.

78) **Is abstract class 100% abstract? Explain?**


- No, an abstract class is not required to be 100% abstract. It can contain both abstract and
non-abstract methods. Abstract classes can have fields, constructors, and regular methods with
implementations.

79) **Explain an interface in Java?**


- An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. It defines a contract for
classes that implement it, specifying a set of methods that must be implemented by those
classes.

80) **What is the difference between Abstract class and interface?**


- Abstract classes can have both abstract and non-abstract methods, while interfaces can only
have method declarations (signatures). Classes can implement multiple interfaces, but they can
only extend one abstract class. Abstract classes can have constructors, while interfaces cannot.

81) **Does Abstract class have Constructors? If yes, why?**


- Yes, abstract classes can have constructors. Constructors in abstract classes are used to
initialize the data members of the abstract class when an instance of a subclass is created.

82) **Do interfaces have constructors?**


- No, interfaces cannot have constructors. They are not meant for creating objects, but rather
for specifying a contract for classes to implement.

83) **Can we instantiate an interface?**


- No, interfaces cannot be instantiated because they only provide method declarations and do
not contain any implementation.

84) **Explain about implements keyword in Java?**


- The `implements` keyword in Java is used to indicate that a class is going to provide
concrete implementations for all the methods declared in an interface. It establishes a
relationship between the class and the interface, allowing the class to fulfill the contract defined
by the interface.

85) **Can an interface inherit from another interface?**


- Yes, an interface can inherit from another interface using the `extends` keyword. This allows
for the creation of a hierarchy of interfaces, where subinterfaces inherit the method declarations
of superinterfaces.

86) **Explain Abstraction, Steps to achieve Abstraction, and its advantages?**


- Abstraction is the process of hiding the implementation details and showing only the
essential features of an object. Steps to achieve abstraction include identifying the necessary
attributes and behaviors, defining interfaces or abstract classes to represent them, and
providing concrete implementations in subclasses. Advantages of abstraction include reducing
complexity, improving maintainability, and facilitating code reuse.

87) **Can we develop final methods in an interface?**


- Yes, since Java 8, interfaces can have static and default methods, which can be marked as
`final` to prevent overriding.

88) **Can we develop a final abstract class?**


- No, a class cannot be both `abstract` and `final` at the same time. An abstract class is meant
to be extended by subclasses, but a final class cannot be subclassed.

89) **Can we develop a static method in an abstract class?**


- Yes, abstract classes can have static methods. Static methods belong to the class itself
rather than to any instance of the class.

90) **Can we just declare a variable in an interface without initializing?**


- Yes, interfaces can have variables declared without initializing them. These variables are
implicitly `public`, `static`, and `final`, and their values cannot be changed by implementing
classes. They act as constants within the interface.

Encapsulation

91)What are the Different access levels in java ?Explain?


92)Explain about Singleton Class?
93)Explain What is Encapsulation?
94)Explain about Java Bean Class?

ANSWERS:
Certainly, here are the explanations for your questions:

91) **What are the Different access levels in Java? Explain?**


- Java provides four access levels to control the accessibility of classes, variables, methods,
and constructors:
1. **Private**: Members declared as private are accessible only within the same class.
2. **Default (Package-private)**: Members with no access modifier are accessible only within
the same package.
3. **Protected**: Members declared as protected are accessible within the same package
and by subclasses (even if they are in a different package).
4. **Public**: Members declared as public are accessible from any other class.
92) **Explain about Singleton Class?**
- Singleton is a design pattern that restricts the instantiation of a class to one object. It ensures
that a class has only one instance and provides a global point of access to that instance. The
Singleton pattern involves a single class which is responsible for creating its own instance and
providing a way to access that instance from anywhere in the program.

93) **Explain What is Encapsulation?**


- Encapsulation is one of the four fundamental OOP concepts. It refers to the bundling of data
(attributes) and methods (functions) that operate on the data into a single unit, typically referred
to as a class. Encapsulation restricts direct access to some of the object's components, and
instead, forces the access through the methods (getters and setters), thereby hiding the
implementation details and protecting the integrity of the data.

94) **Explain about Java Bean Class?**


- JavaBeans are reusable software components for Java. A JavaBean class is a Java class
that follows certain conventions such as having a public default constructor, being serializable,
and providing methods to access and manipulate its properties (attributes) using getter and
setter methods. JavaBeans are commonly used to encapsulate many objects into a single
object (the bean), which can then be passed around, serialized, and manipulated with ease.
They are often used in graphical user interface (GUI) programming and enterprise Java
applications.

Libraries

Object class

95)Which is the supermost class for all the classes in Java?


96)Explain "toString()","hashCode()","equals()" of object class?
98)Can subclass overide "toString()","hashCode()","equals()" of Object Class?
99)Explain final method in java?
100)Explain final class in java?
101)what is the use of clone() method?
102)what is a marker interface?
103)Explain about Arrays in java?
104)Explain primitive Array and Derived(Class-type) Array?

ANSWERS:
Sure, here are the explanations for your questions:

95) **Which is the supermost class for all the classes in Java?**
- The supermost class for all classes in Java is the `Object` class. Every class in Java is either
directly or indirectly derived from the `Object` class.

96) **Explain "toString()","hashCode()","equals()" of Object class?**


- `toString()`: This method returns a string representation of the object. By default, `toString()`
returns a string containing the class name and the object's hash code.
- `hashCode()`: This method returns a hash code value for the object. It is used in conjunction
with hash-based data structures such as HashMap.
- `equals()`: This method compares two objects for equality. By default, it compares memory
addresses to check for object identity. It is often overridden in subclasses to provide custom
equality comparisons.

98) **Can subclass override "toString()","hashCode()","equals()" of Object Class?**


- Yes, subclasses can override these methods inherited from the `Object` class. This allows
subclasses to provide custom implementations that suit their specific needs.

99) **Explain final method in Java?**


- A final method in Java is a method that cannot be overridden by subclasses. When a method
is declared as final in a superclass, it means that subclasses cannot provide a different
implementation for that method.

100) **Explain final class in Java?**


- A final class in Java is a class that cannot be subclassed. When a class is declared as final, it
means that it cannot be extended further, and no other class can inherit from it.

101) **What is the use of clone() method?**


- The `clone()` method in Java is used to create a copy of an object. It performs a shallow copy
by default, meaning it creates a new object and copies all fields of the original object to the new
object. However, if a class implements the `Cloneable` interface, it can override the `clone()`
method to perform a deep copy if necessary.

102) **What is a marker interface?**


- A marker interface in Java is an interface with no methods or constants. Its sole purpose is to
mark or tag classes that implement it with certain properties or behaviors. Examples of marker
interfaces in Java include `Serializable`, `Cloneable`, and `Remote`.

103) **Explain about Arrays in Java?**


- Arrays in Java are data structures used to store a fixed-size sequential collection of elements
of the same type. They can hold primitive data types or object references. Arrays in Java are
zero-indexed, meaning the first element is accessed at index 0.

104) **Explain primitive Array and Derived(Class-type) Array?**


- A primitive array in Java is an array that holds elements of primitive data types such as int,
float, char, etc. For example, `int[] numbers = new int[5];`
- A derived (class-type) array in Java is an array that holds elements of class types, i.e., objects.
For example, `String[] names = new String[5];` Here, `names` is an array of `String` objects.

String in java

105)Justify how Strings are immutable in Java?


106)can we inherit String class in java?justify.
107)Explain the behaviour of "toString()","hashCode()","equals()" of String Class?
108)Explain String pool area?
109)Explain the difference between "==" operator and .equals() method?
110)List out the difference between String,String builder,and String buffer?
ANSWERS:

Sure, here are the explanations for your questions:

105) **Justify how Strings are immutable in Java?**


- Strings in Java are immutable because once a String object is created, its value cannot be
changed. Any operation that appears to modify a String actually creates a new String object. For
example, when you concatenate two strings using the `+` operator, a new String object is created
with the concatenated value. This immutability ensures thread safety, simplifies concurrent
programming, and allows for optimizations like string pooling.

106) **Can we inherit String class in Java? Justify.**


- No, we cannot inherit the String class in Java. The String class is declared as `final`, which
means it cannot be subclassed. This was done to maintain the immutability and security of String
objects.

107) **Explain the behavior of "toString()","hashCode()","equals()" of String Class?**


- `toString()`: Returns the string representation of the object.
- `hashCode()`: Computes a hash code for the string based on its contents.
- `equals()`: Compares the content of two String objects for equality. It returns true if the
content of both strings is the same, otherwise false.

108) **Explain String pool area?**


- The string pool area in Java is a special area in the Java heap memory where String literals
are stored. When a String literal is created, Java checks if it already exists in the string pool. If it
does, the existing instance is returned; otherwise, a new String object is created and added to the
pool. This allows for efficient memory utilization and promotes the reuse of String objects.

109) **Explain the difference between "==" operator and .equals() method?**
- The `==` operator in Java is used to compare the memory addresses of two objects. It checks
whether two object references point to the same memory location.
- The `.equals()` method, on the other hand, is used to compare the content or value of two
objects. It compares the actual contents of the objects and returns true if they are equal, otherwise
false.

110) **List out the difference between String, StringBuilder, and StringBuffer?**
- **String**: Immutable, thread-safe, slower performance for concatenation or modification.
- **StringBuilder**: Mutable, not thread-safe, better performance for concatenation or
modification in a single-threaded environment.
- **StringBuffer**: Mutable, thread-safe, better performance for concatenation or modification
in a multi-threaded environment. However, it is slower than StringBuilder in a single-threaded
environment due to synchronization overhead.
Collection
111)Explain List,Set,Queue type of collection?
112)list out the differences between List,Set,Queue type of collection?
113)Explain the features of ArrayList,LinkedList ?
114)Explain the features HashSet,LinkedHashSet and TreeSet?
115)Explain generics and how to apply it to collection?
116)Explain Boxing and Unboxing in Java?
117)What are Wrapper classes and why its is required?
ANSWERS:
Sure, let's delve into these concepts:

111) **Explain List, Set, Queue type of collection?**


- **List**: A List is an ordered collection of elements where each element has an index. It
allows duplicate elements and maintains the insertion order. Common implementations include
ArrayList, LinkedList, and Vector.
- **Set**: A Set is a collection that does not allow duplicate elements. It does not maintain the
insertion order. Common implementations include HashSet, LinkedHashSet, and TreeSet.
- **Queue**: A Queue is a collection designed for holding elements before processing. It
follows the FIFO (First-In-First-Out) principle. Common implementations include LinkedList,
PriorityQueue.

112) **List out the differences between List, Set, Queue type of collection?**
- **List**: Allows duplicate elements, maintains insertion order, and allows positional access.
- **Set**: Does not allow duplicate elements, does not maintain insertion order, and does not
allow positional access.
- **Queue**: Follows FIFO principle, typically used for holding elements before processing.

113) **Explain the features of ArrayList, LinkedList?**


- **ArrayList**: Backed by an array, provides fast random access and traversal. Insertion and
deletion at the end are fast, but slower in the middle due to array resizing. Not suitable for
frequent insertions or deletions in the middle.
- **LinkedList**: Implemented as a doubly linked list, provides fast insertion and deletion at
any position. Traversal is slower compared to ArrayList. Suitable for frequent insertions or
deletions in the middle.

114) **Explain the features HashSet, LinkedHashSet, and TreeSet?**


- **HashSet**: Implements the Set interface, does not maintain insertion order, and allows null
elements. Provides constant-time performance for basic operations.
- **LinkedHashSet**: Maintains insertion order of elements, implemented as a hash table with
a linked list running through it. Slower than HashSet but faster than TreeSet.
- **TreeSet**: Implements the SortedSet interface, stores elements in a sorted order defined by
either natural ordering or a Comparator. Slower than HashSet and LinkedHashSet due to sorting
overhead.

115) **Explain generics and how to apply it to collection?**


- Generics in Java allow you to define classes, interfaces, and methods with type parameters.
This enables you to create classes and methods that work with any data type. Generics can be
applied to collections by specifying the type of elements the collection will hold within angle
brackets. For example, `ArrayList<String>` specifies an ArrayList that can hold String objects.

116) **Explain Boxing and Unboxing in Java?**


- **Boxing**: Converting a primitive type to its corresponding wrapper class object (e.g., int
to Integer).
- **Unboxing**: Extracting the primitive value from a wrapper class object (e.g., Integer to
int).

117) **What are Wrapper classes and why are they required?**
- Wrapper classes in Java are classes that encapsulate primitive data types. They are required
because Java collections, such as ArrayList and HashSet, can only store objects, not primitives.
Wrapper classes provide a way to use primitives as objects in collections and other scenarios
where objects are required. For example, Integer is a wrapper class for the primitive type int.

Exception

118)Explain Exceptions in java?


119)Explain how to handle exceptions?
120)Explain Checked Exceptions and unchecked Exceptions?
121)list out the difference between checked Exceptions and unchecked Exceptions?
122)list out the differences between "throw" and "throws" keywords?
123)Explain the use of finnaly block?
124)Explain the different ways of handling Checked Exceptions?
125)What is the Difference between final ,finally,finalize() in java?

ANSWERS:
Let's delve into exception handling in Java:

118) **Explain Exceptions in Java?**


- Exceptions in Java are events that occur during the execution of a program that disrupts the
normal flow of instructions. They can occur due to various reasons such as invalid input,
insufficient resources, or unexpected conditions.

119) **Explain how to handle exceptions?**


- Exceptions in Java are handled using try-catch blocks. Code that may throw an exception is
placed within the try block, and the catch block catches and handles the exception if it occurs.
Optionally, a finally block can be used to execute cleanup code regardless of whether an
exception occurs or not.

120) **Explain Checked Exceptions and unchecked Exceptions?**


- **Checked Exceptions**: These are exceptions that are checked at compile time. They are
typically exceptions that a method might throw and are required to be either caught or declared
in the method's throws clause.
- **Unchecked Exceptions**: These are exceptions that are not checked at compile time. They
usually occur at runtime and are subclasses of RuntimeException. Unchecked exceptions do
not need to be caught or declared.
121) **List out the difference between Checked Exceptions and unchecked Exceptions?**
- **Checked Exceptions**: Checked at compile time, must be either caught or declared in the
throws clause, subclasses of Exception (excluding RuntimeException).
- **Unchecked Exceptions**: Not checked at compile time, occur at runtime, subclasses of
RuntimeException.

122) **List out the differences between "throw" and "throws" keywords?**
- **throw**: Used to explicitly throw an exception within a method.
- **throws**: Used in method signature to declare that the method may throw certain
exceptions. It specifies the type of exceptions that the method might throw.

123) **Explain the use of finally block?**


- The finally block is used to execute cleanup code that should be run regardless of whether
an exception is thrown or not. It ensures that certain code is executed, such as closing
resources, before control is transferred out of the try-catch block.

124) **Explain the different ways of handling Checked Exceptions?**


- Checked Exceptions can be handled using try-catch blocks where the exception is caught
and handled within the method, or by declaring the exception in the throws clause of the method
signature to propagate it to the calling method.

125) **What is the Difference between final, finally, finalize() in Java?**


- **final**: Used to declare constants, make variables immutable, or prevent method overriding
or class inheritance.
- **finally**: A block used in exception handling to execute cleanup code regardless of whether
an exception occurs or not.
- **finalize()**: A method in the Object class that is called by the garbage collector before an
object is destroyed. It can be overridden to perform cleanup tasks, but it is generally not
recommended for general use due to unpredictable execution.
Programming questions:

Collections

1. Program: How to copy or clone a ArrayList?


2. Program: How to find does ArrayList contains all list elements or not?
3. Program: How to copy ArrayList to array?
4. Program: How to shuffle elements in ArrayList?
5. Program: How to swap two elements in a ArrayList?
6. Program: How to copy LinkedList to array?
7. Program: How to get sub list from LinkedList?
8. Program: How to reverse LinkedList content?
9. Program: How to read first element from LinkedList?
10. Program: How to read last element from LinkedList?
11. Program: How to iterate through LinkedList in reverse order?
12. Program: How to copy Set content to another HashSet? 13. Program: How to compare two
sets and retain elements which are same on both sets?
14. Program: How to copy Map content to another HashMap?
15. Program: How to search a key in HashMap?
16. Program: How to search a value in HashMap?
17. Program: How to get all keys from HashMap?
18. Program: How to get entry set from HashMap?
19. Program: How to delete all elements from HashMap?
20. Program: Write a program to remove duplicate entries from an array.
21. Program: Write a program to find duplicate value from an array.
22. Program: How to get subset from sorted set?
23. Program: How to copy Map content to another TreeMap?
24. Program: How to search a key in TreeMap?
25. Program: How to search a value in TreeMap?
26. Program: How to get all keys from TreeMap?
27. Program: How to get entry set from TreeMap?
28. Program: How to get sorted sub-map from TreeMap?
29. Program: How to get first key element from TreeMap (Sorted Map)?
30. Program: How to reverse sorted keys in a TreeMap?
31. Program: How to create synchronized list?
32. Program: How to create synchronized set?
33. Program: How to create synchronized map?
34. Program: How to get max element from the given list?
Strings
1. Write a program to reverse a String

2. Write a program to reverse a String with recursive algorithm?

3. Write a program to reverse first half separately and 2 half separately?


nd

4. Write a program to rotate one char in a given string

5. Find out length of the string without length() method of a String?

6. Find out how many words are there in a given string?

7. Write a java program to find the duplicate words and their number of occurrences in a
string?
8. Write a program to reverse the given string word wise?

9. Rotate the string word wise by one

10. Write a java program to count the total number of occurrences of a given character in a
string?

11. Write a java program to count the number of occurrences of each character in a
string?

12. Write a java program to remove all white spaces from a string?

13. Write a program to check whether given string is a palindrome or not?

14. Write a program to check whether given two strings are anagrams? 15.
Write a java program to reverse each word of a given string?

Arrays:

1. Find the sum of all given elements from an int array?


2. Find the min element from the given int array?
3. Find the max element from the given int array?
4. Find the 2nd min element from the given int array?
5. Find the 2nd max element from the given int array?
6. Find the average value of an int array?
7. Find out the sum of all even indexed elements from a given int array?
8. Find out the sum of all odd indexed elements from a given int array?
9. Find out the min value from all even indexed elements from a given
int array?
10. Find out the max value from all odd indexed elements from a given int
array?
11. Find out the avg value from all even indexed elements from a given int
array?
12. Find out the avg value from all odd indexed elements from a given int
array?
13. Find out the sum of all elements from a first half of given int array?
14. Find out the sum of all elements from a second half of given int array?
15. Find out the min value from a first half of given int array?
16. Find out the min value from a second half of given int array?
17. Find out the max value from a first half of given int array?
18. Find out the max value from a second half of given int array?
19. Find out the avg value from a first half of given int array?
20. Find out the avg value from a second half of given int array?
21. Read all elements from an array in the reverse order?
22. Read first half of the elements in the reverse direction from an array?
23. Read second half of the elements in the reverse direction from an array?
24. Read only even indexed elements from an array?
25. Read only even indexed elements from an array in the reverse order?
26. Read only odd indexed elements from an array?
27. Read only odd indexed elements from an array in the reverse order?
28. Find out an index of a specified element from a given array?
29. Swap two given indexed elements from the array?
30. Reverse the elements of given array?
31. Reverse only first half of the elements of given array?
32. Reverse only last half of the elements of given array?
33. Reverse only even indexed of the elements of given array?
34. Reverse only odd indexed of the elements of given array?
35. Swap odd indexed elements with its immediate next even indexed elements
of given array?
36. Do right shift by one for elements of given array?

You might also like