Core Java Interview Questions and Answers 2024
Unlock the secrets to acing your Core Java interview questions and answers 2024. Boost your confidence and land your dream job in Java development.
- What is Java?
Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
- What is the difference between JDK, JRE, and JVM?
JDK (Java Development Kit): It is a software development environment for writing Java applications. It includes the JRE, compilers, and development tools.
JRE (Java Runtime Environment): It is the environment in which Java applications run. It includes the JVM and core libraries.
JVM (Java Virtual Machine): It is an abstract machine that provides a runtime environment in which Java bytecode can be executed.
- What is the main difference between an interface and an abstract class?
An interface is a contract for a class to implement specific methods, but it cannot have any implementation. An abstract class can have some concrete methods along with abstract methods.
- Explain the difference between == and .equals() in Java.
== is used for comparing the reference of two objects.
.equals() is used for comparing the content or value equivalence of two objects.
- What is the purpose of the static keyword in Java?
The static keyword in Java is used to create variables and methods that belong to the class rather than to any specific instance. This means that only one instance of a static variable or method exists, regardless of how many objects of the class are created.
- What is a singleton class?
A singleton class in Java is a class that allows only one instance to be created throughout the entire execution of a program. It is used to control the object creation, limiting the number of instances to one.
Explain the concept of multithreading in Java.
Multithreading in Java is a process of executing multiple threads simultaneously. Threads are lightweight sub-processes that share the same memory space and can run concurrently.
- What is the final keyword used for?
In Java, the final keyword is used to apply restrictions on class, method, and variable. A final class cannot be inherited, a final method cannot be overridden, and a final variable cannot be reassigned.
- What is exception handling in Java?
Exception handling in Java is a mechanism to handle runtime errors (exceptions) so that normal flow of the program can be maintained. It involves the use of try, catch, finally, and throw keywords.
- What is the purpose of the super keyword?
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. It is used to call methods of the parent class, access instance variables, and invoke the constructor of the parent class.
- What are the main principles of Object-Oriented Programming (OOP)?
The main principles of OOP are encapsulation, inheritance, and polymorphism. These principles promote code reusability, maintainability, and modularity.
- What is the difference between ArrayList and LinkedList in Java?
ArrayList is implemented as a resizable array, while LinkedList is implemented as a doubly linked list. ArrayList provides faster access to elements, while LinkedList offers faster insertion and deletion of elements.
- What is the difference between HashMap and HashTable in Java?
HashMap is not synchronized and allows null keys/values, while HashTable is synchronized and does not allow null keys/values. HashMap is generally preferred over HashTable in non-thread-safe scenarios.
Explain the concept of multithreading.
Multithreading in Java is a process of executing multiple threads simultaneously. Threads are lightweight sub-processes that share the same memory space and can run concurrently, allowing for efficient utilization of CPU resources.
- What is a lambda expression in Java?
A lambda expression is a concise way to represent an anonymous function. It allows the definition of a method without a name. Lambda expressions simplify code by reducing the need for boilerplate code.
- What is a try-with-resources statement in Java?
try-with-resources is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.
- Explain the concept of garbage collection in Java.
Garbage collection is the process by which Java automatically manages memory. It reclaims memory that is no longer in use by the program, ensuring efficient memory utilization and preventing memory leaks.
- What is the purpose of the this keyword?
The this keyword in Java is a reference to the current instance of the class. It is used to differentiate between instance variables and parameters with the same name. It is also used to call instance methods.
- What is the difference between method overloading and method overriding?
Method overloading involves having multiple methods with the same name in a class, but with different parameters. Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
- Explain the final keyword in Java.
The final keyword is used to apply restrictions on a class, method, or variable. A final class cannot be inherited, a final method cannot be overridden, and a final variable cannot be reassigned.
Explain the concept of static initialization block.
A static initialization block is a block of code in a Java class that is executed only once when the class is loaded into memory. It is used for static initializations of a class.
- What is a constructor in Java?
A constructor in Java is a special method used to initialize an object of a class. It has the same name as the class and does not have any return type.
.20. What is method chaining in Java?
Method chaining, also known as “fluent interface,” is a design pattern where multiple methods can be called on an object in a single statement. This is achieved by returning this from methods.
- Explain the difference between transient and volatile variables in Java.
transient variables are not serialized during object serialization, meaning their values are not saved. volatile variables are used to indicate that a variable may be modified by multiple threads.
- What is the toString() method in Java?
The toString() method is a method provided by the Object class that is used to return a string representation of an object. It is often overridden in user-defined classes to provide a meaningful representation.
- What is the purpose of the equals() method in Java?
The equals() method is used to compare the contents of two objects for equality. It is often overridden in user-defined classes to define custom equality criteria.
- Explain the concept of anonymous inner classes in Java.
Anonymous inner classes are classes defined without a name. They are typically used when you need to extend an existing class or implement an interface, but you don’t need to reuse the class elsewhere.
What is a Marker Interface in Java?
A Marker Interface in Java is an interface that has no methods or fields inside it. It is used to indicate a capability or feature to the JVM.
- Explain the purpose of the ClassLoader in Java.
The ClassLoader in Java is responsible for loading class files into memory. It searches for the class file in the classpath and loads it into memory.
- What is the purpose of the equals() and hashCode() methods in Java?
The equals() method is used to compare the content of two objects for equality, while the hashCode() method returns a hash code value for the object. These methods are often overridden together to maintain consistency.
- Explain the difference between LinkedList, ArrayList, and Vector.
LinkedList is implemented as a doubly linked list and provides fast insertion and deletion. ArrayList is implemented as a resizable array, providing fast access. Vector is similar to an ArrayList but is synchronized.
- What is the purpose of the transient keyword in Java?
The transient keyword is used to indicate that a variable should not be serialized during object serialization. It is used when you don’t want to persist the state of a variable.
- Explain the finalize() method in Java.
The finalize() method is a method provided by the Object class that is called by the garbage collector before an object is garbage collected. It can be overridden to perform any necessary cleanup operations.
- What is the purpose of the Package statement in Java?
The package statement in Java is used to group related classes, interfaces, and sub-packages together. It helps in organizing the code and preventing naming conflicts.
Explain the concept of inner classes in Java.
Inner classes are classes defined inside another class. They have access to the members of the outer class and can be used to logically group related functionality.
- Explain the concept of method references in Java.
Method references provide a shorthand notation for a lambda expression to call a method. They can make the code more readable and concise, especially when you want to pass a method as an argument.
For Free, Demo classes Call: 020-71173125
Registration Link: Java Classes in Pune!
——————————————————————————————————————————————
Java Interview Questions for Freshers
- Why is Java a platform independent language?
Java language was developed in such a way that it does not depend on any hardware or software due to the fact that the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.
- The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it
- Why is Java not a pure object oriented language?
Java supports primitive data types – byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language.
- Difference between Heap and Stack Memory in java. And how java utilizes this.
Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.
Java Utilizes this memory as –
- When we write a java program then all the variables, methods, etc are stored in the stack memory.
- And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.
Example- Consider the below java program:
class Main {
public void printArray(int[] array){
for(int i : array)
System.out.println(i);
}
public static void main(String args[]) {
int[] array = new int[10];
printArray(array);
}
}
For this Java program. The stack and heap memory occupied by java is –
Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area.
And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime.
- Can java be said to be the complete object-oriented programming language?
It is not wrong if we claim that java is the complete object-oriented programming language. Because Everything in Java is under the classes. And we can access that by creating the objects.
But also if we say that java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.
Now for the question: Is java a completely object-oriented programming language? We can say that – Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don’t directly belong to the Integer classes.
- How is Java different from C++?
- C++ is only a compiled language, whereas Java is compiled as well as an interpreted language.
- Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled.
- C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers.
- C++ supports the concept of Multiple inheritances whereas Java doesn’t support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.
- Pointers are used in C/ C++. Why does Java not make use of pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.
- What do you understand by an instance variable and a local variable?
Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.
All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.
Example:
public void athlete() {
String athleteName;
double athleteSpeed;
int athleteAge;
}
- What are the default values assigned to variables and instances in java?
- There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of (Variable might not be initialized).
- But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type.
- If it is a reference, then it will be assigned to null.
- If it is numeric, then it will assign to 0.
- If it is a boolean, then it will be assigned to false. Etc.
- What do you mean by data encapsulation?
- Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
- It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
- It is used for the security of the private properties of an object and hence serves the purpose of data hiding.
- Tell us something about JIT compiler.
- JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
- The compiler is nothing but a translator of source code to machine-executable code. But what is special about the JIT compiler? Let us see how it works:
o First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
o Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
o JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
o Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.
- How is an infinite loop declared in Java?
Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:
- Using For Loop:
for (;;)
{
// Business logic
// Any break logic
}
- Using while loop:
while(true){
// Business logic
// Any break logic
}
- Using do-while loop:
do{
// Business logic
// Any break logic
}while(true);
- Briefly explain the concept of constructor overloading
Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type and their numbers.
- Can the main method be Overloaded?
Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of –
public static void main(string[] args)
Consider the below code snippets:
class Main {
public static void main(String args[]) {
System.out.println(” Main Method”);
}
public static void main(int[] args){
System.out.println(“Overloaded Integer array Main Method”);
}
public static void main(char[] args){
System.out.println(“Overloaded Character array Main Method”);
}
public static void main(double[] args){
System.out.println(“Overloaded Double array Main Method”);
}
public static void main(float args){
System.out.println(“Overloaded float Main Method”);
}
}
- Comment on method overloading and overriding by citing relevant examples.
In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.
The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.
Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.
- A single try block and multiple catch blocks can co-exist in a Java Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:
public class MultipleCatch {
public static void main(String args[]) {
try {
int n = 1000, x = 0;
int arr[] = new int[n];
for (int i = 0; i <= n; i++) {
arr[i] = i / x;
}
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.println(“1st block = ArrayIndexOutOfBoundsException”);
}
catch (ArithmeticException exception) {
System.out.println(“2nd block = ArithmeticException”);
}
catch (Exception exception) {
System.out.println(“3rd block = Exception”);
}
}
}
Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.
- Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.
- final variable:
o When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
o If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
- final method:
o A method declared as final cannot be overridden by its children’s classes. o A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed here
- final class:
o No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.
- Do final, finally and finalize keywords have the same function? All three keywords have their own utility while programming.
Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:
final int a=100;
a = 0; // error
The second statement will throw an error.
Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println(“Exception occurred”);
}
finally {
System.out.println(“Execution of finally block”);
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:
public static void main(String[] args) {
String example = new String(“hello”);
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}
- Is it possible that the ‘finally’ block will not be executed? If yes then list the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
- Suppose we use System.exit() in the above statement.
- If there are fatal errors like Stack overflow, Memory access error, etc. 19. Identify the output of the java program and state the reason.
- public class Myclass
- {
- public static void main(String[] args) {
- final int i;
- i = 20;
- int j = i+20;
- i = j+30;
- System.out.println(i + ” ” + j);
- }
- }
The above code will generate a compile-time error at Line 7 saying – [error: variable i might already have been initialized]. It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.
- When can you use super keyword?
- The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
- Following are the cases when this keyword can be used:
o Accessing data members of parent class when the member names of the class and its child subclasses are same.
o To call the default and parameterized constructor of the parent class inside the child class.
o Accessing the parent class methods when the child classes have overridden them.
- The following example demonstrates all 3 cases when a super keyword is used.
class Parent{
protected int num = 1;
Parent(){
System.out.println(“Parent class default constructor.”);
}
Parent(String x){
System.out.println(“Parent class parameterised constructor.”);
}
public void foo(){
System.out.println(“Parent class foo!”);
}
}
class Child extends Parent{
private int num = 2;
Child(){
//super constructor call should always be in the first line
// super(); // Either call default super() to call default parent constructor OR super(“Call Parent”); // call parameterised super to call parameterised parent constructor. System.out.println(“Child class default Constructor”);
}
void printNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class
}
@Override
public void foo(){
System.out.println(“Child class foo!”);
super.foo(); //Calls foo method of Parent class inside the Overriden foo method of Child class. }
}
public class DemoClass {
public static void main(String args[]) {
Child demoObject=new Child();
demoObject.foo();
/*
This would print –
Parent class parameterised constructor.
Child class default Constructor
Child class foo!
Parent class foo!
*/
}
}
- Can the static methods be overloaded?
Yes! There can be two or more static methods in a class with the same name but differing input parameters.
- Why is the main method static in Java?
The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static.
- Can the static methods be overridden?
- No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
- Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.
- Difference between static methods, static variables, and static classes in java.
- Static Methods and Static variables are those methods and variables that belong to the class of the java program, not to the object of the class. This gets memory where the class is loaded. And these can directly be called with the help of class names.
o For example – We have used mathematical functions in the java program like – max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like – Math.max(), Math.min(), etc. So that is a static method. And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
- Static classes – A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.
- What is the main objective of garbage collection?
The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.
- This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.
- What is a ClassLoader?
- Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required.
- Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.
- What part of memory – Stack or Heap – is cleaned in garbage collection process?
Heap.
Java Intermediate Interview Questions
- Apart from the security aspect, what are the reasons behind making strings immutable in Java?
A String is made immutable due to the following reasons:
- String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.
- Multithreading: The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
- Collections: In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.
- What is a singleton class in Java? And How to implement a singleton class?
Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed.
Understand this with the help of an example-:
Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as –
class WaterJug{
private int waterQuantity = 500;
private WaterJug(){}
private WaterJug object = null;
// Method to provide the service of Giving Water.
public int getWater(int quantity){
waterQuantity -= quantity;
return quantity;
}
// Method to return the object to the user.
public static Waterjug getInstance(){
// Will Create a new object if the object is not already created and return the object. if(object == null){
object = new WaterJug();
}
return object;
}
}
In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance(). And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.
Waterjug glass1 = WaterJug.getInstance();
glass1.getWater(1);
We can get the single object using this getInstance(). And it is static, so it is a thread safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:
- When singletons are written with double-checked locking, they can be thread-safe. • We can use static singletons that are initialized during class loading. Like we did in the above example.
- But the most straightforward way to create a thread-safe singleton is to use Java enums.
- Which of the below generates a compile-time error? State the reason.
- int[] n1 = new int[0];
- boolean[] n2 = new boolean[-200];
- double[] n3 = new double[2241423798];
- char[] ch = new char[20];
We get a compile-time error in line 3. The error we will get in Line 3 is – integer number too large. It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the capacity of the integer. The maximum array size we can declare is – (2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is – NegativeArraySizeException.
Here what will happen is – At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.
- How would you differentiate between a String, StringBuffer, and a StringBuilder?
- Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
- Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
- Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
- Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads.
Syntax:
// String
String first = “Hello”;
String second = new String(“Hello”);
// StringBuffer
StringBuffer third = new StringBuffer(“Hello”);
// StringBuilder
StringBuilder fourth = new StringBuilder(“Hello”);
- Using relevant properties highlight the differences between interfaces and abstract classes.
- Availability of methods: Only abstract methods are available in interfaces, whereas non abstract methods can be present along with abstract methods in abstract classes. • Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables. • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
- Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
- Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;
Abstract class example:
public abstract class Athlete {
public abstract void walk();
}
Interface example:
public interface Walkable {
void walk();
}
- In Java, static as well as private method overriding is possible. Comment on the statement.
The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.
- What makes a HashSet different from a TreeSet?
Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.
- Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
- Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
- Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
- Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.
- Why is the character array preferred over string for storing confidential information?
In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.
- What do we get in the JDK file?
- JDK– For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
- JRE – To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes + JVM. What are JAVA Classes? It contains some predefined methods that help Java programs to use that feature, build and execute. For example – there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
- JVM – (Java Virtual Machine) JVM is a part of JRE that executes the Java program at the end. Actually, it is part of JRE, but it is software that converts bytecode into machine executable code to execute on hardware.
- What are the differences between JVM, JRE and JDK in Java?
Criteria JDK JRE JVM Abbreviation Java Development Kit Java Runtime
Environment Java Virtual Machine
Definition JDK is a complete software
development kit for
developing Java
applications. It
comprises JRE,
JavaDoc, compiler,
debuggers, etc.
Main
Purpose JDK is mainly used for code development
and execution.
JRE is a software package providing Java class libraries, JVM and all the required
components to run the Java
applications.
JRE is mainly used for environment creation to execute the code.
JVM is a platform-dependent, abstract machine comprising of 3 specifications – document describing the JVM implementation
requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution.
JVM provides specifications for all the implementations to JRE.
Tools
provided
JDK provides tools like compiler,
debuggers, etc for code development
JRE provides
libraries and classes required by JVM to run the program.
JVM does not include any tools, but instead, it provides the specification for implementation.
Summary JDK = (JRE) + Development tools
JRE = (JVM) +
Libraries to execute the application
JVM = Runtime environment to execute Java byte code.
- What are the differences between HashMap and HashTable in Java? HashMap HashTable
HashMap is not synchronized thereby making it better for non-threaded applications.
Allows only one null key but any number of null in the values.
Supports order of insertion by making use of its subclass LinkedHashMap.
HashTable is synchronized and hence it is suitable for threaded applications.
This does not allow null in both keys or values.
Order of insertion is not guaranteed in HashTable.
- What are the different ways of threads usage?
- We can define and implement a thread in java using two ways:
o Extending the Thread class
class class1ThreadExample extends Thread{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
class1ThreadExample ib = new class1ThreadExample();
ib.start();
}
}
- Implementing the Runnable interface
class class1ThreadExample implements Runnable{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
Thread ib = new Thread(new class1ThreadExample ());
ib.start();
}
}
- Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes. • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.
- What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?
There are a total of 3 different types of priority available in Java.
MIN_PRIORITY: It has an integer value assigned with 1.
MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM.
- What is the difference between the program and the process?
- A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. • A program doesn’t execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.
- What is the difference between the ‘throw’ and ‘throws’ keyword in java?
- The ‘throw’ keyword is used to manually throw the exception to the calling method. • And the ‘throws’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.
Example –
class Main {
public static int testExceptionDivide(int a, int b) throws ArithmeticException{ if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}
Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.
And the method testExceptionDivide ‘throws’ the exception based on the condition.
- What are the differences between constructor and method of a class in Java?
Constructor Method
Constructor is used for initializing the object state. Method is used for exposing the object’s behavior.
Constructor Method
Method should have a return type.
Constructor has no return type.
Even if it does not return anything, return type is void.
Constructor gets invoked implicitly. Method has to be invoked on the object explicitly.
If the constructor is not defined, then a default constructor is provided by the java compiler.
If a method is not defined, then the compiler does not provide it.
The constructor name should be equal to the class name. The name of the method can have any name or have a class name too.
A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn’t make sense. Java throws compilation error saying – modifier final not allowed here
Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects.
A method can be defined as final but it cannot be overridden in its subclasses.
A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.
- What is the ‘IS-A ‘ relationship in OOPs java?
‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.
Example – Consider a Television (Typical CRT TV). Now another Smart TV that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.
So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ].
- Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.
- What happens if the static modifier is not included in the main method signature in Java?
There wouldn’t be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.
- Consider the below program, identify the output, and also state the reason for that.
public class Main{
public static void main(String[] args) {
System.out.println(” Hello. Main Method. “);
}
public static void main(int[] args) {
System.out.println(” Hello. Main Method2. “);
}
}
The output of the above program will be Hello. Main Method. This is because JVM will always call the main method based on the definition it already has. Doesn’t matter how many main methods we overload it will only execute one main method based on its declaration in JVM.
- Can we make the main() thread a daemon thread?
In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.
- What happens if there are multiple main methods inside one class in Java?
The program can’t compile as the compiler says that the method has been already defined inside the class.
- What do you understand by Object Cloning and how do you achieve it in Java?
- It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
protected Object clone() throws CloneNotSupportedException{
return (Object)super.clone();
}
- In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.
- How does an exception propagate in the code?
When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.
- How do exceptions affect the program if it doesn’t handle them?
Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get
the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users. This is the type of error that cannot be controlled by the
programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.
- Is it mandatory for a catch block to be followed after a try block?
No, it is not necessary for a catch block to be present after a try block. – A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.
- Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.
- Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.
However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.
- Why does the java array index start with 0?
It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.
Example – Consider the array and assume each element takes 4-byte memory space. Then the address will be like this –
Now if we want to access index 4. Then internally java calculates the address using the formula-
[Base Address + (index * no_of_bytes)]. So according to this. The starting address of the index 4 will be – [100 + (4*4)] = 116. And exactly that’s what the address is calculated.
Now consider the same with 1 index Array –
Now if we apply the same formula here. Then we get – 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula – [Base Address + ((index-1) * no_of_bytes)].
And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.
- Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.
Example – To Delete from the front of the linked list, internally the references adjustments happened like this.
The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.
Whereas in the ArrayList, internally it should work like this-
For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.
- How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.
There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.
Return Type Method Description
boolean add(Element e): This method is used for adding the element at the end of the List. The Datatype of the element is of any type it has been initially assigned with. It returns the boolean indicating successfully inserted or not.
void add(int index, Element e): This method is the overloaded version of add() method. In this, along with the element, the index is also passed to the method for the specific index the value needs to be inserted.
boolean addAll(Collection <extends ? Element > c): This method helps to add all elements at the end of collections from the list received in the parameter. It contains an iterator that helps to iterate the list and add the elements to the collection.
boolean addAll(int index, Collection <extends ? Element > c): This is the overloaded method for addAll() method. In this along with the list, we can pass the specified index from which the list elements need to be added.
- How does the size of ArrayList grow dynamically? And also state how it is implemented internally.
ArrayList is implemented in such a way that it can grow dynamically. We don’t need to specify the size of ArrayList. For adding the values in it, the methodology it uses is –
- Consider initially that there are 2 elements in the ArrayList. [2, 3]. 2. If we need to add the element into this. Then internally what will happen is-
- ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old – [2, 3], New – [2, 3, null].
- Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.
- This process continues and the time taken to perform all of these is considered as the amortized constant time.
This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed –
- It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.
- After searching the element, it needs to shift the element from the right side to fill the index.
So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).
Java Interview Questions for Experienced
- How is the ‘new’ operator different from the ‘newInstance()’ operator in java?
Both ‘new’ and ‘newInstance()’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘newInstance()’ operator.
The ‘newInstance()’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.
- Is exceeding the memory limit possible in a program despite having a garbage collector?
Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.
In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.
Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.
Let’s take a look at the following example:
List<String> example = new LinkedList<String>();
while(true){
example.add(new String(“Memory Limit Exceeded”));
}
- Why is synchronization necessary? Explain with the help of a relevant example.
Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.
Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.
No synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.
Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.
With synchronization:
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.
}
- Define System.out.println().
System.out.println() is used to print the message on the console. System – It is a class present in java.lang package. Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.
So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.
- Can you explain the Java thread lifecycle?
Java thread life cycle is as follows:
- New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
- Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
- Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
- Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time of its aliveness, the thread should go to a runnable state.
o A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
o A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
- Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.
The following flowchart clearly explains the lifecycle of the thread in Java.
- Is it possible to import the same class or package twice in Java and what happens to it during runtime?
It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.
- In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?
This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.
- Will the finally block be executed if the code System.exit(0) is written at the end of try block?
- The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.
- What do you understand by marker interfaces in Java?
Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.
- What are the possible ways of making object eligible for garbage collection (GC) in Java?
First Approach: Set the object references to null once the object creation purpose is served.
public class GarbageCollect {
public static void main (String [] args){
String s1 = “Some String”;
// s1 referencing String object – not yet eligible for GC
s1 = null; // now s1 is eligible for GC
}
}
Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.
public class GarbageCollect {
public static void main(String [] args){
String s1 = “To Garbage Collect”;
String s2 = “Another Object”;
System.out.println(s1); // s1 is not yet eligible for GC
s1 = s2; // Point s1 to other object pointed by s2
/* Here, the string object having the content “To Garbage Collect” is not referred by any reference variable. Therefore, it is eligible for GC */
}
}
Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don’t have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.
public class GarbageCollect {
IBGarbageCollect ib;
public static void main(String [] str){
GarbageCollect ibgc1 = new GarbageCollect();
GarbageCollect ibgc2 = new GarbageCollect();
ibgc1.ib = ibgc2; //ibgc1 points to ibgc2
ibgc2.ib = ibgc1; //ibgc2 points to ibgc1
ibgc1 = null;
ibgc2 = null;
/*
* We see that ibgc1 and ibgc2 objects refer
* to only each other and have no valid
* references- these 2 objects for island of isolcation – eligible for GC
*/
}
}
Java Programming Interview Questions
- Check if a given string is palindrome using recursion.
/*
* Java program to check if a given inputted string is palindrome or not using recursion. */
import java.util.*;
public class Myclass {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String word = s.nextLine();
System.out.println(“Is “+word+” palindrome? – “+isWordPalindrome(word)); }
public static boolean isWordPalindrome(String word){
String reverseWord = getReverseWord(word);
//if word equals its reverse, then it is a palindrome
if(word.equals(reverseWord)){
return true;
}
return false;
}
public static String getReverseWord(String word){
if(word == null || word.isEmpty()){
return word;
}
return word.charAt(word.length()- 1) + getReverseWord(word.substring(0, word.length() – 1)); }
}
- Write a Java Program to print Fibonacci Series using Recursion.
class Myclass {
public static void printFibonacci(int val_1, int val_2, int num){
//Base Case
if(num == 0)
return;
//Printing the next Fibonacci number
System.out.print( val_1 + val_2 + ” “);
//Recursively calling for printing Fibonacci for remaining length
printFibonacci(val_2, val_1+val_2, –num);
}
public static void main(String args[]) {
System.out.println(” *** Fibonacci Series *** “);
//Printing the first two values
System.out.print(“0 1 “);
//Calling Method to print the fibonacci for length 10
printFibonacci(0, 1, 10);
}
}
In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.
- Write a Java Program to find the factorial of a given number.
public class FindFactorial {
public static void main(String[] args) {
int num = 10;
long factorialResult = 1l;
for(int i = 1; i <= num; ++i)
{
factorialResult *= i;
}
System.out.println(“Factorial: “+factorialResult);
}
}
- Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.
Example, consider the number:
- Step 1: 163 => 1+6+3 = 10
- Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number
public class MagicNumber{
public static void main(String[] args) {
int num = 163;
int sumOfDigits = 0;
while (num > 0 || sumOfDigits > 9)
{
if (num == 0)
{
num = sumOfDigits;
sumOfDigits = 0;
}
sumOfDigits += num % 10;
num /= 10;
}
// If sum is 1, original number is magic number
if(sumOfDigits == 1) {
System.out.println(“Magic number”);
}else {
System.out.println(“Not magic number”);
}
}
}
- Write a Java program to create and throw custom exceptions.
class First {
public static void main(String args[]) throws CustomException {
// Throwing the custom exception be passing the message
throw new CustomException(” This is my custom Exception “);
}
}
//Creating Custom Exception Class
class CustomException extends Exception{
//Defining Constructor to throw exception message
public CustomException(String message){
super(message);
}
}
We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.
- Write a Java program to reverse a string.
class First{
public static void main(String[] args){
//Input String
String str = “Welcome”;
//Pointers.
int i = 0, j = str.length()-1;
//Result character array to store the reversed string.
char[] revString = new char[j+1];
//Looping and reversing the string.
while(i < j){
revString[j] = str.charAt(i);
revString[i] = str.charAt(j);
i++;
j–;
}
//Printing the reversed String.
System.out.println(“Reversed String = ” + String.valueOf(revString));
}
}
In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.
Do visit our channel to get more information: Click Here
Author:-
Anil Giri
Call the Trainer and Book your free demo Class For Java Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.