1. What Is Java?
Java is a high-level class-based object-oriented programming language, specially designed to reduce the number of dependencies while program implementation. Java was developed by Sun Microsystems in 1995 and is currently owned by Oracle.
Using the Java Virtual Machine (JVM), Java applications can be easily compiled into bytecode that can run on any computer architecture. Hence, portability can be said to be one of the most important key strengths of Java.
2. What are the differences between an instance variable and a class variable?
Feature |
Instance Variable |
Class Variable |
Declaration |
Inside a class but outside any method |
Inside a class, using the static keyword |
Scope |
Specific to an instance of the class |
Shared among all instances of the class |
Memory Allocation |
Allocated when an instance is created |
Allocated once when the class is loaded |
Access |
Accessed using an instance of the class |
Accessed using the class name |
3. Which class serves as the superclass for all classes?
Object class in Java serves as the superclass for all other classes. Unless explicitly stated otherwise, every class in Java implicitly inherits from the Object class.
4. What are constructors in Java?
Constructors are special methods in Java that are used in instantiating objects which refers to creating an instance or occurrence of anything such as a class or struct., It has no return type and must have the same name as the class itself i.e., the constructor name should be the same as its class name including case letter sensitivity. There exist two types of constructors:
- Default Constructor: No argument constructor is provided by Java if there are no other constructors defined
- parameterised Constructor: A method that takes arguments initialises only once with specific values and an object called a parameterised constructor.
5. Explain the different types of access specifiers.
Access Specifier |
Visibility |
Class |
Package |
Subclass |
Global |
private |
Only within the same class |
Yes |
No |
No |
No |
default |
(no modifier) |
Within the same package |
Yes |
Yes |
No |
protected |
Within the same package and subclasses |
Yes |
Yes |
Yes |
No |
public |
Anywhere |
Yes |
Yes |
Yes |
Yes |
6. Why Is Java a Platform-Independent Language?
Java is platform-independent due to the fact that it is compiled into bytecode, a kind of intermediate code. Java compiler transforms Java source code into JVM instructions which can then be executed directly by JVM just in time or saved as machine code before execution. Because there are many operating systems with JVMs, the same bytecode would run on any OS that has a compatible JVM. This ability to “write once and run anywhere” is one of the key features of Java.
7. What are the FileInputStream and FileOutputStream?
Feature |
FileInputStream |
FileOutputStream |
Purpose |
Reads raw byte data from a file |
Writes raw byte data to a file |
Usage |
Suitable for reading binary data like images |
Suitable for writing binary data like images |
Methods |
read(), read(byte[] b), close() |
write(int b), write(byte[] b), close() |
Constructor |
FileInputStream(String name) |
FileOutputStream(String name) |
Example Usage |
FileInputStream fis = new FileInputStream(“file.txt”); |
FileOutputStream fos = new FileOutputStream(“file.txt”); |
8. Explain public static void main(String args[]).
This is the method used as the entry point of any Java application, written as a whole command line and we can break down each part as:
- public: This means the method is accessible from anywhere.
- static: Static refers to the method which belongs to only the class, not an instance of the class, hence can be called without creating an instance of the class.
- void: This means the method does not return any value.
- main: This is the name of the method. It is the starting point of any Java program.
- String args[]: This is an array of String objects that stores command-line arguments.
9. What is a method in Java?
Method refers to a specific block of code that performs any specific tasks, commonly used to execute code to avoid any redundancy and to make the code more modular. It can be also called an instance of that class because a method can be defined within a class. Methods can accept parameters and return values. The syntax for defining a method is:
returnType methodName(parameters) {
// method body
}
10.What is the difference between equals() and == in Java?
Feature |
equals() |
== |
Purpose |
Checks the logical equality of two objects |
Checks reference equality (if two references point to the same object) |
Method Type |
The method from Object class can be overridden |
Operator |
Usage |
obj1.equals(obj2) |
obj1 == obj2 |
11. Explain Destructors in Java.
Java does not support any type of destructors, unlike the destructors in C++, because Java primarily relies on automatic garbage collection to handle memory leaks and the efficiency of the program. The memory which is no longer in use is directly collected by an automatic garbage collector and deallocated.
12. Explain the difference between this() and super() in Java.
Feature |
this() |
super() |
Usage |
Calls another constructor in the same class |
Calls a constructor in the parent class |
Position |
It must be the first statement in a constructor |
It must be the first statement in a constructor |
Use Case |
Used to initialise the current class’s constructor |
Used to initialise the parent class’s constructor |
13. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println(a + b);
}
}
Answer: 15
14.What are the different ways to create objects in Java?
There are several ways to create objects in Java:
Example obj = new Example();
Example obj = (Example) Class.forName(“Example”).newInstance();
Example obj1 = new Example();
Example obj2 = (Example) obj1.clone();
Example obj = Example.createInstance();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“file.ser”));
Example obj = (Example) in.readObject();
15. What is the use of Static methods and static variables?
Rather than any particular instance of a class, the static methods and variables can be directly associated with the class. They can be accessed directly with the help of a class name and do not create any instance of that class.
16. Differentiate between instance and local variables.
Feature |
Instance Variables |
Local Variables |
Declaration |
Inside a class, outside any method |
Inside a method, constructor, or block |
Scope |
Belongs to an instance of the class |
Belongs to the method, constructor, or block |
Default Value |
Initialised to default value if not set |
Must be explicitly initialised before use |
Lifespan |
Exists as long as the object exists |
Exists only during method execution |
Access Modifiers |
Can use access modifiers |
Cannot use access modifiers |
17. What are Classes in Java?
Classes in Java define a code block using methods, attributes, variables, and different data types that work on one single unit of logic. Hence classes are considered as blueprints in Java programming language and hold information to define the behaviour of the objects.
Syntax of a class:
public class ClassName {
// fields
int number;
String name;
// methods
void display() {
System.out.println(“Number: ” + number + “, Name: ” + name);
}
}
18.What is a static class?
Static classes do not have permission to access instance variables and methods of any outer class. Rather, static classes are nested classes which can access the static member of the outer class.
Syntax of a static class:
public class OuterClass {
static class StaticNestedClass {
void display() {
System.out.println(“This is a static nested class.”);
}
}
}
19.What is an object?
An object can be considered as an instance of a class, which is created from classes, representing different entities that have the behaviour patterns defined by that class. Here each object can have its own set of values for the variables and methods defined in the class.
ClassName obj = new ClassName();
20. Explain different scopes in Java.
In Java, there are four types of scopes:
- Local Scope: Variables declared inside a method are in local scope.
- Instance Scope: Variables declared inside a class but outside any method, without the static keyword, belong to instance scope.
- Static Scope: This can be declared using the ‘static’ keyword and the variables belong to the static scope which can be shared within all instances of the class.
- Block Scope: Variables declared inside a block (e.g., if, for, while) are limited to that block.
21. What Is A Collection Module In Java?
One of the important parts of java.util package is the collection module which can provide many different classes and interfaces for manipulation of objects, ArrayList, HashSet, HashMap, LinkedList, etc.
22. What is the difference between Array and ArrayList in Java?
Feature |
Array |
ArrayList |
Size |
Fixed-size |
Dynamic size (can grow and shrink) |
Type |
Can hold primitive types and objects |
Can hold only objects |
Performance |
Faster due to fixed size |
Slower due to dynamic resizing |
Methods |
Does not provide built-in methods for manipulation |
Provides methods like add(), remove(), get() |
Syntax |
int[] arr = new int[10]; |
ArrayList<Integer> list = new ArrayList<>(); |
23. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]);
}
}
Answer: 3
24. What are the key features of the Java Programming language?
- Simple: Easy to learn and use.
- Object-Oriented: Supports OOP concepts like inheritance, encapsulation, and polymorphism.
- Platform-Independent: Write once, and run anywhere due to the JVM.
- Secure: Provides a secure environment through bytecode verification and the absence of pointers.
- Robustness: Strong memory management, exception handling, and type checking.
- Multithreaded: Supports concurrent execution of multiple threads.
- High Performance: Just-In-Time (JIT) compiler improves performance.
25. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String greeting = “Hello”;
String name = “World”;
System.out.println(greeting + “, ” + name + “!”);
}
}
Answer: Hello, World!
26. Explain JVM, JRE and JDK.
JVM(Java Virtual Machine): The abstract machine that enables Python applications to run on any device or operating system; this reads and interprets Python bytecode instructions
JRE (Java Runtime Environment): JRE can provide many different libraries by executing Python programs, but the compilers and debuggers do not exist as they only support Python interpreters.
JDK (Java Development Kit): JDK is the complete kit for software development that includes JRE, a loader/interpreter (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and many other different tools.
27. Differences between HashMap and HashTable in Java
Feature |
HashMap |
HashTable |
Synchronisation |
Not synchronised (thread-unsafe) |
Synchronized (thread-safe) |
Null keys/values |
Allows one null key and multiple null values |
Does not allow null keys or values |
Performance |
Faster due to lack of synchronisation |
Slower due to synchronisation |
Iteration |
Uses fail-fast iterator |
Uses fail-safe iterator |
Legacy |
Part of Java Collections Framework |
Legacy class, part of earlier versions |
28. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println(“x is greater than 5”);
} else {
System.out.println(“x is not greater than 5”);
}
}
}
Answer: x is greater than 5
29. What are the applications of Java?
- Web Applications: Java is used to create web applications with frameworks like Spring and Struts.
- Enterprise Applications: Large-scale enterprise applications often use Java for its robustness and scalability.
- Mobile Applications: Android apps are primarily developed using Java.
- Desktop GUI Applications: Java provides GUI development through frameworks like Swing and JavaFX.
- Embedded Systems: Java is used in embedded systems because of its portability and efficiency.
- Big Data Technologies: Tools like Hadoop and Apache Spark use Java.
30. What is Memory storage available with JVM?
The JVM divides memory into several distinct areas for efficient management:
- Heap: Used for dynamic memory allocation for Java objects and JRE classes. It is shared among all threads.
- Stack: Stores method frames, local variables, and partial results. Each thread has its own stack.
- Method Area: Stores class structures, such as metadata, the constant pool, and method data.
- Program Counter (PC) Register: Contains the address of the JVM instruction currently being executed.
31.What are the different data types supported in Java?
Type |
Data Type |
Size (bits) |
Default Value |
Primitive |
byte |
8 |
0 |
|
short |
16 |
0 |
|
int |
32 |
0 |
|
long |
64 |
0L |
|
float |
32 |
0.0f |
|
double |
64 |
0.0d |
|
char |
16 |
‘u0000’ |
|
boolean |
1 |
false |
Non-primitive |
String, Arrays, Classes, Interfaces |
– |
null |
32. When to use byte data type?
Byte data is generally used to save memory in data types like large arrays. Also, this can help when you work with different streams of data from a network or I/O file. A byte data represents 8-bit signed integers, ranging from -128 to 127.
33. What is a Class Variable?
A class variable is declared outside any method or constructor and also declared as a static variable using a static keyword. The class variable is shared among all the instances of that class, making it only one copy of the static variable per class.
Example:
public class Example {
static int classVariable = 10;
}
34. What is the default value of Local Variables?
Local variables do not have a default value. Local variables can only be explicitly initialised before they can be used.
35. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
Answer:
0
1
2
36. Can you list the differences between System.out, System.err, and System.in?
Feature |
System.out |
System.err |
System.in |
Purpose |
Standard output stream |
Standard error stream |
Standard input stream |
Usage |
Used to display output to the console |
Used to display error messages to the console |
Used to read input from the console |
Stream Type |
PrintStream |
PrintStream |
InputStream |
Buffering |
Buffered |
Buffered |
Buffered |
Typical Use |
Normal program output |
Error messages and diagnostics |
Reading user input |
37. What do you understand about an IO stream?
To perform the input and output operations in Java, the IO stream library is used because it can represent the input source or the output destination, which can be a disk file, current device or another program.
38. List down operators that are supported in Java.
Java supports a wide range of operators:
- Arithmetic Operators: +, -, *, /, %
- Unary Operators: +, -, ++, –, !
- Assignment Operators: =, +=, -=, *=, /=, %=
- Relational Operators: ==, !=, >, <, >=, <=
- Logical Operators: &&, ||, !
- Bitwise Operators: &, |, ^, ~, <<, >>, >>>
- Ternary Operator: ? :
- Instanceof Operator: instanceof
39. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println(sum);
}
}
Answer: 15
40. What is the difference between >> and >>> operators?
Feature |
>> (Signed Right Shift) |
>>> (Unsigned Right Shift) |
Usage |
Shifts bits to the right, preserving the sign bit (sign-extended) |
Shifts bits to the right, zero-filling the leftmost bits (zero-filled) |
Behaviour with Negative Numbers |
Preserves the sign bit (negative numbers remain negative) |
Does not preserve the sign bit (negative numbers become positive) |
Example |
-8 >> 2 results in -2 |
-8 >>> 2 results in 1073741822 |
41. What is an array in Java?
Array in Java helps to store, manage, rearrange and sort data elements in a single variable as a list. You can store the same data type elements in one array which will act as a whole one variable, mainly helping in data handling and data manipulating. We do not have to assign each element as a new variable, as it would be a very unprofessional method of pruning errors.
Example:
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
42. What is String in Java?
A sequence of characters put together can be represented whole as a string. In Java, the strings are immutable, hence once a String object is created, its value cannot be changed again.
Example:
String message = “Hello, World!”;
43. What are the different ways to add comments in Java?
Java supports two types of comments:
- Single-line Comments: Used by inserting // at the beginning of the comment.
- Multi-line Comments: Enclose the code block with /* and */ to make it a comment.
44. How do you copy an array in Java?
There are several ways to copy an array in Java:
- Using a Loop:
- Using System.arraycopy():
- Using Arrays.copyOf():
- Using clone() Method:
45. Why Is Java Not a Purely Object-Oriented Language?
Hare, Java cannot be called a purely object-oriented language because it supports primitive data types such as int, char, and byte which cannot be called class objects. Everything must be treated as an object in any purely object-oriented learning language.
46. Explain how different types of constructors are used in Java.
Constructors are special methods used to initialise objects. There are two main types of constructors in Java:
Constructor Type |
Description |
Syntax Example |
Default Constructor |
No arguments are provided by the compiler if no other constructors are defined. |
public Example() {} |
parameterised Constructor |
Takes arguments to initialise fields with specific values. |
public Example(int value) { this.value = value; } |
47. What is the use of a default constructor?
If no other constructors are created by us, a default constructor is created by the compiler automatically in Java, which helps to provide a default initialisation to an object. Default constructors do not require any parameters and automatically set the fields to their default values.
48.What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String str = “Java”;
System.out.println(str.length());
}
}
Answer: 4
49. What is the difference between Array and Collection in Java?
Feature |
Array |
Collection |
Type |
Fixed-size holds elements of a single type |
It can be dynamically resized and can hold different types |
Data Structures |
Only linear data structures |
Includes List, Set, Queue, Map |
Methods |
Limited methods for manipulation |
Rich API for manipulation (add, remove, iterate) |
Syntax |
int[] arr = new int[10]; |
Collection<Integer> collection = new ArrayList<>(); |
50.What is a super keyword in Java?
The super keyword in Java is used to refer to the immediate parent class object. It is commonly used to:
- Call the superclass constructor.
- Access superclass methods.
- Access superclass fields.
51. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String str = “Hello”;
char ch = str.charAt(1);
System.out.println(ch);
}
}
Answer: e
52. What makes a HashSet different from a TreeSet?
Feature |
HashSet |
TreeSet |
Order |
Does not guarantee any order of elements |
Maintains elements in ascending order |
Performance |
Offers constant time performance for basic operations like add, remove, and contains |
Offers log(n) time performance for basic operations |
Null Elements |
Allows one null element |
Does not allow null elements |
Backed By |
Backed by a HashMap |
Backed by a TreeMap |
Usage |
Use it when you don’t need a sorted order |
Use when you need elements in sorted order |
53. Define a Java program to reverse a string.
Program:
public class ReverseString {
public static void main(String[] args) {
String original = “Hello, World!”;
String reversed = reverseString(original);
System.out.println(“Reversed: ” + reversed);
}
public static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
}
54. What is the final keyword in Java?
The final keyword in Java is used to restrict the modification of variables, methods, and classes. It can be applied in three contexts:
- Final Variables: Prevents reassignment. Once a final variable is assigned, it cannot be changed.
- Final Methods: Prevents method overriding. A final method cannot be overridden by subclasses.
- Final Classes: Prevents inheritance. A final class cannot be subclassed.
55.Explain the difference between break and continue statements.
Feature |
break |
continue |
Usage |
Exits the loop or switch statement immediately |
Skips the current iteration and proceeds to the next iteration |
Control Flow |
Transfers control outside the loop |
Transfers control to the beginning of the loop |
Use Case |
Use to terminate a loop or switch statement early |
Use to skip certain iterations within a loop |
56.What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 2;
System.out.println(a / b);
}
}
Answer: 2
57. Explain the difference between static and non-static methods in Java.
Feature |
Static Methods |
Non-static Methods |
Access |
It can be called without creating an instance |
Requires an instance of the class to be called |
Usage |
Used for operations that don’t require data from an instance |
Used for operations that work on the instance data |
Memory Allocation |
Allocated memory only once when the class is loaded |
Allocated memory every time an instance is created |
Access to Members |
Can access static variables and other static methods directly |
Can access all variables and methods (including static) |
58. What are the advantages of Packages in Java?
Packages in Java provide several advantages:
- Namespace Management: Packages help avoid name conflicts by grouping related classes and interfaces into namespaces.
- Access Control: Packages allow you to define classes and methods with package-level access, which is not accessible outside the package.
- Reusability: By organising classes into packages, it becomes easier to reuse code.
- Maintenance: The packages help manage and maintain different large codebases by grouping them into their related functionality altogether.
- Modularity: By encapsulating related classes and interfaces modularity can be achieved by Packages, which helps to make the code more manageable and scalable.
59. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
double a = 5.0;
double b = 2.0;
System.out.println(a / b);
}
}
Answer: 2.5
60. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String text = “Java Programming”;
System.out.println(text.substring(5, 16));
}
}
Answer: Programming
61.What are the differences between C++ and Java?
Feature |
C++ |
Java |
Platform Dependency |
Platform-dependent (compiled to machine code) |
Platform-independent (compiled to bytecode) |
Memory Management |
Manual (using pointers) |
Automatic (using garbage collection) |
Multiple Inheritance |
Supported (using classes) |
Not supported (achieved using interfaces) |
Operator Overloading |
Supported |
Not supported |
Pointers |
Supported |
Not supported |
Global Variables |
Supported |
Not supported |
Templates/Generics |
Templates |
Generics |
62. What is a ClassLoader?
A ClassLoader in Java is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. It is a subsystem used to load class files. Java provides three built-in class loaders:
- Bootstrap ClassLoader
- Extension ClassLoader
- System/Application ClassLoade
63. What are the differences between Heap and Stack Memory in Java?
Feature |
Heap Memory |
Stack Memory |
Storage |
Stores objects and instance variables |
Stores method frames and local variables |
Memory Management |
Managed by the Garbage Collector |
Managed by the Java Virtual Machine (JVM) |
Lifespan |
Exists as long as the application runs |
Exists only for the duration of a method call |
Memory Allocation |
Dynamic (size can grow or shrink) |
Static (fixed size) |
Access Speed |
Slower access |
Faster access |
64. What are the Memory Allocations available in Java?
Java has several types of memory allocations:
- Stack
- Heap
- Program Counter (PC) Register
- Native Method Stack
65. Differentiate the constructors and Destructors.
Feature |
Constructors |
Destructors |
Purpose |
Initialise new objects |
Clean up resources before an object is destroyed (not present in Java) |
Invocation |
Called automatically when an object is created |
Called when an object is destroyed (not applicable in Java) |
Parameters |
Can have parameters (parameterised Constructors) |
N/A (Java uses finalize() for cleanup, but it is not recommended) |
Overloading |
Can be overloaded (multiple constructors) |
N/A |
Example Language |
Java, C++ |
C++ (Java does not have destructors) |
66. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Hello”);
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}
Answer:
true
false
true
67. What will be the output of the following code?
Program:
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 0;
try {
int z = x / y;
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero”);
} finally {
System.out.println(“This is the finally block”);
}
}
}
Answer:
Cannot divide by zero
This is the finally block
68. What will be the output of the following code?
Program:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
}
}
Answer:
[2]
69. List differences between the Set and List interface.
Feature |
Set |
List |
Order |
Does not maintain any order |
Maintains the insertion order |
Duplicates |
Does not allow duplicate elements |
Allows duplicate elements |
Access Methods |
No methods to access elements by index |
Allows access to elements by index |
Common Implementations |
HashSet, TreeSet, LinkedHashSet |
ArrayList, LinkedList |
Usage |
Ideal for unique elements |
Ideal for an ordered collection of elements |
70. Can you explain what happens if you don’t use the static modifier with the main method?
If you do not use the static modifier with the main method, the Java Virtual Machine (JVM) will not be able to invoke it as the entry point for the program. When you are using the main method, it must be public, static, and void for the JVM to start the execution of the program. Without using the static keyword, the main method would require an instance of the class to be created before it can be called. This will hinder the purpose of having a standard entry point to start the program execution, resulting in a runtime error.
71. What will be the output of the following code?
public class Main {
public static void main(String[] args) {
String s1 = “Java”;
String s2 = “Programming”;
String s3 = s1.concat(s2);
System.out.println(s3);
}
}
Answer:
JavaProgramming
72. Can we overload the main() method?
Yes, we can overload the main() method in Java. However, as the entry point of the program will be the public static void main(String[] args), the JVM will only call this main method with this exact signature. Any other overloaded versions of the main can be called from within the program using any other method but it will not be called by JVM.
73. What are the differences between Python and Java?
Feature |
Python |
Java |
Typing |
Dynamically typed |
Statically typed |
Syntax |
Easier and more concise |
More verbose |
Memory Management |
Automatic (Garbage Collection) |
Automatic (Garbage Collection) |
Use Cases |
Web development, scripting, data science |
Enterprise applications, Android development |
Inheritance |
Supports multiple inheritance directly |
Supports multiple inheritance via interfaces |
74. What are Packages in Java?
Packages can be defined as a set of different but related classes and interfaces that can provide any access protection in Java. It can also handle namespace management, making it an overall way to manage large codebases and their internal conflicting names.
75. How many types of packages are available in Java?
- Built-in Packages: They are provided by the Java API, such as java.util, java.io, etc.
- User-defined Packages: Created by programmers to bundle related classes and interfaces together.
76. What will be the output of the following code?
Program:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put(“A”, 1);
map.put(“B”, 2);
map.put(“A”, 3);
System.out.println(map.size());
System.out.println(map.get(“A”));
}
}
Answer:
2
3
77. What is the Wrapper class in Java?
The Wrapper class in Java provides a way to use primitive data types (int, char, etc.) as objects. Each primitive type has a corresponding wrapper class:
- int -> Integer
- char -> Character
- boolean -> Boolean
Wrapper classes are used in collections, where only objects are allowed, and to utilise utility methods provided by these classes.
78. How many ways can you take input from the console?
There are several ways to take input from the console in Java:
- Using Scanner class
- Using BufferedReader and InputStreamReader
- Using Console class
79. How are print, println, and printf different from each other?
Method |
Description |
Example Usage |
print |
Prints the text without a newline at the end |
System.out.print(“Hello”); |
println |
Prints the text with a newline at the end |
System.out.println(“Hello”); |
printf |
Prints formatted text using format specifiers |
System.out.printf(“Hello, %s!”, “World”); |
80. What are the main concepts of OOPs in Java?
The main concepts of Object-Oriented Programming (OOP) in Java are:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
81. Explain the differences between the constructors and methods.
Feature |
Constructors |
Methods |
Purpose |
Initialise new objects |
Define the behaviour and operations of objects |
Name |
Same as the class name |
Can have any name |
Return Type |
No return type |
Must have a return type (void or other) |
Invocation |
Called automatically when an object is created |
Called explicitly using the object |
Overloading |
Can be overloaded |
Can be overloaded |
82. What is an Interface?
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. Interfaces cannot contain instance fields or constructors. They are used to specify a set of methods that one or more classes must implement, promoting a form of multiple inheritance and providing a way to achieve abstraction.
Example:
public interface Animal {
void eat();
void sleep();
}
83. What is encapsulation in Java?
Wrapping the data or variables and the code that is acting upon the data methods together to form a single unit is called encapsulation in Java. The main advantage of encapsulation is to protect the data from any unauthorised access.
So that no one can modify the data without permission, which is a very important part of the project, it can be achieved through declaring variables as private using private keywords and also providing public getter and setter methods to access and update the values of those variables.
84.What do you mean by aggregation?
This can be understood as a form of association where there is a class reference to any other class, but both classes can exist without depending on each other. It represents a “has-a” relationship. For example, a Library has Books, but Books can exist independently of the Library.
85. Why are pointers not used in Java?
Pointers are not used in Java to maintain simplicity and security. One of the primary reasons for this is that most of the time, pointers can lead to complex code which is difficult for error handling. Situations like memory leaks and pointer arithmetic errors can occur due to pointers. Hence by eliminating pointers, Java provides a safer programming environment.
86. What is Synchronisation?
This is the mechanism which has shared control access according to resources to better manage the permission. It allows only one thread to access a synchronised block of code or any synchronised method block while executing a program, providing mutual exclusion.
87. What is multithreading in Java?
Multi-threading in Java is a feature that allows concurrent execution of two or more threads for maximum utilisation of the CPU. Each thread runs parallel to others, enabling multiple tasks to be performed simultaneously within a single program. Multi-threading is commonly used in applications where tasks are independent and can run simultaneously, such as web servers, GUI applications, and real-time systems.
88. What are the pros and cons of synchronisation?
Feature |
Pros |
Cons |
Thread Safety |
Ensures data consistency and prevents corruption |
This can lead to contention, reducing performance |
Predictability |
Provides controlled access to shared resources |
Increases complexity in code |
Consistency |
Guarantees that critical sections are executed in a controlled manner |
It can cause deadlocks if not handled properly |
Simplified Access |
Simplifies reasoning about concurrent code |
Can reduce scalability in highly concurrent systems |
89. What is the covariant return type?
The covariant return type allows a method in a subclass to override a method in its superclass and return a type that is a subclass of the return type declared in the superclass method. This enhances flexibility and reusability in method overriding.
Example:
class Animal {
Animal get() {
return this;
}
}
class Dog extends Animal {
@Override
Dog get() {
return this;
}
}
90. What is the transient keyword?
To showcase if the field should not be serialised, the transient keyword is used. When any object is serialised, transient fields are skipped and then they will not be a part of the object’s persistent state. This is useful for fields that contain sensitive information or are not needed after deserialization.
Example:
class User implements Serializable {
private String username;
private transient String password; // This field will not be serialised
}
91. What are the differences between the methods of sleep() and wait()?
Feature |
sleep() |
wait() |
Class |
Thread class |
Object class |
Purpose |
Pauses the current thread for a specified time |
Causes the current thread to wait until another thread invokes notify() or notifyAll() |
Synchronisation |
Do not release the lock |
Releases the lock on the object |
Usage |
Thread.sleep(milliseconds) |
object.wait() |
Exception |
Throws InterruptedException |
Throws InterruptedException |
92. What is an association?
Association in Java is a relationship between two classes that enables one class to use functionalities provided by another class. It represents a “uses-a” relationship. Association can be one-to-one, one-to-many, many-to-one, or many-to-many. It describes how objects of different classes interact with each other.
93. What will be the output of the following code?
Program:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList(“abc”, “bcd”, “cde”);
List<String> result = list.stream()
.filter(s -> s.startsWith(“b”))
.collect(Collectors.toList());
System.out.println(result);
}
}
Answer:
[bcd]
94. What is Polymorphism, and how can we achieve it?
Polymorphism refers to the ability of object-oriented programming to represent any object in many forms. It allows one interface to be used for a general class of actions and its types are:
- Compile-time Polymorphism (Method Overloading): This can be achieved by defining multiple methods using different parameters but with the same name within the same class.
- Runtime Polymorphism (Method Overriding): This refers to defining a method that has the same name and signature in the subclass just as the method in its superclass.
95. Explain the difference between Composition and Aggregation.
Feature |
Composition |
Aggregation |
Relationship Type |
Strong ownership and lifecycle dependency |
Weak ownership and an independent life cycle |
Lifespan |
The contained object’s lifespan depends on the container object |
Contained objects can exist independently |
Example |
A Car has an Engine (composition) |
A Library has Books (aggregation) |
Implementation |
Contained object created within the container |
Contained object passed to the container |
Use Case |
Use when contained objects should not exist independently |
Use when contained objects can exist independently |
96. What are the different interfaces of the Collection framework?
The main interfaces of the Java Collection framework are:
- Collection: The root interface for most of the collection classes.
- List: Ordered collection (also known as a sequence) that allows positional access and insertion.
- Set: Collection that cannot contain duplicate elements.
- Queue: Collection used to hold multiple elements prior to processing.
- Deque: Double-ended queue that allows insertion and removal at both ends.
- Map: This maps keys to values without allowing any duplicate keys.
97. What will be the output of the following code?
Program:
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of(“apple”, “banana”, “cherry”)
.filter(s -> s.contains(“a”))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Answer:
APPLE
BANANA
98. What is a Vector in Java?
A vector can be a dynamic array that does not have any fixed size, i.e. it can grow or shrink in size according to the data input. Vectors are generally synchronised and thread-safe, hence they can be applied safely in multi-threaded environments. However one of the drawbacks of this is slow performance speed because of synchronisation.
Features of Vector:
- Automatically resizes itself when elements are added or removed.
- Allows duplicate elements.
- Maintains insertion order.
- Provides methods to add, remove, and access elements.
99. How to make Java ArrayList Read-Only?
Here you should use the Collections.unmodifiableList to make a Java ArrayList read-only. This method helps prevent any unnecessary modifications by returning an unmodified view of the specified list.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add(“A”);
list.add(“B”);
list.add(“C”);
List<String> readOnlyList = Collections.unmodifiableList(list);
System.out.println(readOnlyList); // Output: [A, B, C]
// The following line will throw UnsupportedOperationException
// readOnlyList.add(“D”);
}
}
100. What is a priority queue in Java?
This is a type of queue where you can put each element with a certain order or criteria, natural ordering or also by a comparator ordering at the time of queue construction. In the queue, the last element will be the head according to the specified ordering and elements are dequeued in the same order.
Features of PriorityQueue:
- Does not permit null elements.
- Unbounded, but has an initial capacity.
- Not thread-safe (use PriorityBlockingQueue for thread safety).
- Elements are ordered either according to their natural ordering or by a comparator.
101. What is the difference between Iterator and ListIterator?
Feature |
Iterator |
ListIterator |
Applicable Collections |
All Collection types |
Only List types |
Traversal Direction |
One-way traversal (forward) |
Two-way traversal (forward and backwards) |
Add Elements |
Cannot add elements |
Can add elements |
Modify Elements |
Can remove elements |
Can remove and set elements |
Methods |
hasNext(), next(), remove() |
hasNext(), next(), hasPrevious(), previous(), add(), set(), remove() |