Java is a high-level, object-oriented programming language . It was designed to be platform-independent, meaning that Java programs can run on any device or operating system that has a Java Virtual Machine (JVM) installed.Â
- Platform Independence
- Object-Oriented
- Simple and Familiar Syntax
- Automatic Memory Management
- Robust and Secure
- Multi-threading Support
In Java, the static keyword is used to declare members (variables and methods) that belong to the class as a whole rather than specific instances (objects).
In object-oriented programming (OOP), adoption allows a subclass or derived class to inherit attributes and behaviors (methods and variables) from another class (superclass or base class). Inheritance promotes code reuse, modularity, and the creation of hierarchical relationships between classes.Â
In Java, the static keyword is used to declare members (variables and methods) that belong to the class as a whole rather than specific instances (objects).
The main purposes of the static keyword in Java are as follows:
- Creating Class-Level Variables
- Accessing Variables and Methods Without Instance Creation
- Sharing Common Data Among All Instances
- Memory Efficiency
In Java, the super keyword allows access to superclass members that are usually hidden by subclass methods or variables. It is also used to invoke the superclass constructor via the subclass constructor. This promotes code reuse and subclass customisation while retaining access to superclass features.
In Java, method overloading refers to the ability to set up numerous methods with the same name but distinct parameter lists. These methods may have varying numbers or types of parameters. When you call an overloaded method, Java selects which version of the method to execute based on the arguments passed.
In Java, method overriding happens when a subclass provides a custom implementation of a method specified in its superclass. When overriding a method, certain requirements must be observed to guarantee proper behaviour.
Rules of method overriding:
- Method Signature
- Access Modifier
- Exception Handling
- Return Type
- Static Methods
- Final Methods
Literals are constants that are explicitly written into code. They indicate fixed values that remain constant throughout the program’s operation. In Java, literals can represent a variety of data types, including integers, floating-point numbers, characters, strings, and logical values.
Tokens are the smallest units of a Java program and act as building blocks for code construction.
class, public, private, protected, static, final, abstract, interface, extends, implements, super
Constructors cannot be overridden in Java. In Java, constructors are not subject to the same adoption rules as methods. Each class in Java has its own constructor, which subclasses learn from its superclass. However, constructors cannot be overridden or inherited in the same way that methods can.
The Java Virtual Machine (JVM) maintains memory in a hierarchy that is made up of multiple memory sections, each with a distinct purpose.
The method signature public static void main(String[] args) sets the Java program’s entry point. The String[] the arguments option allows the application to accept command-line arguments when run from the command line. These arguments can be used to provide input or configuration to the program during runtime.
Local Variables:
- Local variables are defined in a particular section of code, such as a method, constructor, or block within a method (contained in curly braces {}).
- They are only available within the block in which they are declared, and they disappear after the block is executed
- Local variables are commonly used for temporary storage or calculations in a specific context.
Global Variables (Instance Variables):
- Global variables, also known as instance variables, are declared within a class but not in a method, constructor, or block.
- They are accessible to all methods, constructors, and blocks in the class.
- Global variables are associated with class objects and keep their values for the duration of the object’s existence.
- CharAt(int index)
- Length()
- Substring(int beginIndex):Â
- Substring(int beginIndex, int endIndex):
- Concat(String str)
- toLowerCase
Yes, you can overload a static method in Java. Method overloading is the process of defining multiple methods in a class that have the same name but different argument lists. These methods, including static methods, can have a variety of parameter counts and kinds.
In Java, access modifiers are keywords that regulate the accessibility or visibility of classes, variables, methods, and constructors inside a program. There are four main access modifiers:
Public
In Java, access modifiers are keywords that regulate the accessibility or visibility of classes, variables, methods, and constructors inside a program. There are four main access modifiers:
Protected
The protected access modifier restricts access to a class, method, or variable to subclasses (through inheritance) and other classes in the same package.
Default
The default (no modifier) access modifier limits access to a class, method, or variable to classes from the same package.
Private:
The private access modifier limits access to a class, method, or variable to members of the same class.
- Creating Class-Level Variables
- Accessing Variables and Methods Without Instance Creation
- Sharing Common Data Among All Instances
- Memory Efficiency
In object-oriented programming (OOP), adoption allows a subclass or derived class to inherit attributes and behaviours (methods and variables) from another class (superclass or base class). Inheritance promotes code reuse, modularity, and the creation of hierarchical relationships between classes.
In Java, the static keyword is used to declare members (variables and methods) that belong to the class as a whole rather than specific instances (objects).
The main purposes of the static keyword in Java are as follows:
- Creating Class-Level Variables
- Accessing Variables and Methods Without Instance Creation
- Sharing Common Data Among All Instances
- Memory Efficiency
In object-oriented programming (OOP), adoption allows a subclass or derived class to inherit attributes and behaviours (methods and variables) from another class (superclass or base class). Inheritance promotes code reuse, modularity, and the creation of hierarchical relationships between classes.Â
In Java, the final keyword is used to restrict classes, methods, and factors, indicating that they cannot be modified or overridden once started.Â
The final keyword performs many functions depending on where it is used.
Final Variables:
- When applied to a variable, the final keyword guarantees that the variable’s value cannot be modified once initialized.
- When a final variable is assigned a value, it becomes a constant, and any attempt to assign a new value to it produces a compilation error.
- Final parameters are frequently employed to specify constants or unchanging values that should not be changed throughout the program.
Final Methods
- When applied to a method, the final keyword specifies that it cannot be overridden by subclasses.
- Final methods are stable and ensure that the method’s behavior is constant across all subclasses.
- Final methods are frequently used in design patterns or key system classes when specific methods should not be changed or extended.
Final Classes:
- When added to a class, the final keyword specifies that it cannot be subclassed or extended by other classes.
- Final classes ensure integrity and prevent modification or extension of their functionality.
- Final classes are frequently used in utility classes, immutable classes, and classes with sensitive implementations that must not be changed.
Garbage collection in Java is an automatic memory management method that detects and frees memory that is no longer in use by the program. It is important for managing memory resources and reducing memory leaks and mistakes in Java programs. Here is a description of how garbage collection works in Java.
There are several types of inheritance, including:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Multiple Inheritance (through Interfaces)
- Hybrid (or Virtual) Inheritance
Yes it is required to have catch block for each try block
An abstract class in Java is one that cannot be created on its own but must be subclassed by other classes. It acts as a template for other classes to follow, as well as providing shared behaviour and structure among subclasses. Any class which has both abstract methods and concrete methods(static and non static)Â is called Abstract class.Â
- Primitive Type Casting
- Class Type Casting.
In Java, the super keyword refers to the current class’s superclass . It can be used in a variety of circumstances, including accessing superclass members, calling superclass constructors, and calling superclass methods.
In Java, a constructor is a particular sort of function used to initialise class objects. It uses the same name as the class and has no return type, not even empty. When the new keyword is used to create a class object, constructors are automatically executed.
No, downcasting can’t happen implicitly in Java. Because, Downcasting is the process of transforming a superclass reference to a subclass reference. This conversion is not safe by default since the subclass may include fields or methods not found in the superclass.
In Java, constructor overloading refers to stating many constructors within a class, each with a different argument list. This allows the class to provide multiple methods for setting up objects depending on different argument combinations.
        Abstract Classes |
            Interfaces |
