Technical Questions Based On Core JAVA
Technical Questions Based On Core JAVA
• What is a JVM?
• It is:
JDK (Java Development Kit): It is a software development kit that includes tools for
developing, compiling, and debugging Java applications. The JDK includes the JRE
(Java Runtime Environment), which contains the JVM, libraries, and other necessary
components to run Java applications.
Java and Pointers: Java does not have explicit pointer support like languages such as C
or C++. Instead, it uses references to objects. In Java, you can manipulate objects
indirectly through references, but you don't have direct access to memory addresses.
This helps in preventing certain types of errors like buffer overflows and enhances
security.
These are the basic building blocks for storing simple values in arrays. Unlike objects,
primitive data types are not instances of classes in Java.
By convention, constant variable names are often written in uppercase letters with
underscores separating words, providing a visual cue that they are constants. The
`final` keyword ensures that the variable cannot be reassigned once it has been given a
value.
• Does the order of public and static declaration matter in main() method?
Yes, the order of `public` and `static` declarations in the `main()` method matters in
Java. The correct order is `public static void main(String[] args)`. The `public` and
`static` modifiers must appear before the return type (`void`) in the method signature.
The specific order is part of the syntax required by Java for the `main()` method to
serve as the entry point for the program.
• What is a package?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
• Can a class that has been declared as private be accessed outside its package?
The private modifier specifies that the member can only be accessed in its own class.
The protected modifier specifies that the member can only be accessed within its own
package (as with package-private) and, in addition, by a subclass of its class in another
package.
• If we do not want our class to be inherited by any other class what should we do?
To prevent a class from being inherited by any other class, declare it with the final
keyword. This makes the class final, and it cannot be extended by other classes.
• Can you give few examples of final classes defined in Java API?
A few examples of the final classes are string, integer, and other wrapper classes.
• Differentiate final from finally and finalize()?
final: Used to declare a variable, method, or class. It indicates that a variable cannot be
reassigned, a method cannot be overridden, or a class cannot be subclassed.
finalize(): A method in the Object class. It is called by the garbage collector before an
object is reclaimed. It can be overridden to provide cleanup operations for an object
before it is garbage-collected. However, it is not commonly used due to its limitations
and unpredictability.
1. Static Methods: A method declared with the `static` keyword is associated with the
class rather than with instances of the class. It can be invoked using the class name
without creating an instance of the class.
2. Access to Class-Level Data: Static methods can only access static variables and other
static methods within the same class. They cannot access instance variables directly.
3. Main Method: The `main()` method, which serves as the entry point for a Java
application, is a commonly used static method.
4. Utility Methods: Static methods are often used for utility functions that do not rely on
the state of an instance but perform a general-purpose task.
Using the `static` keyword in method declarations allows them to be associated with the
class itself rather than instances of the class.
• What are the restrictions imposed on a static method or a static block of code?
restrictions on static methods and static blocks in Java include limited access to instance
members, inability to use this and super keywords, direct access only to static members,
inability to call non-static methods directly, and considerations regarding initialization
order in static blocks.
• If you want to to print "Hello" even before main() is executed, how will you achieve that?
To print "Hello" before `main()` is executed, you can use a static block. Code inside a static
block is executed when the class is loaded, even before the `main()` method. Here's a short
example:
public class MyClass {
static {
System.out.println("Hello");
}
public static void main(String[] args) {
// Rest of the main method
}
In this example, "Hello" will be printed when the class `MyClass` is loaded, before the
`main()` method is executed.
In your example, Class C has provided an implementation for method m2, and it's
acceptable. You can create an object of Class C, and it will be a valid instance of both
Class C and Interface I. However, keep in mind that any class that extends Class C or
uses objects of Class C will need to provide implementations for any remaining abstract
methods declared in Interface I (in this case, method m1).
interface ParentInterface {
void methodA();
}
• What is Externalizable?
Externalization serves the purpose of custom Serialization, where we can decide what to
store in stream. Externalizable interface present in java.io, is used for Externalization
which extends Serializable interface.
• What value does read() return when it reaches the end of a file?
the read() method in Java returns -1 when it reaches the end of a file. This is a standard
convention used in input streams to indicate the end of the stream or file.
This is possible because there is a widening conversion from byte to double in Java.
• Differentiate between a static and a non-static inner class?
Static Inner Class:
• Associated with the outer class, but it's a static member.
• Can be instantiated without creating an instance of the outer class.
• Cannot directly access non-static members of the outer class.
• Doesn't have a reference to an instance of the outer class.
• Commonly used for grouping utility classes or when an inner class doesn't
require access to the outer class's instance.
1. Intrinsic Lock: The lock associated with an object is often referred to as its intrinsic
lock or monitor.
4. Every Object Has a Lock: Every Java object, including instances of user-defined
classes and built-in classes, has a lock associated with it.
5. Reentrant: The lock associated with an object is reentrant, meaning that a thread
holding the lock can reacquire it without blocking itself.
In this example, the lock used by the `synchronizedMethod()` is associated with the
instance of the `Example` class.
1. Interface Implementation: The class of the object being referenced must implement
the interface to which you are casting.
interface MyInterface {
void myMethod();
}
interface SuperInterface {
void superMethod();
}
interface SubInterface extends SuperInterface {
void subMethod();
}
It's important to ensure that the object being cast is indeed an instance of the interface,
or a `ClassCastException` may occur at runtime. This can be checked using the
`instanceof` operator before performing the cast.
• Which non-Unicode letter characters may be used as the first character of an identifier?
the first character of an identifier in Java can be a Unicode letter, underscore (_), or
dollar sign ($). It is not limited to English letters and may include letters from various
languages.
• What are the restrictions placed on method overloading?
- Overloaded methods must have a different method signature.
- The method signature includes the method name and parameter types.
- Return type alone is not sufficient to differentiate overloaded methods.
- If a method has varargs, it should be the last parameter.
- Overloaded methods can have the same or different return types.
- Changing only the return type is not sufficient for overloading.
- Overloaded methods can have different access modifiers and throw different
exceptions.
- Understanding these restrictions ensures clarity and avoids ambiguity in overloaded
methods.
• What is casting?
the conversion of one data type into another; for example, from an integer to a string or
vice versa. The casting statement in the source code of a program causes the compiler to
generate the machine code that performs the actual conversion. See data type, integer
and string.
Here, `void` indicates that the `main()` method does not return any value.
-Not Accessible Outside the Class: The `private` variable is not accessible from outside
the class, as shown in the following example:
- Protected: Members with `protected` access modifier are accessible within the same
package and by subclasses, regardless of whether they are in the same package or a different
one.
- Public: Members with `public` access modifier are accessible from any class, regardless of
the package. They have the widest visibility.
• Explain Downcasting
downcasting in Java is the process of casting a reference of a superclass type to a
reference of a subclass type. It allows you to access the specific methods or fields of the
subclass that are not available in the superclass.
• What modifiers may be used with an inner class that is a member of an outer class?
the modifiers that may be used with an inner class (a member of an outer class) in Java
are:
1. Private: Inner classes can be private, limiting their access to the outer class only.
2. Protected: Inner classes can be protected, allowing access within the same package
and by subclasses.
public class Outer {
protected class Inner {
// Inner class implementation
}
}
4. Public: Inner classes can be public, allowing access from any class.
These modifiers determine the visibility and accessibility of the inner class in relation to
other classes within and outside the package.
• How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
• ASCII uses 7 bits.
• Unicode can use 16 or 32 bits, depending on the encoding (UTF-16 or UTF-32).
• UTF-16 uses 16 bits (2 bytes) for most characters.
• UTF-8 uses variable-width encoding, with 8 bits for common ASCII characters
and variable lengths for others.
• What are the restrictions placed on the location of a package statement within a source code
file?
The restriction that is placed is that the package statement must appear as the first line
in a source code file (excluding blank lines and comments).
• What are order of precedence and associativity and how are they used?
Order of Precedence:
• Determines the evaluation sequence of operators.
• Higher precedence operators are evaluated first.
• Crucial for correct expression evaluation.
• Example: In a + b * c, * has higher precedence than +.
Associativity:
• Defines the order of evaluation for operators with the same precedence.
• Left-to-right or right-to-left associativity.
• Determines the direction of operation in a sequence.
• Example: In a - b + c, + and - have left-to-right associativity.
• Which characters may be used as the second but not as the first character of an identifier?
In Java, the characters that may be used as the second but not as the first character of
an identifier are:
1. Digits (0-9): Digits can be used as the second character and beyond, but not as the
first character.
// Valid identifiers
int num1;
char c2;
String str3;
2. Underscore (_): Underscore can be used as the second character and beyond.
// Valid identifiers
int _count;
String _name;
These rules are important for following Java naming conventions and ensuring that
identifiers are valid.
• Is the ternary operator written x : y ? z or x ? y : z ?
The correct syntax for the ternary operator in Java is:
x?y:z
So, it is written as `x ? y : z`. This syntax signifies that if the boolean expression `x` is
true, then the result is `y`; otherwise, the result is `z`.
Example:
int result = 7 / 2; // Result is 3, not 3.5
Here, `7 / 2` results in `3`, as the fractional part (`0.5`) is truncated, and the result is
rounded towards zero.
• If a class is declared without any access modifiers, where may the class be accessed?
If a class is declared without any access modifiers (i.e., no `public`, `private`, or
`protected` keyword), it is assigned package-private access by default. This means the
class can be accessed within the same package but not from outside the package.
In this example, the `Subclass` inherits the constructor `Superclass(int x)`, and the
`Subclass` constructor uses `super(y)` to invoke the constructor of the `Superclass` with
a parameter.
These primitive types are not objects and are used to store simple values directly. They
have no methods or additional properties.
• What are the restrictions that are placed on the values of each case of a switch statement?
In a switch statement in Java, there are several restrictions and rules placed on the
values of each case:
2. Unique Values: Each case value must be unique within the switch statement.
Duplicate case values are not allowed.
switch (variable) {
case 42:
// Case implementation
break;
case 42: // Error: Duplicate case value
// Case implementation
break;
}
3. Compile-Time Constant: The expression used in each case label must be a compile-
time constant. This means it must be known at compile-time.
4. No Falling Through: Unlike some other languages, Java does not allow "fall-
through" behavior between case labels. Each case should end with a break statement or
another control-flow statement like return.
switch (variable) {
case 42:
// Case implementation
// No break; // Error: Fall-through is not allowed
case 43:
// Case implementation
break;
}
These restrictions ensure the clarity and predictability of switch statement behavior in
Java.
1. `while` Statement:
- Condition is checked before the loop body is executed.
- If the condition is initially false, the loop body may not execute at all.
while (condition) {
// Loop body
}
2. `do-while` Statement:
- Condition is checked after the loop body is executed.
- The loop body always executes at least once, even if the condition is initially false.
do {
// Loop body
} while (condition);
Example:
public class Outer {
public void outerMethod() {
final int localVar = 42; // Local variable
In this example, the `LocalInner` class is a local inner class with the `final` modifier on
the local variable `localVar`.
• When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class under the following conditions:
1. No Constructors Defined: If a class does not have any constructors explicitly defined,
the compiler automatically provides a default constructor.
- Access Within the Same Package: The method can be accessed by any class within the
same package, whether it is a subclass or not.
package mypackage;
- Access in Subclasses: The method is also accessible to subclasses, even if they are in a
different package.
package mypackage;
However, it's important to note that methods declared as `protected` are not accessible
from classes outside the package unless they are subclasses of the class declaring the
protected method.
2. Class or Interface Type:** The right operand must be a class or interface type,
indicating the type to check against.
3. Null: The `null` value can be used with the `instanceof` operator. In this case, it
always evaluates to `false`.
These legal operands make it possible to check the type of an object dynamically during
runtime, helping to perform type-safe operations.
Example usage:
boolean isTrue = true;
boolean isFalse = false;
if (isTrue) {
// Code block executed when the condition is true
} else if (!isFalse) {
// Code block executed when the condition is false
}
In this example, `true` and `false` are used as boolean literals in the initialization of
`isTrue` and `isFalse` variables, and they are also used in the conditional statements.
- Nested Class:
- A broader term that includes inner classes.
- Sometimes used specifically for static nested classes.
- Can access outer class members.
In essence, all inner classes are nested classes, but not all nested classes are necessarily
inner classes.
Example:
int intValue = 5;
double doubleValue = 2.5;
Public Class:
1. Access: Accessible from any other class.
2. Package: Can be in any package.
3. Inheritance Can be subclassed by classes in any package.
4. Visibility: Members (fields, methods) are visible to all classes.
5. Modifiers: Declared using the `public` access modifier.
Non-Public Class:
1. Access: Accessible only within the same package (package-private), within subclasses
(protected), or within the same class (private).
2. Package: Often part of a specific package.
3. Inheritance: Can be subclassed only by classes in the same package (package-
private), subclasses, or classes within the same package (protected), or not subclassed at
all (private).
4. Visibility: Members are visible only within the allowed scope (package, subclass, or
class).
5. Modifiers: Declared using package-private (`default`), `protected`, or `private` access
modifiers.
The choice between a public and a non-public class depends on the desired level of
encapsulation and the intended usage of the class within or outside its package.
Example:
public class Example {
boolean myBoolean; // Automatically initialized to false
Prefix (++i):
1. Increment and Use: Increments the value of the variable before its current value is
used in the expression.
2. Order of Operations: The increment operation is performed first, and then the
updated value is used.
3. Example:
int i = 5;
int result = ++i; // Increment i before using its value
// i is now 6, result is 6
Postfix (i++):
1. Use and Increment: Uses the current value of the variable in the expression and then
increments the value.
2. Order of Operations: The current value is used first, and then the increment
operation is performed.
3. Example:
int i = 5;
int result = i++; // Use the current value of i, then increment
// i is now 6, result is 5
1. `public`:
- The class is accessible from any other class.
- It can be used by classes in different packages.
2. `default` (Package-Private):
- If no access modifier is specified, the default access level is package-private.
- The class is accessible only within the same package.
class DefaultClass {
// Class members
}
3. `final`:
- The class cannot be subclassed or extended.
public final class FinalClass {
// Class members
}
4. `abstract`:
- The class may have abstract methods that are meant to be implemented by
subclasses.
- It cannot be instantiated on its own.
5. `strictfp`:
- The class, including its methods, adheres to strict floating-point precision according
to the IEEE 754 standard.
These modifiers control the visibility, inheritance, and behavior of the top-level class in
the context of access and polymorphism in Java.
`if` Statement:
1. Conditional Expression:
- Usage: Used for conditional execution based on a boolean expression.
- Conditions: Supports complex conditions using relational and logical operators.
int x = 5;
if (x > 0) {
// Code block executed if x is greater than 0
} else if (x == 0) {
// Code block executed if x is equal to 0
} else {
// Code block executed for other cases
}
2. Expression Type:
- Flexible: Can handle various conditions and expressions.
- Type: Works with boolean expressions.
`switch` Statement:
1. Expression Value:
- Usage: Used for conditional execution based on the value of an expression.
- Expression: Evaluates the expression once and compares it to constant values.
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
// Code block executed for Monday
break;
case 2:
// Code block executed for Tuesday
break;
// ... other cases ...
default:
// Code block executed for other cases
}
2. Expression Type:
- Limited: Works with expressions that evaluate to byte, short, char, int, String, or
enums.
- Constant Values: Each `case` must be a constant value.
3. Fall-Through Behavior:
- Fall-Through: Without a `break` statement, control falls through to the next case.
- Default: The `default` case is optional and serves as the default action.
In summary, `if` statements are more flexible and can handle a variety of conditions,
while `switch` statements are designed for situations where a single expression is
compared to constant values, and fall-through behavior might be desired.
• What are the practical benefits, if any, of importing a specific class rather than an entire
package (e.g.
Importing specific classes rather than entire packages in Java provides benefits such as
reduced namespace pollution, improved code readability, prevention of name conflicts,
potentially faster compilation, and easier maintenance by explicitly specifying and
managing dependencies.
import java.net.*;
// Now, all classes in java.net are available without qualification
- `import java.net.Socket;`:
- Imports only the specific `Socket` class from the `java.net` package.
- Avoids namespace pollution and clearly indicates the used class.
import java.net.Socket;
// Only the Socket class from java.net is available without qualification
In practice, it's recommended to import only the specific classes needed to minimize
potential naming conflicts and enhance code readability.
• Can we overload a method based on different return type but same argument type?
No, in Java, method overloading is not allowed solely based on different return types.
Overloading requires differences in the method signature, and the return type alone is
not considered when determining method signatures.
Two methods are considered to have the same signature if they have the same method
name and the same parameter types. The return type is not considered in this
determination.
Example of disallowed method overloading:
// Compiler error: "Method 'sum(int, int)' has the same erasure 'sum(int, int)' as
another method in type 'Example'"
double sum(int a, int b) {
return a + b;
}
}
In the example above, attempting to overload the `sum` method based on the return
type results in a compilation error because the parameter types are the same. Method
overloading in Java is based on the method signature, which includes the method name
and parameter types, but not the return type.
Example:
public class Example {
static {
// First static initializer block
System.out.println("First static initializer");
}
static {
// Second static initializer block
System.out.println("Second static initializer");
}
• What is the difference between the Boolean & operator and the && operator?
`&` (Boolean AND) Operator:
1. Performs a bitwise AND operation on integral types.
2. Evaluates both sides of the expression regardless of the first operand's value.
3. Does not short-circuit the evaluation; both operands are always evaluated.
4. Can be applied to boolean values, but it is not commonly used for boolean conditions.
Example:
int a, b, c;
a = b = c = 5;
In this example, the right-associative nature of the assignment operator means that `c =
5` is evaluated first, followed by `b = c` and finally `a = b`. The value `5` is assigned to
all three variables (`a`, `b`, and `c`).
• Can a double value be cast to a byte?
Yes, a `double` value can be cast to a `byte` in Java, but it involves explicit type casting.
However, keep in mind that this conversion may result in loss of precision and possible
truncation, as a `double` has a wider range and precision than a `byte`.
Example:
double doubleValue = 123.456;
byte byteValue = (byte) doubleValue;
It's important to be cautious when creating loops to avoid unintended infinite loops, as
they can lead to program execution never reaching subsequent code and may cause the
program to become unresponsive.
Example:
public class Example {
String str; // Automatically initialized to null
In the example above, both the instance variable `str` and the local variable `localStr`
are automatically initialized to `null` if not explicitly assigned a value.
`this()` in Constructors:
- Used to call another constructor within the same class.
- Must be the first statement in the constructor.
- Enables constructor chaining within the same class.
Example:
public class MyClass {
private int value;
// Parameterized constructor
public MyClass(int value) {
this.value = value;
}
`super()` in Constructors:
- Used to call a constructor in the superclass.
- Must be the first statement in the subclass constructor.
- Enables the initialization of the superclass part of an object.
Example:
public class MyBaseClass {
private int baseValue;
In summary, `this()` is used for constructor chaining within the same class, while
`super()` is used for invoking a constructor in the superclass. Both must be the first
statement in the constructor.
- Final Method:
- A method declared as `final` cannot be overridden by subclasses.
- Ensures that the method's implementation remains unchanged in any derived classes.
-Final Variable:
- A variable declared as `final` cannot be reassigned once it's initialized.
- Implies a constant value that cannot be modified after the initial assignment.
- Abstract Method:
- An abstract method is declared using the `abstract` keyword and lacks a method
body.
- Exists within an abstract class.
- Subclasses must provide concrete implementations for abstract methods.
- Serves as a blueprint, ensuring consistency in derived classes.
In essence, an abstract class provides a structure for its subclasses, and abstract
methods within that class define a contract that must be fulfilled by any concrete
subclasses. Instances of abstract classes cannot be created directly, and their purpose is
to be extended by subclasses that provide specific implementations for abstract
methods.
• What is a transient variable?
A transient variable in Java is a variable marked with the transient keyword. It
indicates that the variable should not be serialized when the object to which it belongs is
serialized. When an object is serialized (converted into a byte stream), transient
variables are skipped and not included in the serialization process. This is commonly
used for variables that should not be persisted or need special handling during the
serialization and deserialization processes.
For example, consider the `int` data type in Java, which is a 32-bit signed integer. If an
operation results in a value exceeding the maximum positive or minimum negative
representable value, it will wrap around to the opposite extreme value:
Similarly, if a value goes below the minimum representable value, it wraps around to
the maximum positive value:
int minValue = Integer.MIN_VALUE; // -2147483648
int underflowedValue = minValue - 1; // Wraps around to Integer.MAX_VALUE
(2147483647)
Example:
int x = -8;
int result1 = x >> 1; // Result: -4 (sign bit is filled)
int result2 = x >>> 1; // Result: 2147483644 (zeros are filled)
In this example, `>>` preserves the sign bit, resulting in a negative number, while `>>>`
treats the value as non-negative and fills with zeros, producing a positive number.
• Is size of a keyword?
No, "size" is not a keyword in Java. Keywords in Java are reserved words that have a specific
meaning and cannot be used as identifiers (such as variable names or method names). Examples
of Java keywords include `int`, `class`, `if`, `else`, `return`, and so on.
If you are referring to determining the size of data types or objects in Java, you can use methods
provided by the `java.lang.instrument` package or libraries like Java's Instrumentation API for
more advanced memory measurement. Additionally, you might consider using profilers or
memory analysis tools for more comprehensive insights into the memory usage of your Java
program.