InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Java Multithreading |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Answer» What is Multithreading? Multithreading is a Java feature that permits the execution of two or more portions of a program at the same time to maximise CPU efficiency. Each such portion of the program is referred to as a thread. The above image shows 3 processes wherein process 1 consists of 3 threads, process 2 consists of 2 threads and process 3 consists of 1 thread. Java Runnable Interface: In Java, java.lang.Runnable is an interface that a class must implement if its instances are to be executed by a thread. Java Thread Class: Thread programming is possible with Java’s Thread class. The Thread class contains constructors and methods for creating and operating on threads. Thread is a subclass of Object that implements the Runnable interface. Methods of the Java Thread Class: The following table shows the methods of the Java Thread class and its use cases.
Java Multithreading has the following advantages:
How to implement multithreading in Java? Multithreading can be performed in Java using two different mechanisms:
By extending the Thread class: We’ll make a class that extends the java.lang.Thread class. The run() method of the Thread class is overridden by this class. The run() procedure is where a thread starts its life. To begin thread execution, we construct an object of our new class and use the start() method. Start() calls the Thread object’s run() function. Example - class Sample extends Thread {public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("An exception is caught"); } } } class Multithread { public static void main(String[] args) { int n = 5; // Number of threads for (int i = 0; i < n; i++) { Sample obj = new Sample(); obj.start(); } } } Output - Thread 20 is runningThread 18 is running Thread 21 is running Thread 19 is running Thread 17 is running Explanation - In the above code, the Sample class extends the Thread class present in java.lang package. In the Multithread class, we create 5 threads by creating an instance of the Sample class. We then invoke the run() method of the instance created by calling the start() method of the instance. By implementing the Runnable Interface: We make a new class that implements the java.lang.Runnable interface and overrides the run() method. After that, we create a Thread object and call its start() method. Example - class Sample implements Runnable {public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("An exception is caught"); } } } class Multithread { public static void main(String[] args) { int n = 5; // Number of threads for (int i = 0; i < n; i++) { Thread obj = new Thread(new Sample()); obj.start(); } } } Output - Thread 20 is runningThread 18 is running Thread 21 is running Thread 19 is running Thread 17 is running Explanation: In the above code, the class Sample implements the Runnable interface. In the sample class, we override the run() method. In the Multithread class, we create 5 threads by creating an instance of the Thread class. Runnable Interface vs. Thread Class: The following are the key differences between using the Runnable interface and the Thread class:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 2. |
Java Generics |
|
Answer» Generics refer to types that have been parameterized. The goal is to make type (Integer, String, etc., as well as user-defined types) a parameter for methods, classes, and interfaces. Generics can be used to design classes that function with a variety of data types. A generic entity is a type that works on a parameterized type, such as a class, interface, or method. In Java, generics are equivalent to templates in C++. Generics are used extensively in classes such as HashSet, ArrayList, HashMap, and others. Generic class: In the same way that C++ specifies parameter types, we use <> to define parameter types in generic class formation. The following syntax is used to construct generic class objects. ClassName <Type> obj = new ClassName <Type>()Here, ‘ClassName’ denotes the name of the class whose instance is to be created. <Type> specifies the data type to be used while instantiating the object. ‘obj’ is the name of the object to be created. Example - class Sample<T>{ // Declaring an object of type T T obj; Test(T obj) // constructor { this.obj = obj; } public T getObject() { return this.obj; } } class Test { public static void main (String[] args) { // instance of Integer type Sample <Integer> obj1 = new Sample<Integer>(10); System.out.println(obj1.getObject()); // instance of String type Test <String> obj2 = new Test<String>("Interview Bit"); System.out.println(obj2.getObject()); } } Output - 10Interview Bit In the above example, a generic class Sample has been created which accepts a parameter T to determine the type of the class. We create 2 instances of the Sample class. One with an Integer type and the other with a String type. The following are the advantages of using generics in Java: Type-safety: In generics, we can only hold one type of object. It does not allow for the storage of objects of different types. Example - List list = new ArrayList();list.add(1); list.add("Interview Bit"); The above code snippet runs fine. This is because we have not specified any type while creating an instance of the List class. However, if we run the below code snippet, we get a compile-time error. List<Integer> list = new ArrayList<Integer>();list.add(1); list.add("Interview Bit");// compile-time error This is because we have specified the instance of the List class to be of type Integer. Typecasting isn’t necessary: When we use generics, we do not need to typecast the object when we access it. Example - List list = new ArrayList();list.add("Interview Bit"); String s = (String) list.get(0);//typecasting In the above code, we can see that before accessing the element of the list, we need to typecast it to String type explicitly. This is because we have not declared the list instance to be of a specific type. However, if we run the below code snippet, we do not need to typecast it explicitly. List<String> list = new ArrayList<String>();list.add("Interview bit"); String s = list.get(0); This is because we have specified the instance of the List class to be of String type. Checking at Compile Time: It is checked at compile time to ensure that an issue does not arise at runtime. It is considerably better to handle the problem at compile time than at runtime, according to an excellent programming approach. Example - List<String> list = new ArrayList<String>();list.add("Interview Bit"); list.add(100);//Compile Time Error The above code snippet gives a compile-time error. This verifies that the code is checked at compile-time. |
|
| 3. |
Java Collections |
||||||||||||||||||||||||||||||
|
Answer» The collection of objects refers to any group of individual objects that are represented as a single unit. In JDK 1.2, a new framework called “Collection Framework” was established, which contains all of the collection classes and interfaces. The Collection interface (present in the java.util.Collection package) and the Map interface (present in the java.util.Map package) are the two basic root interfaces of Java collection classes. The above image shows various interfaces and the classes present in those interfaces in the Java Collections framework. The ones in yellow colour represent interfaces while the ones in blue colour represent classes that implement those interfaces. The following table lists the methods present in the collection interface:
Interfaces that extends the Collections interface:- The following are the interfaces present in the Collection framework of Java:
|
|||||||||||||||||||||||||||||||
| 4. |
Java Commands |
|
Answer» Following are the most widely used java commands:- 1. java –version: This is one of the most fundamental Java commands for checking the Java version installed on your machine. This is also used to confirm that the installation and PATH variable settings are correct. The above image is a snapshot of the output we get on running the java -version command. 2. javac –version: This command displays the version of the compiler that is in charge of compiling the source code. This is also a component of the Java Development Kit, or JDK for short. The above image is a snapshot of the output we get on running the javac -version command. 3. whereis: This Java command searches the directory for a given component. In the example below, we’ve taken into account javac. The above image is a snapshot of the output we get on running the command whereis javac. 4. echo: The echo command is a must-know command in Java since it allows you to display the contents of a specific file. In most cases, this is used to verify the PATH variables. The above image is a snapshot of the output we get on running the command echo %PATH% 5. javap: The javap command is used to disassemble one or more class files. The outcome is determined by the choices made. When no options are specified, the javap command prints both protected and public fields, as well as all of the methods of the classes supplied to it. 6. javah: Using this tool, you can produce c header and source files from a java class automatically. The generated c headers and source files are used to implement native methods and to refer to an object’s instance variable in the native source code. 7. Javadoc: The Javadoc command and its arguments are used to generate HTML pages or API documentation from a group of Java source files in a seamless manner. This tool parses the declarations and documentation comments in an array of java source files and generates HTML pages that describe the public and protected classes, interfaces, fields, and nested classes, according to the default parameters. |
|
| 5. |
Java Exception Handling |
||||||||||||||||||||||||||||||||||||||
|
Answer» Meaning of Exception: An exception is an unwelcome or unexpected occurrence that occurs during the execution of a program, i.e. at run time, and disturbs the program's usual flow of instructions. Error vs Exception: What is the Difference? An error implies that there is a major problem that a reasonable programme should not attempt to solve whereas an exception denotes a set of circumstances that a reasonable programme would attempt to catch. Hierarchy of Exceptions: As we can see in the above image, all exception and error kinds are subclasses of the hierarchy's root class, Throwable. Exceptions can be divided into two categories:
Built-in Exceptions in Java: Exceptions that are present in Java libraries are known as built-in exceptions. The following table lists the built-in exceptions in Java:
Java Try-Catch:-
try { // code to be checked }
catch { // code to handle exception } finally keyword:- In Java, the finally block represents code that is to be executed whether or not an exception is caught. In case a catch block is present after the try block, it is run after the catch block has been executed. However, in case there is no catch block present after the try block, the finally block is executed after the try block has been executed. Syntax - finally{ // code to be executed } Difference between final, finally and finalize: The following table lists the differences between final, finally and finalize:
throw keyword:- In Java, the throw keyword is used to throw an exception from a method or any block of code. We can either throw a checked or an unchecked exception. Throwing custom exceptions is the most common use of the throw keyword. throws keyword:- The throws keyword is used to handle exceptions in the absence of a try/catch block. It specifies the exceptions that a method should throw in case an exception occurs. Example - class Test {// This method throws an exception static void foo() throws IllegalAccessException { System.out.println("Inside the foo() method"); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { foo(); } catch (IllegalAccessException e) { System.out.println("Exception caught"); } } } Output - Inside the foo() methodException caught Explanation - In the above code, the function foo() specifies that an IllegalAccessException should be thrown in case an exception occurs using the throws keyword. In the foo() function, we explicitly throw an exception. This is caught by the catch block present in the main method of the class. |
|||||||||||||||||||||||||||||||||||||||
| 6. |
Java Regex |
||||||||||||||||||||||||||||||||||||||||||||
|
Answer» Regex (short for Regular Expressions) is a Java API for defining String patterns that may be used to search, manipulate, and modify strings. Regex is frequently used to specify the limits in a number of areas of strings, including email validation and passwords. The java.util.regex package contains regular expressions. This is made up of three classes and one interface. The java.util.regex package consists of the following three classes, which are listed below in the tabular format:
Pattern class: There are no public constructors in this class. It is a collection of regular expressions that can be used to define various types of patterns. This can be done by executing the compile() method, which takes a regular expression as its first input and returns a pattern after it has been executed. The following table lists the methods present in this class and their description:
Matcher Class: This object is used to evaluate the previously described patterns by performing match operations on an input string in Java. There are no public constructors defined here either. Invoking a matcher() on any pattern object can be used to accomplish this. The following table lists the methods present in this class and their description:
|
|||||||||||||||||||||||||||||||||||||||||||||
| 7. |
Strings in Java |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Answer» Strings are Objects in Java that are internally supported by a char array. Strings are immutable (that is, their content cannot be changed once initialised) because arrays are immutable. Every time you make a change to a String, a new String is produced. String syntax in java:- <String_Type> <string_variable> = "<sequence_of_string>";In Java, there are two ways to make a string: Using String literal: String str = "Interview Bit";Using new keyword: String str = new String ("Interview Bit");Difference between String literal and String object: The following table lists the differences between String literal and String object:
String Pool: String pool is a Java heap storage area where string literals are stored. String Intern Pool or String Constant Pool are other names for it. It’s the same as object allocation. It is empty by default and is maintained privately by the Java String class. When we create a string, the string object takes up some memory in the heap. Creating a large number of strings may raise the cost and memory requirements, lowering performance. During the initialization of string literals, the JVM takes several efforts to improve efficiency and reduce memory usage. The String class keeps a pool of strings to reduce the number of String objects created in the JVM. In the above image, we can see that the String pool is a portion of the heap memory maintained by Java to store String literals. We can see that the literals ‘str1’ and ‘str2’ point to the same memory area. However, we can see that a new String object is always created whether or not the String exists already. However, we can make the String object to check if the String already exists by using the intern() method. Built-in String Methods:
str.append("Interview Bit"); String Buffer vs String Builder: The following table lists the differences between String Buffer and String Builder in Java:
StringTokenizer: StringTokenizer is a Java class that is used to split a string into tokens. In the above image, we can see that StringTokenizer divides the inputted string into tokens based on the default delimiter which is space. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 8. |
Arrays in Java |
|
Answer» In Java, an array is a collection of like-typed variables with a common name. Arrays in Java are not the same as those in C/C++. The following are some key points to remember regarding Java arrays.
Syntax for declaring an array:- datatype variable_name[];OR datatype[] variable_name; Despite the fact that the above declaration declares variable_name to be an array variable, no actual array exists. It just informs the compiler that this variable (variable_name) will contain an array. You must allocate memory space to it using the new operator. Syntax of instantiating an array in java:- variable_name = new datatype [size];For example, int sample_array[]; //declaring arraysample_array = new int[20]; // allocating memory for 20 integers to array Array Literal:- Array literals can be utilised in situations where the size of the array and its variables are already known. For example, int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };The produced array’s length is determined by the length of this sequence. In the most recent versions of Java, there is no need to write the new int[] portion. |
|
| 9. |
Abstract class and Interfaces |
||||||||||||
|
Answer» Abstract Class:- In C++, a class becomes abstract if it has at least one pure virtual function. In Java, unlike C++, an abstract class is created using a separate keyword abstract. The following are some key points to remember about Java abstract classes.
Example - abstract class Sample1 {abstract void fun(); } class Sample2 extends Sample2 { void fun() { System.out.println("Inside Sample2's fun function."); } } class Test { public static void main(String args[]) { Base b = new Derived(); // We can have references of Base type. b.fun(); } } Output - Inside Sample2's fun function.Explanation - In the above code, we have defined an abstract class Sample1. We declare the function definition in this class. We define another class Sample2 and extend it from Sample1. Here, we provide the implementation for the method of the abstract class inherited. Now we create an instance of the Sample2 class and invoke the fun() function. Java Interfaces:-
Syntax - interface INTERFACE_NAME {// constant fields // methods } The interface keyword is used to declare an interface. Its purpose is to provide complete abstraction. All methods in an interface are declared with an empty body and are public by default, and all fields are public, static, and final. A class that implements an interface is required to implement all of the interface's functions. The keyword implements is used to implement an interface. Reasons for introducing interfaces in Java:
Example - interface Sample{ final int a = 1; // public, static and final void display(); // public and abstract } // A class that implements the interface. class Test implements Sample { // Implementing the capabilities of the interface. public void display() { System.out.println("InterviewBit"); } public static void main (String[] args) { Test t = new Test(); t.display(); System.out.println(a); } } Output - InterviewBit1 Explanation - In the above code, we created an interface Sample having a public, static and final data member ‘a’ and a function signature with name ‘display’. We create a class Test that implements this interface and provides the definition for the display function. We also access the data member ‘a’ defined in the interface. Abstract Class vs Interface: The following table depicts the differences between abstract classes and interfaces in Java:
|
|||||||||||||
| 10. |
Java Math Class |
|
Answer» |
|
| 11. |
Java Inheritance |
|
Answer» In Java, Inheritance is a feature that allows one object to inherit all of the characteristics and behaviours of its parent object. It's a crucial component of OOPs (Object Oriented programming systems). Inheritance in Java refers to the ability to build new classes that are based on existing ones. When you inherit from an existing class, you can use the parent class's methods and fields. You can also add additional methods and properties to your current class.
Types of inheritance in Java: 1. Single Inheritance - Subclasses inherit the features of a single superclass via single inheritance. Class A acts as a base class for the derived class B in the figure below. Example - class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void foo(){ System.out.println("Inside Test's foo method."); } } class Main{ public static void main(String args[]){ Test t = new Test(); t.fun(); t.foo(); } } Output - Inside Sample's fun method.Inside Test's foo method. Explanation - In the above code, the class Test inherits from the class Sample. We create an object of the Test class and call the methods defined in both classes. 2. Multilevel Inheritance - Multilevel Inheritance: In Multilevel Inheritance, a derived class inherits from a base class, and the derived class also serves as the base class for other classes. Class A serves as a base class for derived class B, which in turn serves as a base class for derived class C in the diagram below. In Java, a class cannot directly access the members of a grandparent. Example - class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void foo(){ System.out.println("Inside Test's foo method."); } } class Result extends Test{ void display(){ System.out.println("Inside display method of Result class."); } } In the above code snippet, the class Test inherits from the class Sample and the class Result inherits from the class Test. 3. Hierarchical Inheritance - One class serves as a superclass (base class) for several subclasses in Hierarchical Inheritance. Class A acts as a base class for the derived classes B, C, and D in the diagram below. Example - class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void foo(){ System.out.println("Inside Test's foo method."); } } class Result extends Sample{ void display(){ System.out.println("Inside display method of Result class."); } } class Example extends Sample{ void display(){ System.out.println("Inside display method of Example class"); } } In the above code snippet, the classes Test, Result and Example inherit from the Sample class. 4. Multiple Inheritance - When a class inherits from more than one class, it is referred to as multiple inheritances. The below image shows class C inheriting from classes A and B. Java does not support multiple inheritances as it can lead to ambiguity. We can implement the concept of multiple inheritances through the use of interfaces which we will discuss later in this article. Hybrid Inheritance - Hybrid Inheritance is a blend of two or more of the inheritance kinds listed above. The below figure shows two classes B and C inheriting from class A and a class D inheriting from both classes B and C. Thus hybrid inheritance requires multiple inheritances and since Java does not support multiple inheritances, hybrid inheritance is not supported by Java. Diamond Problem in Java: Let us consider the previous example of hybrid inheritance to understand the diamond problem. Let us also consider the following code snippet: class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void foo(){ System.out.println("Inside Test's foo method."); } } class Result extends Sample{ void foo(){ System.out.println("Inside display method of Result class."); } } class Example extends Test and Result{ void display(){ System.out.println("Inside display method of Example class"); } } class Main{ public static void main(String args[]){ Example e = new Example(); e.foo(); // Ambiguity } } In the above code, the classes Test and Result inherit from the class Sample and the class Example inherits from the classes Test and Result. Here, we have assumed for now that Java supports multiple inheritances. It is because of this problem that Java does not support multiple inheritances of classes and hence all of this is avoided. |
|
| 12. |
Java Polymorphism |
|
Answer» Polymorphism is a Java feature that allows us to do a single operation in multiple ways. Polymorphism is made up of two Greek words: poly and morphism. The words "poly" and "morphs" denote "many" and "forms," respectively. As a result, polymorphism denotes the presence of several forms. Polymorphism in Java is divided into two types: compile-time polymorphism and runtime polymorphism. Compile-time Polymorphism: Compile-time polymorphism is also known as static polymorphism. In Java, this is achieved by function overloading. Method Overloading: When there are numerous functions with the same name but distinct parameters, this is referred to as overloading. Changes in the number of arguments or the kind of arguments can cause functions to become overloaded. Example - class Sample {// Method with 2 integer parameters static int Multiply(int a, int b) // method overloading { return a * b; } // Method with same name but with 2 double parameters static double Multiply(double a, double b) // method overloading { return a * b; } } class Test { public static void main(String[] args) { // Calling method by passing // input as in arguments System.out.println(Sample.Multiply(1, 4)); System.out.println(Sample.Multiply(5.5, 4.2)); } } Output - 423.1 Explanation: In the above code, the class Sample has two functions with the same name ‘multiply’ but they have different function signatures which implement method overloading. So, we have the same name for a function that returns the multiplication of two integers and a function that returns the multiplication of two doubles. Runtime Polymorphism: Runtime polymorphism, often known as Dynamic Method Dispatch, is a technique for resolving calls to overridden methods at runtime rather than at compile time. A superclass's reference variable is used to call an overridden method in this process. The object referred to by the reference variable is used to determine which method should be called. Example - class Sample{void fun(){ System.out.println("Inside Sample's fun method."); } } class Test extends Sample{ void fun(){ System.out.println("Inside Test's fun method."); } } class Main{ public static void main(String args[]){ Sample s = new Test() s.fun(); } } Output - Inside Test's fun method.Explanation - In the above code, the Test class inherits from the Sample class and both the Test class and the Sample class have a method named ‘fun’ defined. This leads to method overriding. Now in the main class, we create a ‘Sample’ reference variable and allot an instance of the ‘Test’ class to it. Now, we invoke the fun() method. Since, the reference variable stores an object of the ‘Test’ class, the fun() method of the ‘Test’ class gets invoked. |
|
| 13. |
Java Methods |
|
Answer» A method is a collection of statements or a series of statements organised together to conduct a specific task or action. It’s a technique for making code more reusable. We create a method once and then use it repeatedly. We don’t have to write code over and over again. It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed. Method Declaration:- Method properties such as visibility, return type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers. Method signature - A method signature is a statement that identifies a method. It’s included in the method declaration. It contains the method name as well as a list of parameters. Access Specifier - The method’s access specifier, also known as a modifier, determines the method’s access type. It specifies the method’s visibility. There are four different types of access specifiers in Java:
Return Type - The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything. Method name - The name of a method is defined by its method name, which is a unique name. It must be appropriate for the method’s functionality. If we’re making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it. Parameter List - The parameter list is a collection of parameters separated by a comma and wrapped in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters. Method body - The method declaration includes a section called the method body. It contains all of the actions that must be completed. It is protected by a pair of curly braces. |
|
| 14. |
Java Packages |
|
Answer» In Java, a package is a container for a collection of classes, sub-packages, and interfaces. Packages are used for the following purposes:
Subpackages - Subpackages are packages that are contained within another package. These are not automatically imported; they must be imported manually. Members of a subpackage also have no access privileges, therefore they are treated differently by protected and default access specifiers. Types of packages:- The above image shows that packages can be classified into two broad categories - User Defined Packages and In-Built Packages. Built-in Packages: These packages contain a huge number of classes that are included in the Java API. The following are some of the most often used built-in packages as shown in the image below:
User-defined packages: These are the packages that the user has defined. |
|
| 15. |
Control Flow in Java |
|
Answer» The Java compiler runs the code from beginning to end. The statements in the code are executed in the order that they occur in the code. Java, on the other hand, includes statements for controlling the flow of Java code. It is one of Java’s most important aspects, as it ensures a smooth program flow. There are three different types of control flow statements in Java. They are as follows: Decision-Making Statements: As the name implies, decision-making assertions determine which and when to execute statements. Decision-making statements analyse the Boolean expression and control the program flow based on the condition’s result. In Java, there are two sorts of decision-making statements: If and switch statements. If Statement: The “if” statement in Java is used to test a condition. Depending on the circumstances, the program’s control is diverted. The If statement’s condition returns a Boolean value, either true or false. There are four forms of if-statements in Java, as mentioned below. Simple if: The most basic of all control flow statements in Java is simple if statements. It evaluates a Boolean statement and, if the expression is true, allows the program to begin a block of code. Syntax - if(condition) {statement; //executes when condition is true } if-else: The if-else statement is an expansion of the if-statement that employs the else block of code. If the if-condition block is evaluated as false, the else block is executed. Syntax - if(condition) {statement; //executes when condition is true } else{ statement; //executes when condition is false } if-else-if ladder: The if-else-if statement is made up of an if statement and several else-if statements. In other words, a decision tree is created by a sequence of if-else statements in which the computer can enter the block of code where the condition is true. At the end of the chain, we may also define an else statement. Syntax - if(condition 1) {statement; //executes when condition 1 is true } else if(condition 2) { statement; //executes when condition 2 is true } else { statement; //executes when all the conditions are false } Nested if-statement: The if statement can contain an if or if-else statement inside another if or else-if statement in nested if-statements. Syntax - if(condition 1) {statement; //executes when condition 1 is true if(condition 2) { statement; //executes when condition 2 is true } else{ statement; //executes when condition 2 is false } } Switch Statement: Switch statements in Java are similar to if-else if-else statements. A single case is run based on the variable that is being switched in the switch statement, which comprises various blocks of code called cases. Instead of using if-else-if statements, you can use the switch statement. It also improves the program’s readability.
We must remember that the case expression will be of the same type as the variable when employing switch statements. It will, however, be a constant value. Syntax - switch (expression){case value1: statement1; break; . . . case valueN: statementN; break; default: default statement; } Loop Statements: In programming, we may need to run a piece of code multiple times while a condition evaluates to true. Loop statements are used to repeat the set of instructions. The execution of the set of instructions is contingent on a certain circumstance. In Java, there are three different forms of loops that all work in the same way. However, there are differences in their syntax and the time it takes to check for conditions. For Loop: The for loop in Java is comparable to the for loop in C and C++. In a single line of code, we may initialise the loop variable, check the condition, and increment/decrement. We only use the for loop when we know exactly how many times we want to run a block of code. Syntax - for(initialization, condition, increment/decrement) {//block of statements } While Loop: The while loop can also be used to repeatedly iterate over a set of statements. If we don’t know the number of iterations ahead of time, though, we should use a while loop. In contrast to the for loop, the initialization and increment/decrement do not happen inside the while loop statement. Because the condition is tested at the start of the loop, it’s also known as the entry-controlled loop. The loop body will be executed if the condition is true; else, the statements after the loop will be executed. The while loop’s syntax is seen below. while(condition){//looping statements } Do While Loop: After running the loop statements, the do-while loop verifies the condition at the end of the loop. We can use a do-while loop when the number of iterations is unknown and we need to run the loop at least once. Because the condition is not tested in advance, it is also known as the exit-controlled loop. The do-while loop’s syntax is seen below. do{ //statements } while (condition); Jump Statements: Jump statements are used to move the program’s control to certain statements. Jump statements, in other words, move the execution control to another area of the program. In Java, there are two types of jump statements: break and continue.
|
|
| 16. |
Identifiers in Java |
|
Answer» Identifiers are used to identify items in the Java programming language. A class name, method name, variable name, or label can all be used as identifiers in Java. Rules for defining Java identifiers:-
Reserved words:- Some words are reserved in the Java programming language to indicate the language’s established features. These are known as reserved words. They can be divided into two categories: keywords(50) and literals (3). Functionalities are defined by keywords, and literals are defined by values. Symbol tables use identifiers in the various analysing phases of a compiler architecture (such as lexical, syntactic, and semantic). |
|
| 17. |
Operators in Java |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Answer» The below image shows the different types of operators available in Java. The following table describes each category of operators along with examples of each type.
Precedence and Associativity of operators in Java:- When dealing with hybrid equations involving more than one type of operator, precedence and associative principles are applied. Because there might be multiple valuations for the same equation, these criteria determine which component of the equation to analyse first. The precedence of operators is shown in the table below in decreasing order of magnitude, with the highest precedence at the top and the lowest precedence at the bottom.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 18. |
Access Modifiers in Java |
|||||||||||||||||||||||||
|
Answer» The accessibility or scope of a field, function, constructor, or class is defined by the access modifiers in Java. The access modifier can be used to adjust the access level of fields, constructors, methods, and classes.
The following table depicts the level of accessibility that each access modifier allows in Java.
|
||||||||||||||||||||||||||
| 19. |
Java Comments |
|
Answer» The statements in a program that are not executed by the compiler and interpreter are referred to as Java comments. Comments can be used to explain and improve the readability of Java code. Comments in a program help to make it more human-readable by putting the details of the code involved, and effective use of comments makes maintenance and bug discovery easier. The following are the different types of comments in Java:
Only one line of code is commented with a single-line comment. It is the most common and straightforward method of commenting on statements. Syntax - // This is a sample comment
Multiple lines of code can be commented with the multi-line comment. Because we must offer '//' at every line to describe a full method in a code or a complex snippet, single-line comments might be tedious to write. To get around this, you can utilise multi-line comments. Between /* and */ are multi-line comments. Java does not execute any text between /* and */. /*This is an Example of multi line comment */
This type of comment is commonly used while writing code for a project/software package because it aids in the generation of a documentation page for reference, which can be used to learn about the methods available, their parameters, and so on. Syntax - /** Comment starts* This is a * Sample comment * comment ends*/ |
|
| 20. |
Java Keywords |
|
Answer» a) Understanding the this keyword in Java: The this keyword in java can be used in multiple ways. The following are the use cases of the this keyword: this: to refer to the current instance variable of the class The this keyword can be used to refer to the current instance variable of a class. If there is any ambiguity between the instance variables and arguments, this keyword clears things out. Example - class Sample{int a; Sample(int a){ this.a=a; } void display(){ System.out.println("a = "+a); } } class Test{ public static void main(String args[]){ Sample s1=new Sample(10); s1.display(); } } Output - a = 10Explanation: In the above code, we can see that both the data member of the class Sample and the parameter of the constructor of the Sample class have the same name ‘a’. Here, we use the this keyword to differentiate between the two. this: to call the method of the current class The this keyword can be used to call a method in the current class. If you don't use this keyword, the compiler will add it for you when you call the method. Let's look at an example. class Sample{void fun() { System.out.println("hello there"); } void foo(){ System.out.println("hello foo"); this.fun(); } } class Test{ public static void main(String args[]){ Sample s = new Sample(); s.foo(); } } Output - hello foohello there Explanation - In the above code, we have 2 methods defined in the Sample class fun and foo. We create an instance of the Sample class and call the method foo(). In the foo() method, we call the fun() method using this keyword. this() is used to call the constructor of the current class The current class constructor can be called using the this() call. It allows for constructor chaining. Example - class Sample{Sample() { System.out.println("In default constructor"); } Sample(int a) { this(); System.out.println("In Parameterised constructor"); } } class Test{ public static void main(String args[]){ Sample s = new Sample(10); } } Explanation - In the above code, we have two constructors defined in the Sample class. We call the default constructor from the parameterised constructor using the this() statement. this: to use as a parameter in a method The keyword this can also be used as an argument in a method. It is primarily used in event handling. Let's look at an example: class Sample{void fun(Sample obj) { System.out.println("Received the object"); } void foo(){ fun(this); } } class Test{ public static void main(String args[]){ Sample s = new Sample(); s.foo(); } } In the above code, two functions fun and foo have been defined in the Sample class. The function fun() accepts a parameter of Sample object type. We call the function fun() from the function foo() and pass this as a reference to the current invoking object. this keyword can be used to get the current instance of a class This keyword can be returned as a statement from the method. In this situation, the method's return type must be the class type (non-primitive). Let's look at an example: class Sample{Sample getObject() { return this; } void foo(){ System.out.println("Inside foo function") } } class Test{ public static void main(String args[]){ Sample s = new Sample(); s.getObject().foo(); } } Output - Inside foo functionIn the above code, we have a function ‘getObject’ defined in the Sample class which returns a reference to the current invoking object. We use this reference returned to call the foo() method from the Test class. b) final keyword in Java: The final keyword is used in a variety of situations. To begin with, final is a non-access modifier that only applies to variables, methods, and classes. The behaviour of final in each scenario is listed below: Final Variables: Example - final int temp = 10;Final Classes: A final class is one that has been declared with the final keyword. It is not possible to extend a final class. A final class can be used in two ways:
Example - final class Sample{ // code } class Test extends Sample // COMPILE-ERROR! { // code } The above code gives a compile-time error. The reason is that the class Sample is declared as final and since the class Test is trying to extend the Sample class, it gives a compile-time error. Final Methods: A method is called a final method when it is declared with the final keyword. It is not possible to override a final method. In the Object class, many methods defined are declared final. This is done so that a user cannot modify the definition of those functions in their java classes. We must use the final keyword to declare methods for which we must use the same implementation throughout all derived classes. Example - class Sample{ final void fun() { System.out.println("Inside fun function"); } } class Test extends Sample { void fun() // COMPILE-ERROR! { //code } } The above code on execution gives a compile-time error. The reason is that the fun() function declared in the Sample class is a final method so we cannot override it in the inherited class. In the above code, the Test class tries to override the fun() function defined in the Sample class and this leads to a compilation error. c) static keyword in Java: In Java, the static keyword is mostly used to control memory. In Java, the static keyword is used to share a class's variable or method. Static keywords can be used with variables, methods, blocks, and nested classes. The static keyword refers to a class rather than a specific instance of that class. The static keyword is used in the following ways: Static Blocks: You can declare a static block that gets executed exactly once when the class is first loaded if you need to do the computation to initialise your static variables. Consider the Java program below, which demonstrates the use of static blocks. class Test{ static int x = 25; static int y; // static block static { System.out.println("Inside Static block."); y = x * 4; } public static void main(String[] args) { System.out.println("Value of x : " + x); System.out.println("Value of y : " + y); } } Output - Inside Static block.Value of x : 25 Value of y : 100 Explanation - In the above code, there are 2 static variables x and y. X is initialised with 25. We can see that first of all, the static block is executed which prints the statement “Inside Static block.” and initialises y to x * 4 (i.e., 100). Static Variables: When a variable is marked as static, a single copy of the variable is made at the class level and shared among all objects. Static variables are effectively global variables. The static variable is shared by all instances of the class. In a program, static blocks and static variables are executed in the order in which they appear. Example - class Test{ // static variable static int x = fun(); // static block static { System.out.println("Inside static block"); } // static method static int fun() { System.out.println(Inside fun function"); return 10; } public static void main(String[] args) { System.out.println("Value of x : " + x); System.out.println("Inside main method"); } } Output - Inside fun functionInside static block Value of x : 10 Inside main method Explanation - In the above code, first of all, x gets initialised by calling the fun() function. Hence, the statement “Inside fun function” gets printed. Then, the static block gets executed since it is after the initialisation of x statement. At last, the statements inside the main method get printed. Static Methods: The static method is defined as a method that is declared using the static keyword. The main() method is the most common example of a static method. Any static member of a class can be accessed before any objects of that class are generated, and without requiring a reference to any object. Static methods are subject to the following constraints:
Example - class Test{ static int x = 1; // static variable int y = 20; // instance variable static void fun() // static method { x = 20; System.out.println("Inside fun function"); y = 10; // compilation error since there is a static reference to the non-static field b foo(); // compilation error since there is a static reference to the non-static method foo() System.out.println(super.a); // compilation error since we cannot use super in a static context } void foo() // instance method { System.out.println("Inside foo function"); } public static void main(String[] args) { // main method } } The above code results in a compilation error. There are 3 reasons for it.
Static Classes: When a class is declared with the static keyword, it is said to be a static class. A class can be made static in Java if and only if it is nested inside another class. We can't use the static modifier on top-level classes, but we can use it on nested classes. Example - public class Test {private static String str = "Interview bit"; // Static class static class Sample { public void display(){ System.out.println(str); } } public static void main(String args[]) { Test.Sample obj = new Test.Sample(); obj.display(); } } Output - Interview bitExplanation - In the above code, we have a static nested class named ‘Sample’ inside the ‘Test’ class. We create an object of the Sample class and call the display function. d) super keyword in Java: In Java, the super keyword is a reference variable that refers to parent class instances. With the concept of Inheritance, the term "super" entered the picture. It's most commonly used in the following situations: Using super with variables: When a derived class and a base class have identical data members, there is uncertainty for the JVM as to which class’s data member is being referred to. In order to resolve this ambiguity, we use the super keyword with the data member’s name. This code snippet will help us comprehend it better: class Sample1{ int x = 1; } class Sample2 extends Sample1 { int x = 2; void display() { System.out.println("The value of x is : " + super.x); } } class Test { public static void main(String[] args) { Sample2 s = new Sample2(); s.display(); } } Output - The value of x is : 1Explanation - In the above code both the classes, Sample1 and Sample2 have a data member named ‘x’. We use the super keyword inside the display function of the Sample2 class to access the data member x of the parent class Sample1. Using super with methods: To resolve ambiguity when a parent and child class have the same-named methods, we employ the super keyword. This code snippet demonstrates how to use the super keyword. class Sample1{ void fun() { System.out.println("Inside Sample1's fun method"); } } class Sample2 extends Sample1 { void fun() { System.out.println("Inside Sample2's fun method"); } void display() { super.fun(); } } class Test { public static void main(String[] args) { Sample2 s = new Sample2(); s.display(); } } Output - Inside Sample1's fun methodExplanation - In the above code, both the classes Sample1 and Sample2 have a method named fun. However, in the display method of the Sample2 class, the statement “Inside Sample1’s fun method” gets printed because of the super keyword. Use of the super keyword with constructors: The super keyword can also be used to access the constructor of the parent class. Another key point to note is that, depending on the situation, 'super' can refer to both parametric and non-parametric constructors. The following is a code snippet to demonstrate the concept: class Sample1{ Sample1() { System.out.println("Inside Sample1's default constructor.") } } class Sample2 extends Sample1 { Sample2() { super(); System.out.println("Inside Sample2's default constructor."); } } class Test { public static void main(String[] args) { Sample2 s = new Sample2(); } } Output - Inside Sample1's default constructor.Inside Sample2's default constructor. Explanation - In the above code, the class Sample2 extends the class Sample1. We invoke the constructor of the Sample1 class in the constructor of the Sample2 class by using the super keyword. Hence, when we create an instance of the Sample2 class, both the statements get printed. |
|
| 21. |
Datatypes in Java |
|||||||||||||||||||||||||||
|
Answer» The different sizes and values that can be stored in the variable are defined by data types. In Java, there are two types of data types: Primitive Data Types in Java:- Primitive data types are the building blocks of data manipulation in the Java programming language. These are the most fundamental data types in the Java programming language. Following are the different primitive data types available in Java:-
Non Primitive data types in Java:- The non-primitive data types in Java include classes, interfaces and arrays. We will discuss more on them in the upcoming topics. |
||||||||||||||||||||||||||||
| 22. |
Variables in Java |
|
Answer» In Java, a variable is a data container that stores data values during the execution of a Java program. A data type is allocated to each variable, indicating the type and quantity of data it may store. It is a program’s fundamental storage unit. All variables in Java must be defined before they may be used. Syntax of declaring a variable:- datatype variable_name;Here, datatype refers to the type of data that can be stored in the variable. variable_name refers to the name of the variable being declared. In the above image, we can see that a variable named ‘age’ has been declared of type ‘int’ and has been initialised with the value ‘20’. Types of variables:-
|
|
| 23. |
Java Terminology |
|
Answer» Let us quickly go through some of the most important terms used in the Java programming language. JVM: The JVM stands for Java Virtual Machine. A program’s execution is divided into three stages. A Java program is written, compiled and then run. As we can see in the above image, first the JVM language classes are processed by the class loader subsystem which is responsible for loading, linking and initialization of the java classes. After being processed by the class loader, the generated files are stored in the JVM Memory which consists of method area, heap, JVM language stacks, PC registers and native method stacks. The execution engine accesses the files from this JVM memory and makes use of the Native Method Interface and Native Method Libraries.
The Java Virtual Machine’s job is to run the bytecode generated by the compiler. Although each operating system has its own JVM, the output they provide after bytecode execution is consistent across all of them. Java is known as a platform-independent language for this reason. Bytecode: Bytecode is a type of intermediate code generated by the compiler after source code has been compiled (JAVA Program). Java is a platform-independent language thanks to this intermediate code. JRE: The Java Runtime Environment (JRE) is included with the JDK. The JRE installation on our computers allows us to run the Java program, but we cannot compile it. A browser, JVM, applet support, and plugins are all included in JRE. JRE is required for a computer to run a Java program. In the above image, we can see that JVM together with the Java Class Libraries makes up the JRE. Java Development Kit (JDK): When we learn about bytecode and JVM, we use the name JDK. As the name implies, it is a complete Java development kit that includes everything from the compiler to the Java Runtime Environment (JRE), debuggers, and documentation. In order to design, compile, and run the java application, we must first install JDK on our computer. In the above image, we can clearly see that JVM and the Library classes together make up the JRE. JRE when combined with Development Tools makes up JDK. Garbage Collection: Garbage collection is the technique through which Java programs maintain their memory automatically. Java programs are compiled into bytecode that may be executed by a Java Virtual Machine, or JVM. Objects are produced on the heap, which is a part of memory devoted to the Java application, while it runs on the JVM. Some objects will become obsolete over time. To free up memory, the garbage collector detects these useless objects and deletes them. finalize method: It’s a method that the Garbage Collector calls shortly before deleting or destroying an object that’s suitable for Garbage Collection in order to do cleanup. Clean-up activity entails de-allocating or closing the resources associated with that object, such as Database Connections and Network Connections. It’s important to remember that it’s not a reserved keyword. Garbage Collector destroys the object as soon as the finalise method completes. The finalise method is found in the Object class and has the following syntax: protected void finalize throws Throwable{} Since the finalize function is contained in the Object class and Object is the superclass of all Java classes, the finalize method is available to all Java classes. As a result, the garbage collector may invoke the finalise function on any java object. We must override the finalize method present in the Object class to specify our own clean-up activities since the finalize function in the Object class has an empty implementation.
|
|