An abstract class is one that cannot be created on its own and can include both abstract (unimplemented) and concrete (implemented) methods. | An interface is an object type in Java that only consists of abstract methods, constants, and default methods. |
Abstract classes can include constructors, member factors, and ordinary methods in addition to abstract methods. |
Interfaces cannot include constructors, instance variables, or concrete methods. |
Subclasses of an abstract class must either implement all of the abstract methods defined in the abstract class, or be labeled abstract. | Classes implement interfaces by providing implementations for all of the abstract methods defined in the interface. |
Yes, We can overload non-static methods in Java. Method overloading is a feature in which a class can have multiple methods with the same name but different argument lists. These methods may have varying numbers or types of parameters. Overloading non-static methods allows you to provide multiple instances of a method within a class, each with different input parameters or tasks.
Yes, we can overload Java constructors. Constructor overloading is a concept that allows a class to have multiple constructors that have different argument lists. Each constructor may begin an object in a unique way depending on the inputs supplied to it. This allows for flexibility in object creation and initialization inside the same class.
Yes, in general, Java queues support duplicate values. A queue is a data structure that uses the First-In-First-Out (FIFO) principle, in which elements are added to the back (end) and removed from the front (beginning) of the queue.
In Java, an interface is a reference type that, like a class, provides a set of abstract methods that any classes that implement the interface must implement. It acts as a contract or blueprint for implementing classes, defining a set of methods that must be provided by those classes.
Yes, we can overload the main method in Java. Overloading is the process of defining numerous methods in the same class that share the same name but have different argument lists. Java allows you to specify many main methods, each with a different parameter type.
In Java, throw and throws are both used in exception handling, but they serve different purposes:
throw:
When you find an uncommon condition or problem in your code that needs to be handled, you can use the throw keyword to manually raise (or “throw”) an exception.
throws:
The throws keyword in a method declaration indicates that the method may throw one or more exceptions.
In Java, narrowing conversion means changing a data type with a bigger range to a data type with a shorter range. This may result in data loss or precision. Narrowing conversions are generally clear and require the use of explicit casting.
Here Java does not execute implicit narrowing conversions because they can cause data loss, and Java promotes type safety. As a result, narrowing conversions must always be performed directly, using explicit casting.
Yes, a super calling statement can be both parameterized and non-parameterized in Java.
We go for collection in Java due to several reasons:
- Dynamic Size
- Built-in Operations
- Type Safety
- Generic Support
- Performance
In Java, this keyword refers to the current object within a function or constructor. It allows you to access instance variables, execute methods, and call the current object’s constructors. This keyword is especially useful in situations where instance variables and parameters share the same name, allowing you to distinguish between them.
this calling statement:
In Java, this keyword refers to the current object within a function or constructor. It allows you to access instance variables, execute methods, and call the current object’s constructors. This keyword is especially useful when instance variables and parameters share the same name, allowing you to distinguish between them.
try Block:
- The try block includes the code that is possibly capable of throwing an exception.
- It encloses the statements that need to be monitored for exceptions.
- If an exception occurs within the try block, the flow of execution is switched to the catch block.
Catch Block
- The catch block follows the try block and contains code to handle the exception thrown within the try block.
- Multiple catch blocks can be used to handle various types of exceptions, allowing for more detailed error handling.
- When an exception is caught in a catch block, the code inside the catch block is performed to handle the exception, such as recording an error message or recovering from the exceptions
finally Block:
- If present, the finally block comes after the catch block and contains code that will be executed regardless of whether an exception occurs.
- It is commonly used to free up resources, perform cleanup tasks, or verify that specific code is executed regardless of whether an exception occurs.
- The finally block is important for activities such as closing file handles, releasing database connections, and freeing allocated resources.
Lambda expressions, introduced in Java 8, are a feature that allows you to pass functionality as a method argument or build anonymous functions in Java. Lambda expressions allow you to represent instances of single-method interfaces (also known as functional interfaces) more compactly and simply.
Here’s how lambda expressions are used in Java:
Syntax:
- Lambda expressions consist of three parts: parameters, an arrow (->), and a body. The body can be a single expression or a block of code.
- Syntax: (parameters) -> expression or (parameters) -> { statements; }
Functional Interfaces:
- Lambda expressions are most typically used with functional interfaces, which contain only one abstract method.
- Lambda expressions provide a convenient approach to implement a functional interface’s abstract method inline, avoiding the need to build a new class or explicitly implement the interface.
Arrays in Java provide numerous benefits, including simplicity, random access, and memory efficiency.
Â
Also they have some disadvantages:
- Fixed Size
- Lack of Flexibility
- Inefficient Insertions and Deletions
- Inefficient Search
- No Built-in Methods
- Memory Management
Yes, a constructor in Java can be both parameterized and non-parameterized.
In Java, the synchronized keyword is used for thread synchronization, which means that only one thread can access a block of code or an object’s important area at a time. In a multithreaded context, the synchronized keyword provides mutual exclusion by excluding several threads from changing shared data or resources at the same time.
In Java, multithreading allows many threads to run concurrently within the same program, allowing for parallelism and efficient resource use. Multithreading in Java is generally accomplished using the Thread class and the Runnable interface.
Thread Class:
-
The Thread class in Java is a built-in class provided by the Java platform and is found in the java.lang package.
-
It represents a thread of execution or a distinct path of execution within a Java program.
Runnable Interface:
-
The Runnable interface in Java is a functional interface found in the java.lang package.
-
It represents a task or unit of labor that can be carried out by a thread.
Multiple inheritance is not explicitly supported in Java due to the possibility for confusion and difficulty in resolving issues that may arise when a class inherits from multiple superclasses. There are various reasons why multiple inheritance is not allowed in Java.
Diamond Problem:
- Multiple inheritance can cause the “diamond problem,” in which doubt emerges when two or more superclasses of a class have the identical method signature.
- Resolving such conflicts requires the compiler determining which superclass method should be called, which can be difficult and error-prone.
Code Clarity and Maintenance
- Allowing multiple inheritance can result in complex and less readable code, making it difficult to understand and maintain.
- The relationships between classes become more complex, increasing the possibility of errors and reducing code maintainability.
Interface-Based Multiple Inheritance:
- Java does not support multiple inheritance of classes, but it does allow multiple inheritance of interfaces.
- Interfaces allow for some of the benefits of multiple inheritance, such as specifying contracts for behaviour that can be implemented by multiple classes without introducing the challenges involved with class inheritance.
Java operates internally via a combination of generation and interpretation techniques.
Here’s a summary of how Java operates internally.
Compilation:
When you write Java code, it begins in the form of human-readable source code files with the.java extension. Javac compiles these source files into platform-independent bytecode.
Bytecode:
Bytecode is a low-level version of Java code that exists independently of the underlying hardware and operating system. It is saved in.class files. This bytecode is not executed directly by the machine, but rather via the JVM.
Java Virtual Machine (JVM):
The JVM is an essential part of the Java platform. It is responsible for running Java bytecode. The JVM loads bytecode from.class files, checks it for security and accuracy, and then runs it. The JVM also handles memory allocation and garbage collection, resulting in more efficient use of memory.
In Java, errors are handled using the try and catch blocks. Exceptions are unexpected events that occur during a program’s execution, such as dividing by zero or accessing an array index that is out of bounds. The try block encloses any code that may throw an exception.Â
If an error occurs within the try block, the associated catch block handles it softly, avoiding the application from crashing. This provides for more sophisticated error handling and allows developers to anticipate and respond to unusual events in their code, boosting its dependability and maintainability.
Static methods cannot be overridden in Java. When a subclass registers a static method with the same signature as a static method in its superclass, it is actually hiding the superclass function rather than overriding it. This means that the subclass method will be called if the subclass reference is used, even if the superclass instance is used. This behaviour is referred to as method concealing.
Java’s “Write Once, Run Anywhere” (WORA) principle makes it often regarded as platform-independent.
Java’s platform independence is primarily defined as its ability to run the same bytecode on multiple platforms; however, certain aspects of Java applications can continue to display platform-specific behaviour due to interactions with the underlying operating system or the use of platform-specific libraries and components.
Static | Non Static |
Static members, such as variables and methods, are assigned to the class rather than a specific instance of the class. | Non-static members, such as variables and methods, are linked to specific instances (objects) of the class. |
They are started only once, at the start of the program execution, and are shared among all instances (objects) of the class. | Each instance of the class has its own set of non-static members, which are initialised independently for each instance. |
Static members can be used directly using the class name, avoiding the need to construct an instance of the class. | Non-static members can only be accessed with a class instance (object). |
In Java, both the == operator and the.equals() method are used to compare objects, although they serve separate functions and behave differently.
== Operator:
The == operator in Java is used to compare object references, not the actual contents of objects.
When comparing two objects using ==, it checks whether the two references point to the same memory location, i.e., whether they are the same object in memory.
For primitive data types (e.g., int, double), == compares the actual values.
.equals() Method:
The.equals() method compares the actual contents or values of objects to ensure equality.
By default, the .equals() method in the Object class compares object references, similar to the == operator. However, many classes override the .equals() method to provide custom comparison logic based on the content of the objects.
When comparing strings, for example, the.equals() method compares the characters within the strings to see if they are the same.
Checked Exceptions | Un Checked Exceptions |
Checked exceptions are subclasses of Exception (excluding Runtime Exception and its subclasses) that must be caught or stated in the method signature using a throws clause. | Unchecked exceptions are subclasses of both RuntimeException and Error. |
Checked exceptions are unusual circumstances that a well-behaved application should foresee and recover from. | Unchecked exceptions are runtime mistakes that are unanticipated or caused by the programmer, such as logic errors, null pointer dereferences, or arithmetic problems. |
JDK | JRE (Java Runtime Environment) | JVM (Java Virtual Machine) |
The JDK is a software development kit used to create Java programs. | The Java Runtime Environment (JRE) is necessary to run Java applications. | The JVM is a virtual processing machine that serves as a runtime environment for executing Java bytecode. |
It consists of the tools and places needed to create, compile, debug, and document Java programs. | It includes the Java Virtual Machine (JVM), core libraries, and other runtime components required to run Java bytecode. | It translates Java bytecode and just-in-time (JIT) converts it into native machine code for the underlying platform. |
Static Initialization Blocks (SIBs):
- Static initialization Blocks are run when the class is loaded into the JVM.
- They are only run once, regardless of how many objects are generated using the class.
- SIBs are used to set static variables or complete static initialization operations.
Instance Initialization BlocksÂ
- Instance Initialization Blocks are executed when a class object is generated.
- They are executed before the class’s constructor is run.
- IIBs are used to set up instance variables and perform instance-level initialization activities.
Constructor:
- Constructors run after the instance initialization blocks.
- Constructors are used to initialise a newly created object and complete any further initialization activities that the object requires.
- When an object is formed, the new keyword is used to explicitly call the constructor, which might be parameterized or not.
Main Method:
- The main method is a Java program’s entry point and is called when it is executed.
- It runs after the SIBs, IIBs, and constructors.
- The main method initiates the program’s execution and can call other methods or execute any important tasks.
 So the order of execution is SIB,Main Method,IIB,Constructors.
Java Streams are a strong feature introduced in Java 8 that gives you a functional way to manipulate collections of objects. Streams make it possible to define complex data processing operations in a simple and declarative manner, allowing functional-style programming in Java.
Â
Advantages of Streams:
Streams use method linking and lambda expressions to express advanced data processing algorithms in a more clear and understandable way.
Clarity and readability:
Streams encourage declarative programming, which focuses on what to do (functional transformations) rather than how to accomplish it (imperative control flow).
Lazy Evaluation:
Intermediate operations in a stream are assessed lazily, which means that parts are handled only as needed. This can result in improved performance and resource utilisation.
Parallelism:
Streams allow parallel processing, allowing you to take use of multicore processors and boost performance for computationally complex workloads. Parallel streams automatically divide and share the task among different threads.
Immutable State:
Streams are intended to be stateless and do not change the underlying data source. This promotes immutability and helps to avoid side effects, making code more predictable and easier to reason about.
The Java Collections framework is a complete set of classes and interfaces that allow you to explain and handle collections of things. It consists of interfaces, implementations, and algorithms for managing, manipulating, and exploring collections in Java programs. The Collections framework is divided into several important components:
Standardisation:
It provides a standardised and uniform approach to working with collections in Java, allowing developers to write code that is portable, reusable, and interoperable across various collection types and implementations.
Abstraction
The framework hides the intricacies of collection management, allowing developers to focus on application logic rather than the low-level specifics of data structures and algorithms.
Performance:
It provides an array of collection implementations with varied performance characteristics, allowing developers to select the best data structure for their individual use case, performance needs, and memory constraints.
Productivity:
The framework provides utilities and algorithms for performing common operations on collections, which eliminates the need for developers to create generic code and allows them to write more concise, expressive, and efficient code.
In the case of multiple if block statements, the maximum number of if blocks that can be performed is determined by the conditions indicated in each if statement as well as the runtime data.
Each if statement analyses its condition, and if it returns true, the appropriate block of code within that if statement is executed. If the condition returns false, the code block associated with the if statement is bypassed, and the program moves on to the next if statement (if any).
If all criteria are true, the corresponding code blocks will be run. However, if any of the if conditions evaluate to false, the code blocks associated with the following if statements will not be executed.
As a result, when using several if block statements, the number of blocks executed varies based on the data and conditions found during program execution. If all conditions evaluate to true, all if blocks can be run; otherwise, just a subset of if blocks can be executed based on the condition assessment.
In Java, the final keyword is used to define entities that cannot be changed after initialization. Here are common uses of the final keyword.
Final Variables:
Declaring a variable as final means its value cannot be changed once assigned. It must be initialised either at the time of declaration or within the constructor of the class. Final variables are typically used for constants or values that should not change throughout the execution of the program.
Final Methods:
Declaring a method as final in a superclass prevents subclasses from overriding it. This is useful when you want to enforce a specific behaviour in subclasses and prevent further modification of the method’s implementation.
Final Parameters:
Declaring method parameters as final ensures that the parameter values cannot be modified within the method. While this doesn’t prevent changes to the state of objects passed as parameters, it prevents reassignment of the parameter variables within the method.
Method Overloading:
Method overloading is the ability of declaring multiple methods in a class that share the same name but have different parameter lists.
Examples of Method Overloading
package package22;
public class Methodoverloading {
static void add(double c)
{
System.out.println("1");
}
static void add()
{
System.out.println("2");
}
static void add(int a)
{
System.out.println("3");
}
static void add(int a, String b)
{
System.out.println("4");
}
static void add(int a, char b)
{
System.out.println("5");
}
public static void main(String[] args)
{
add();
add(3.12);
add(300);
add(-13,"Hi");
add(12,'A');
}
}
Output:
2
1
3
4
5
Method Overriding
Method overriding happens when subclass and superclass have the same name and parameters and subclass provides a particular implementation of a method specified in its superclass.
Examples of Method Overriding
package pocker;
class Arithmeticoperator4
{
void add()
{
System.out.println("Addition of 3 numbers");
}
}
public class MethodOverriding extends Arithmeticoperator4{
void add()
{
System.out.println("Addition of 2 numbers");
super.add();
}
public static void main(String[] args) {
MethodOverriding b1 = new MethodOverriding();
b1.add();
}
}
Output:
Addition of 2 numbers
Addition of 3 numbers
In Java, the default value of a binary data type is false, whether it is a global or instance variable. This means that if you declare a boolean variable but do not explicitly assign it a value, it will default to false.
However, it’s worth noting that local variables (variables declared within a method or block) in Java do not have default values and must be explicitly initialised before use.
True
Oracle Corporation owns java.
To determine the range of each data type in Java, you must consider the number of bits allotted for each type and whether it is signed or unsigned. The general formula to calculate range of datatype is
-2 (power of n-1) to 2(power of n-1) – 1 where n is size in bits
Here’s how you can calculate the range for commonly used primitive data types:
byte:
Size: 8 bits
Range: -128 to 127 (signed), 0 to 255 (unsigned)
Short:
Size: 16 bits
Range: -32,768 to 32,767 (signed), 0 to 65,535 (unsigned)
Int:
Size: 32 bits
Range: -2,147,483,648 to 2,147,483,647 (signed), 0 to 4,294,967,295 (unsigned)
long:
Size: 64 bits
Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (signed), 0 to 18,446,744,073,709,551,615 (unsigned)
float:
Size: 32 bits
Range: Approximately ±3.40282347E+38F
Double:
Size: 64 bits
Range: Approximately ±1.79769313486231570E+308
Compilation checks for Compile Time Error, it mainly checks for syntax, rules and then translates the .java file to .class file.
Interpretation checks for the Run Time Error, it reads the code line by line, then executes and then translates the .class file to binary.
1.JDK (java development kit) – jdk are the library files which are required to run or write the program.
2.JRE (java runtime environment) – This has to be present in all the devices to run any java program.
3.JIT (just in time) – It is responsible for the conversion of .class file to binary.
No, constructors in Java do not have a return type, not even void. The purpose of a constructor is to initialise objects of a class, and it is automatically invoked when an object is created using the new keyword.
Yes, with Java, you can have many catch blocks for a single try statement. Each catch block can handle a particular type of exception, allowing you to gently manage a variety of unusual events.
The Scanner class in Java reads input from a variety of sources, including the keyboard, files, and streams. It contains techniques for processing and storing input, allowing you to read various forms of data interactively while the application is running.Â
Exception handling in Java is a framework for dealing with realtime mistakes or exceptional conditions that arise during program execution. It allows programmers to gracefully resolve failures while avoiding program termination due to unhandled exceptions.
Some commonly encountered exceptions in Java include:
NullPointerException
- ArrayIndexOutOfBoundsException
- FileNotFoundException
- OException
Constructors cannot be overridden in Java because they are not inherited, unlike methods. When a subclass extends a superclass, it inherits its constructors but does not override them. Each class, including subclasses, has its own constructors, which are not part of the inheritance structure.
Name as many String functions as possible?
length()
charAt
substring
concat
toUpper
toLowerCase
No, in Java, you cannot inherit a class straight from an interface. Interfaces define a contract for classes to implement, whereas classes define behaviour and state.
What is the difference between System.out. println() and System.out.print
System.out.println():
- The println() method publishes the supplied message to the console and then advances the cursor to the next line.
- After printing the message, it adds a line terminator to the output, causing the next output to appear on a new line.
- This approach is widely used to print a message followed by a newline character, such as when showing many lines of text or formatting the output.
System.out.print():
- The print() method prints the specified message to the console without moving the cursor to the next line.
- It does not add a line terminator after printing the message, therefore any future output will be on the same line.
- This approach is useful for publishing multiple messages on the same line or controlling the output formatting, such as writing integers or strings without inserting unnecessary newline characters.
System is the class, out is a static field of the System class, and println() is a method of the PrintStream class returned by the outfield.
In Java, the Arrays.toString() function converts an array to a human-readable string representation. It is very handy for debugging or when you need to present the contents of an array in an understandable format, such as when writing array items to the console or logging them.
No, arrays in Java cannot have negative sizes. Trying to build an array with a negative size will throw a runtime exception, particularly NegativeArraySizeException.
Object-oriented programming (OOP) is an approach to programming that focuses on the concept of objects. In OOP, objects are instances of classes that contain data (attributes) and behaviours (methods) associated with a certain entity or concept. Encapsulation, inheritance, polymorphism, and abstraction are among the most important OOP ideas.
Here are some popular object-oriented programming languages:
- Java
- C++
- Python
- Ruby
- CLOS (Common Lisp Object System)
while (condition) {
// Statements to be executed repeatedly as long as the condition is true
}
The continue keyword in Java is used inside loops (such as while, for, or do-while) to skip the remainder of the current iteration and move on to the next iteration of the loop. When the continue statement is found, the loop skips the remaining code for the current version and advances to the next iteration.
b] keywordÂ
B] Token
A]Â Separator
a).java file is converted to .class file
b) binary is given as input to the operating system.
a) library files.
The access specifier of the main method in Java is public.
The method parameter of the main method in Java is a) parameterized.
In a java class there cannot be multiple public static void main String args[]. So the answer is b) False
The return type of the main method in Java is void.
Yes, we can modify the public static void main(String[] args) function in Java. This method acts as the Java program’s starting point, and you can adjust its implementation to execute various tasks or activities as required by your program.Â
Identifiers in Java should be written in c) camel case.
switch (expression) {
case value1:
// Statements to be executed if expression matches value1
break;
case value2:
// Statements to be executed if expression matches value2
break;
// Additional case statements
default:
// Statements to be executed if expression does not match any case
}
In Java, there can be only one main method with the signature.
This method is the Java program’s entry point, and each class can only have one entry point. Having many main methods with the same signature in a single class could lead to an integration problem.
In Java, the byte data type is an 8-bit signed two’s copy integer, which can represent integer values between -128 and 127.
‘=’ is a) Assignment operator.
No, in Java, output cannot be displayed without a main method (psvm). The main method is the Java program’s entry point, where the program’s execution begins.
No, it is not required to create an object to call a static method inside the main method in Java. Because static methods belong to the class rather than individual instances of the class. They can be accessed just using the class name, without creating an object.
Yes, it is required to create an object to call a non-static method inside the main method in Java. Because Non-static methods have a connection with class instances, therefore you must first build a class object and then call the non-static function from that object.
No, method overloading in Java requires that the method signatures differ in terms of the amount and type of parameters. Without parameterization, method signatures would be identical, making method overloading impossible.
No, In in constructor overloading in Java, it is not required to use a non-parameterized constructor for overloading. Constructor overloading simply involves defining multiple constructors within a class, each with a different parameter list.
No, In Java, you cannot use a local variable before it has been created. Local variables must be explicitly assigned a value before they may be accessed or utilized inside the scope in which they are defined.Â
No, Because Local variables cannot be classified as static or non-static because they are defined within a method or block and may only be accessed within that context.
Yes, in Java, global variables can be distinguished as static or non-static.
Yes, in Java, global variables (also known as instance variables or class variables) can be used without being explicitly initialized. When a global variable is declared, it is automatically populated with a default value based on its type.
In the case of an if and else block in Java, only one block of code will be executed based on the condition provided. If the condition of the if statement evaluates to true, the code block associated with the if statement will be executed.
When using nested if-else statements in Java, the maximum number of code blocks that can be printed is set by the nesting depth and the individual conditions considered.
A global variable in Java, also known as an instance variable or class variable, has a scope that covers the whole class in which it is declared. This indicates that the variable can be accessed from any method, constructor, or block within the class, as well as from other classes, if it is declared with the appropriate access modifier.
Java is a platform-independent programming language. This means that Java programs can run on any platform or operating system that has the Java Virtual Machine (JVM) installed.
In Java, subclasses do not inherit constructors. But we can call constructors from superclass to sub class using super calling statement.
No, Multiple-level inheritance in Java is not possible through the use of class concepts. Trying to achieve multiple level inheritance using class result in Diamond Problem. Multiple level inheritance is only achieved by using the concept of interface.
Reusability and Efficiency
Type Safety
Performance Optimization
Interoperability and Compatibility
Examples of Java Collections framework classes and their advantages:
ArrayList
HashSet
LinkedHashSet
LinkedList
Stack
Array Deque
Hash Map
The various advantages of collection framework classes are
- Java Collection classes have a common set of methods : The Java Collection framework has lot of interfaces like Collection, Iterable, List, Queue,Set, Map and classes like ArrayList,HashMap,HashSet and Vector. So all the classes that implement the interfaces have common set of methods.
- Saves time and energy of programmers: Programmer need to have to spend time in writing the program rather he can pay attention to proper utilization of his program.Thus collection framework ensures that all concepts of Object Oriented Programming like abstraction have been utilised successfully thus saving time and of programmers.
- Increases efficiency and speed of program: Due to best implementation of the interfaces by the classes as well as usage of Object Oriented Programming concepts like abstraction and other data structures, speed and efficiency of program is increased.
Java annotations are a type of metadata introduced in Java 5 that allows developers to include additional information, instructions, or metadata in Java code. Annotations are represented by @ symbols followed by the annotation’s name.Annotations do not alter the implementation of the program. Annotations also provide some extra information about the program.
 Annotations Hierarchy in Java
Java access specifiers are keywords that regulate the visibility and accessibility of classes, methods, variables, and constructors in Java. These access specifiers specify which other classes or code components may access the declared elements.
Yes, it is possible to overload constructors in Java. Constructor overloading is the ability to declare numerous constructors with different argument lists within a single class.
StringBuffer | StringBuilder |
StringBuffer is thread-safe, which means it is linked and safe to use in multi-threaded settings. Multiple threads can access and edit a StringBuffer object simultaneously without the risk of data corruption or inconsistency. | StringBuilder isn’t thread-safe. It is not coordinated, therefore many threads cannot access it at the same time. Multiple threads attempting to alter a StringBuilder object at the same time may cause data corruption or unexpected behavior. |
StringBuffer operations are coordinated, resulting in some performance overhead, particularly in multi-threaded circumstances where coordination locks are gained and released. | StringBuilder methods are not coordinated, which leads to superior performance than StringBuffer, particularly in single-threaded situations. StringBuilder operations are faster because they avoid the overhead of coordinating their actions. |
In conclusion, mastering Java interviews is a key step towards advancing your career in the tech industry. By familiarising yourself with these Java Interview Questions and Answers, you are better prepared to showcase your knowledge and skills to potential employers. Remember to practise, stay updated with the latest trends in Java with Selenium, and maintain a positive attitude throughout your interview process. With dedication and perseverance, you can ace any Java interview and secure your dream job. Good luck on your Java programming journey!