Java is a widely-used programming language that is used by software developers in technology companies. The blog aims to target Java interview questions and answers that the interviewer asks for Java-related topics like Java OOPs, Hibernate, Spring, Maven, Microservices, etc. Every question is followed with an answer so that a beginner, intermediate, or advanced level Java developer can prepare for the job interview in less time.
It is suggested to go through this blog 2-3 times to face a technical interview for the position of Java developer from Software Engineer level to Principal Engineer level.
Java is a most popular and widely used programming language that is defined as a collection of objects. With the use of Java, we can develop software, games, desktop applications, web applications, etc.
Java is a purely object-oriented programming language because it is impossible to write any Java program without a class or object. Java is not a pure programming language focused on objects. Java supports non-primitive types of data, such as int, float, boolean, double, long, etc.
JDK is the acronym for Java Development Kit. It includes the tools and libraries that are used in the creation of Java software. Also, it contains the compilers and debuggers that are needed for Java program compilation.
JRE, on the other hand, is an acronym for Java Runtime Environment. It comes with the installation package of JDK as JRE provides libraries and JVM that are used to execute a Java program.
Java Virtual Machine or JVM in short is a conceptual (or abstract) machine that is used to execute bytecode. Both hardware and software platforms have different JVM and for this reason, JVM is platform-independent. JVM is responsible for verifying and executing the bytecode on a platform.
JIT or Just in Time compiler in Java is used for performance enhancement. By default, it is enabled. It is a compilation achieved at execution time. The use of the JIT compiler was popularized by Java by using it in the JVM.
Windows helps you to write Java code and compile it on the Windows platform. As it is in the Unix environment, the class and jar files that you get from the Windows platform will run. So it’s a completely autonomous language of the platform. The Java byte code is behind all this portability. Java compiler-generated bytecode can be interpreted by any JVM. So writing programs in Java and expecting them to run on any platform is much simpler. The Javac Java compiler compiles Java code, and the Java JVM compiler runs that code.
In Java, a class loader is a class that is used to load files in JVM. Class loaders load files from their physical file locations e.g. Filesystem, Network location, etc.
There are three main types of class loaders in Java.
- Bootstrap class loader: This is the first class loader. It loads classes from the rt.jar file.
- Extension class loader: It loads class files from JRE/lib/ext location.
- Application class loader: This class loader depends on CLASSPATH to find the location of class files. If you specify your jars in CLASSPATH, then this class loader will load them.
No, you cannot write it like this. Any method has to first specify the modifiers and then the return value. The order of modifiers can change. We can write static public void main() instead of public static void main().
Java doesn’t initialize local variables with any default value. Therefore, these variables will be null by default.
Following are the main principles of OOPs:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Languages in object-oriented programming such as Java and C++ adopt OOPS ideas such as Encapsulation, Abstraction, Polymorphism, and Inheritance, etc. Object-based programming languages adopt certain OOPS functions, but support for polymorphism and inheritance is not provided, for eg. JavaScript, VBScript, etc. Object-based programming languages allow objects to be supported and you can construct objects from the builder. Encapsulation is also assisted by their languages. There are also regarded as languages that are Prototype-oriented.
Java is an object-oriented language, in which we create and use objects. A constructor is a piece of code similar to a method. It is used to create an object and set the initial state of the object. A constructor is a special function that has the same name as class name. Without a constructor, there is no other way to create an object. By default, Java provides a default constructor for every object. If we overload a constructor then we have to implement a default constructor.
When a constructor is called in Java, it returns the object created by it. This is how new objects are created in Java.
In Java,’ this’ keyword corresponds to the object’s current case. It is helpful for discriminating between local variables and instance variables. It can be used for calling constructors or you can use it to refer to an instance. In the case of the overriding method, this is used to drop the existing class method.
In Object-Oriented Programming, inheritance is an important concept. Any objects share similar attributes and behavior. We may place the typical actions and features in a base class, which is also known as the superclass, by using Inheritance. And then this base class inherits all properties with similar actions. It is also expressed by the relationship between IS and A. Inheritance enables duplication of code, override of methods, and polymorphism.
Multiple Inheritance suggests that two or more parent classes, will inherit actions. The concern with Multiple Inheritance is that with the same form, all parent classes can have separate implementations. So they’ve got various ways to do the same thing. What implementation does the children’s class pick now? In Multiple Inheritance, this ends in complexity. This is the key explanation for Java not promoting the introduction of Multiple Inheritance. Let’s say you’ve got a TV class and another AtomBomb class. They all have the switchOn) (function, but only the TV has the switchOff) (function. If both classes are inherited from your class, then you have a dilemma. You should change all parents to switchOn), but switchOff can only switchOff TV. But in Java, you can implement several interfaces.
In Java, instead of pointers, there are references. In memory, these references point to objects. But these memory sites do not provide easy entry. The JVM is free to transfer objects into the memory of the VM. The disappearance of pointers allows Java to efficiently handle memory and garbage collection. It also gives developers the ease of not caring about memory allocation and deallocation.
In Java, the pointer equivalent is an Object reference. When we use a. (dot) it points to object reference. So JVM uses pointers but programmers only see object references. In case an object reference points to a null object, and we try to access a method or member variable on it, then we get NullPointerException.
For all the objects in a class, static variables are common. There is no need to validate the value of a static variable whenever a new object is produced. Any code that uses a static variable can be in any state. It can be inside a new object or at the level of a class. In a Java class, the scope of the static variable is also open-ended. If we want better control on scope, then variables should be generated at the object development stage. Even specifying static variables is not a reasonable idea since they go against the ideals of Object-Oriented Programming.
In Java, the main method is labeled as static, so the JVM will call it to start the application. If the main method is not static, which builder would the Java process call? As such, labeling the key static method in Java is recognized as a convention. But if we delete the static, then the uncertainty will be there. The Java process could not understand which method to call a class to start the program. In the Java process, this convention helps to define the starting code for a class program that is transmitted as an argument to the Java process.
There is a class that has static member variables at times. Any complex initialization involves these variables. The static block at this time helps to initialize complex static member variable initialization as a function. The static block is executed long before the key block is executed. We may also often substitute a static block with a static class method.
Sometimes, for a class that is not dependent on member variables of an object, there is a need to specify actions. In a static system, such conduct is caught. If there is an action that depends on an object’s member variables, then we do not label it static, it stays as an instance process. We don’t need to construct an object in order to call the static process. We only mark it by the name of the class. But for an example procedure to be called, we need to first, build/get an object. A static procedure does not access instance member variables. But both instance variables and static variables can be named by an example process.
In Java, a class can have multiple methods with the same name but different arguments. It is called Method Overloading. To implement method overloading we have to create two methods with the same name in a class and do one/more of the following:
- Different number of parameters
- The different data type of parameters
- A different sequence of the data type of parameters
Method Overloading allows two methods with the same name to differ in:
- Number of parameters
- The data type of parameters
- The sequence of the data type of parameters
No, Java does not permit a static process to be overridden. If you build the same-named static method in the subset, it is a different method, not an overridden method.
Differences between method overloading and overriding are:
- Method overloading is static polymorphism. Method overriding is runtime polymorphism.
- Method overloading occurs within the same class. Method overriding happens in two classes with hierarchy relationships.
- Parameters must be different in method overloading. Parameters must be the same in method overriding.
- Method overloading is a compile-time concept. Method overriding is a runtime concept.
The polymorphism that occurs during runtime is Runtime Polymorphism or Dynamic Polymorphism. It is not understood which method will be called at runtime in the case of the overriding method. JVM specifies the exact method that should be titled, depending on the type of entity. So, it is not known at compile time which method would be called at runtime.
In Static binding references are resolved at compile time. In Dynamic binding references are resolved at Run time.
For Example:
Person p = new Person();
p.walk(); // Java compiler resolves this binding at compile time.
public void walk(Object o){
((Person) o).walk(); // this is dynamic binding.
}
In class-level programming, abstraction exists. It helps in covering the specifics of the implementation. Encapsulation is often known as “Information Hiding”. An example of encapsulation is the private labeling of the member variables and having getter and setter for these member variables.
In Java, an abstract class has one or more abstract techniques. In the abstract class, an abstract method is only declared, but it is not implemented. In Java, an abstract class must be generalized and a child class must follow its abstract methods. Java also does not make a new instance of the Abstract type.
An Interface in Java is an abstract type blueprint of a class. It requires the strategies a class must adopt. Like a protocol, it has signatures and frequent statements of the process.
In Java, there are various interfaces that do not have any data members or methods. Such interfaces are called marker interfaces. Some examples are- serial, cloneable, remote, etc.
Annotations are the alternative to the marker interface.
Several differences between abstract class and interface are as follows:
- An abstract class may have body methods (non-abstract techniques) applied. Only abstract approaches provide an interface. The interface will provide static/default methods in an applied form from Java 8 onwards.
- An abstract class can have instance member variables. An interface cannot have instance variables. It can only have constants.
- An abstract class will have a constructor. The interface can’t provide a constructor. Another class needs to execute it.
- A class can extend only one abstract class. A class can implement more than one interface.
In Java, we cannot change the value of a final variable. Once the value is set or assigned, it cannot be changed.
To create a final method in Java, you need to add a modifier final to that method. A final method cannot be overridden by a child class.
Integer class is a wrapper for int. If an integer class is not marked final then any other class can extend it and modify the behavior of integer operations. To avoid this scenario, the integer class is marked as final.
A package is used to encapsulate a group of classes, interfaces, and sub-packages. Often, it is a hierarchical structure of storing information. It is easier to organize the related classes and sub-packages in this manner. A Package also provides access protection for classes and interfaces. A package also helps in removing naming collisions.
If the first exception allows another exception to be executed in a program, the Chained Exception is considered such a condition. Chained exceptions help to find the root cause of the exception that happens when the application is executed.
Following are the constructors that support chained exceptions in Throwable classes:
- Throwable initiate (Throwable)
- Throwable (Throwable)
- Throwable (String, Throwable)
- Throwable getCause()
Following are the differences between the JAR file and the WAR file are the following:
- JAR file stands for Java Archive file that allows us to combine many files into a single file. Whereas, WAR files stand for Web Application Archive files that store XML, java classes, and JavaServer pages, etc., for Web Application purposes.
- JAR files hold Java classes in a library. Whereas, WAR files store the files in the ‘lib’ directory of the web application.
- All the enterprise Java Bean classes and EJB deployment descriptors present in the EJB module are packed and stored in a JAR file with a .jar extension. Whereas, the WAR file contains the web modules such as Servlet classes, GIFs, HTML files, JSP files, etc., with .war extension
Through storing key-value pairs, a HashMap in Java works. HashMap uses a hash function to bring items into a collection and extract them from the collection using the hashCode and equals methods. The HashMap determines the hash value of the key on the invocation of the put) (method and then stores the pair within the array in the specific index. Where there is a key, the value of the key is changed with the new value. Some significant features of a HashMap are its ability, its load factor, and the resizing of the threshold.
- Hashtable is synchronized while HashMap is not synchronized. For the same reason, HashMap works better in non-threaded applications, because unsynchronized objects typically perform better than synchronized ones.
- Hashtable does not allow null keys or null values whereas HashMap allows one null key and any number of null values.
- One of the subclasses of HashMap is LinkedHashMap, so if we want a predictable iteration order in the event, we can easily swap out the HashMap for a LinkedHashMap. But, this would not be as easy using Hashtable.
The system class includes a static function named GC() to request the Garbage Collector to be run by JVM. Using Runtime .getRuntime() .gc() method, the Runtime class allows the application to interact with the JVM in which the application is running. Both the System.gc() and Runtime.GC() (methods help give the JVM a hint such that the JVM can start a set of garbage. It is up to the Java Virtual Machine (JVM), however, to start the garbage collector immediately or later in time.
Following things take place during the creation of an object in Java:
- Memory allocation: Memory allocation is carried out to store all the class instance variables and the object’s implementation-specific data.
- Initialization: Initialization takes place to initialize the default values of the objects.
- Constructor: For their parent classes, constructors invoke the constructors. This method continues until the java.langObject function Object() { [native code] } is called. For all objects in Java, the java.lang. Object class is the foundation class.
- Execution: Before the body of the function Object() { [native code] } is executed, all instance variables should be initialised and all initialization blocks must be executed. After that, the function Object() { [native code] }’s body is executed.
When we create an object of String in Java using a new() operator, it is created in a heap memory area and not into the String pool. But when we create a String using literal, then it gets stored in the String pool itself. The String pool exists in the PermGen area of heap memory.
For example,
String str = new String(“java”);
The above statement does not put the String object str in the String pool. We need to call the String. intern() method to put the String objects into the String pool explicitly. It is only possible when we create a String object as String literal.
For example,
String str1 = “java”;
Java automatically puts the String object into the String pool.
The java. lang package in Java includes the classes that are important for Java programming language design. The Object Class is the most critical class in this set. It also includes classes of wrappers including- Integer, Boolean, Character, etc. It offers a math class with mathematical activities.
With several answers, it is an open-ended question. In my opinion, the most important Java programming language class is the object class. In Java, it is the origin of all the classes. It offers certain strategies that are really necessary and basic.
No. JVM is loaded internally by default.
If we import the same package into a class several times, the compiler only includes it once. So neither JVM nor Compiler gives several times error/warnings on adding a package. If you have two classes of the same name, you can get a name collision when you incorrectly import the class. Internally, the JVM only loads the class once.
In Java, a Locale object represents a specific geographical, political, or cultural region. It is used for locale-sensitive operations in Java. It helps is following the local conventions of a country, a native of the region. These conventions can be for formatting the dates, money, numbers, etc.
*
* *
* * *
* * * *
* * * * *
public class Codegnan
{
public static void PyramidPattern(int n)
{
for (int i=0; i<n; i++) //outer loop for number of rows(n)
{ for (int j=n-i; j>1; j–) //inner loop for spaces
{
System.out.print(” “); //print space
}
for (int j=0; j<=i; j++ ) //inner loop for number of columns
{
System.out.print(“* “); //print star
}
System.out.println(); //ending line after each row
}
}
public static void main(String args[]) //driver function
{
int n = 5;
PyramidPattern(n);
}
}
*
* *
* * *
* * * *
* * * * *
public class Codegnan
{
public static void RTriangle(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n)
{ for(j=2*(n-i); j>=0; j–) // inner loop for spaces
{
System.out.print(” “); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print(“* “); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
RTriangle(n);
}
}
*
* *
* * *
* * * *
* * * * *
public class Codegnan
{
public static void printStars(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n)
{ for(j=2*(n-i); j>=0; j–) // inner loop for spaces
{
System.out.print(” “); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print(“* “); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
printStars(n);
}
}
*
***
*****
****************
*******
*****
***
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print(“Enter the number of rows: “);
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n – 1;
for (j = 1; j<= n; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(” “);
}
space–;
for (i = 1; i <= 2 * j – 1; i++)
{
System.out.print(“*”);
}
System.out.println(“”);
}
space = 1;
for (j = 1; j<= n – 1; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(” “);
}
space++;
for (i = 1; i<= 2 * (n – j) – 1; i++)
{
System.out.print(“*”);
}
System.out.println(“”);
}
}
}
* * * * *
* * * *
* * *
* *
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “); //takes input from user
int rows = sc.nextInt();
for (int i= rows-1; i>=0 ; i–)
{
for (int j=0; j<=i; j++)
{
System.out.print(“*” + ” “);
}
System.out.println();
}
sc.close();
}
}
* * * * *
* * * *
* * *
* *
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i= 0; i<= rows-1 ; i++)
{
for (int j=0; j<=i; j++)
{
System.out.print(” “);
}
for (int k=0; k<=rows-1-i; k++)
{
System.out.print(“*” + ” “);
}
System.out.println();
}
sc.close();
}
}
*****
****
***
**
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); // takes input
System.out.println(“Enter number of rows: “);
int rows = sc.nextInt();
for (int i= rows; i>= 1; i–)
{
for (int j=rows; j>i;j–)
{
System.out.print(” “);
}
for (int k=1;k<=i;k++)
{
System.out.print(“*”);
}
System.out.println(“”);
}
sc.close();
}
}
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i= 0; i<= rows-1 ; i++)
{
for (int j=0; j<=i; j++)
{
System.out.print(“*”+ ” “);
}
System.out.println(“”);
}
for (int i=rows-1; i>=0; i–)
{
for(int j=0; j <= i-1;j++)
{
System.out.print(“*”+ ” “);
}
System.out.println(“”);
}
sc.close();
}
}
*
**
***
*********
****
***
**
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i= 1; i<= rows ; i++)
{
for (int j=i; j <rows ;j++)
{
System.out.print(” “);
}
for (int k=1; k<=i;k++)
{
System.out.print(“*”);
}
System.out.println(“”);
}
for (int i=rows; i>=1; i–)
{
for(int j=i; j<=rows;j++)
{
System.out.print(” “);
}
for(int k=1; k<i ;k++)
{
System.out.print(“*”);
}
System.out.println(“”);
}
sc.close();
}
}
import java.util.Scanner;
public class Codegnan
{
// Java program to print alphabet A
void display(int n)
{
// Outer for loop for number of lines
for (int i = 0; i<=n; i++)
{
// Inner for loop for logic execution
for (int j = 0; j<= n / 2; j++)
{
// prints two column lines
if ((j == 0 || j == n / 2) && i != 0 ||
// print first line of alphabet
i == 0 && j != n / 2 ||
// prints middle line
i == n / 2)
System.out.print(“*”);
else
System.out.print(” “);
}
System.out.println();
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Edureka a = new Edureka(); a.display(7);
}
}
*
* *
* * *
* * * *
* * * * * *
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i=1; i<= rows ; i++)
{
for (int j = i; j < rows ; j++)
{
System.out.print(” “);
}
for (int k = 1; k <= (2*i -1) ;k++)
{ if( k==1 || i == rows || k==(2*i-1))
{
System.out.print(“*”);
}
else
{
System.out.print(” “);
}
}
System.out.println(“”);
}
sc.close();
}
}
*********
* *
* *
* *
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i=rows; i>= 1 ; i–)
{
for (int j = i; j < rows ; j++)
{
System.out.print(” “);
}
for (int k = 1; k <= (2*i -1) ;k++)
{
if( k==1 || i == rows || k==(2*i-1))
{
System.out.print(“*”);
}
else
{
System.out.print(” “);
}
}
System.out.println(“”);
}
sc.close();
}
}
*
* *
*
* *
**
* *
* *
*
* *
*
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i=1; i<= rows ; i++)
{
for (int j = rows; j > i ; j–)
{
System.out.print(” “);
}
System.out.print(“*”);
for (int k = 1; k < 2*(i -1) ;k++)
{
System.out.print(” “);
}
if( i==1) { System.out.println(“”);
}
else
{
System.out.println(“*”);
}
}
for (int i=rows-1; i>= 1 ; i–)
{
for (int j = rows; j > i ; j–)
{
System.out.print(” “);
}
System.out.print(“*”);
for (int k = 1; k < 2*(i -1) ;k++)
{
System.out.print(” “);
}
if( i==1)
System.out.println(“”);
else
System.out.println(“*”);
}
sc.close();
}
}
*
* *
* * *
* * * *
* * * * *
public class Codegnan
{
public static void printNums(int n)
{
int i, j,num;
for(i=0; i<n; i++) // outer loop for rows
{
num=1;
for(j=0; j<=i; j++) // inner loop for rows
{
// printing num with a space
System.out.print(num+ ” “);
//incrementing value of num
num++;
}
// ending line after each row
System.out.println();
}
}
public static void main(String args[])
{
int n = 5;
printNums(n);
}
}
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
int i, j, k = 1;
for (i = 1; i <= 5; i++){
for (j = 1; j< i + 1; j++){
System.out.print(k++ + ” “);
}
System.out.println();
}
}
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
int number = 1;
System.out.printf(“%” + (n – i) * 2 + “s”, “”);
for (int j = 0; j <= i; j++) {
System.out.printf(“%4d”, number);
number = number * (i – j) / (j + 1);
}
System.out.println();
}
}
}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Taking rows value from the user
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(i+” “);
}
System.out.println();
}
sc.close();
}
}
5
5 4
5 4 3
5 4 3 2
5 4 3 2 1
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Taking rows value from the user
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();for (int i = rows; i >= 1; i–)
{
for (int j = rows; j >= i; j–)
{
System.out.print(j+” “);
}
System.out.println();}sc.close();
}
}
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++)
{
for (int j = i; j >= 1; j–)
{
System.out.print(j+” “);
}
System.out.println();
}
sc.close();
}
}
10101
01010
10101
01010
10101
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++)
{
int num;
if(i%2 == 0)
{
num = 0;
for (int j = 1; j <= rows; j++)
{
System.out.print(num);
num = (num == 0)? 1 : 0;
}
}
else
{
num = 1;
for (int j = 1; j <= rows; j++)
{
System.out.print(num);
num = (num == 0)? 1 : 0;
}
}
System.out.println();
}
sc.close();
}
}
1
10
101
1010
10101
import java.util.Scanner;
public class Codegnan
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the number of rows: “);
int rows = sc.nextInt();
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
if(j%2 == 0)
{
System.out.print(0);
}
else
{
System.out.print(1);
}
}
System.out.println();
}
sc.close();
}
}
1
2 3
4 5 6
7 8 9 10
public class Floyd
{
public static void main(String[] args)
{
int rows = 4, number = 1;
for(int i = 1; i <= rows; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print(number + ” “);
++number;
}
System.out.println();
}
}
}
public class ReverseString
{
public static void main(String[] args)
{
String str = “Reversed String”;
StringBuilder str2 = new StringBuilder();
str2.append(str);
str2 = str2.reverse();
// used string builder to reverse
System.out.println(str2);
}
}
import java.util.Scanner;
public class SwapTwoNumbers
{
public static void main(String[] args)
{
int x, y, temp;
System.out.println(“Enter x and y”);
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println(“Before Swapping” + x + y);
temp = x;
x = y;
y = temp;
System.out.println(“After Swapping” + x + y);
}
}
import java.util.Scanner;
class SwapNum
{
public static void main(String args[])
{
int x, y;
System.out.println(“Enter x and y”);
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
System.out.println(“Before Swapping\nx = “+x+”\ny = “+y);
x = x + y;
y = x – y;
x = x – y;
System.out.println(“After Swapping without third variable\nx = “+x+”\ny = “+y);
}
}
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
int temp, num;
boolean isPrime = true;
Scanner in = new Scanner(System.in);
num = in.nextInt();
in.close();
for (int i = 2; i<= num/2; i++)
{
temp = num%i;
if (temp == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
System.out.println(num + “number is prime”);
else
System.out.println(num + “number is not a prime”);
}
}
import java.util.Scanner;
public class Palindrome
{
public static void main (String[] args)
{
String original, reverse = “”;
Scanner in = new Scanner(System.in);
int length;
System.out.println(“Enter the number or String”);
original = in.nextLine();
length = original.length();
for (int i =length -1; i>;=0; i–)
{
reverse = reverse + original.charAt(i);
}
System.out.println(“reverse is:” +reverse);
if(original.equals(reverse))
System.out.println(“The number is palindrome”);
else
System.out.println(“The number is not a palindrome”);
}
}
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int num, a = 0,b=0, c =1;
Scanner in = new Scanner(System.in);
System.out.println(“Enter the number of times”);
num = in.nextInt();
System.out.println(“Fibonacci Series of the number is:”);
for (int i=0; i<num; i++)
{
a = b;
b = c;
c = a+b;
System.out.println(a + “”);
//if you want to print on the same line, use print()
}
}
}
public class DuplicateCharacters
{
public static void main(String[] args)
{
String str = new String(“Sakkett”);
int count = 0;
char[] chars = str.toCharArray();
System.out.println(“Duplicate characters are:”);
for (int i=0; i<str.length();i++)
{
for(int j=i+1; j<str.length();j++)
{
if (chars[i] == chars[j])
{ System.out.println(chars[j]);
count++;
break;
}
}
}
}
}
class Armstrong
{
public static void main(String[] args)
{
int c=0,a,temp;
int n=153;//It is the number to check Armstrong
temp=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(temp==c)
System.out.println(“armstrong number”);
else
System.out.println(“Not armstrong number”);
}
}
Armstrong number is the number which is the sum of the cubes of all its units, tens and hundred digits for three-digit numbers.
153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
If you have a four-digit number, for example:
1634 = 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 + 1296 + 81 + 256 = 1634
Now, in this program, we have a temp and integers declared. We have initialized c with value 0. Then, we need to assign the integer value which we are going to check for Armstrong (in our case, let us say 153). Then we have assigned our temp variable with that number which we are going to check.
Thereafter, we have used while conditional check where the remainder is assigned to a and the number is divided by 10 and assigned to n. Now, our c variable which was set to zero initially is assigned with c+ (a*a*a). Suppose we have to evaluate a four-digit number then c should be assigned with c + (a*a*a*a).
Finally, we have put an if-else statement for conditional checking where we have compared the value contained in c against temp (which has the actual number stored at this point). If it matches, then the number is Armstrong otherwise not. (refer Q.81)
class Codegnan
{
public static void main(String[] args)
{
String str1 = “Remove the white spaces from here.”;
//Using replaceAll() function
String str2 = str1.replaceAll(“\\s”, “”);
System.out.println(str2);
}
}
}
java -cp /dev/myapp.jar:/dev/mydependency.jar com.Codegnan.MyApp
Final is a Java keyword used to indicate that either a method cannot override in a subclass, or a class cannot be extended or a field cannot be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.
A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file exists at runtime, but for some reason, the class could not be turned into a Class definition. A common cause is an exception being thrown in static initialization blocks.
The only obligation is that for any objects o1 and o2 then if o1.equals(o2) is true then o1.hashCode() == o2.hashCode() is true.
Note that this relationship goes only one way: for any o1, o2 of some class C, where none of o1 and o2 are null, then it can happen that o1.hashCode() == o2.hashCode() is true BUT o1.equals(o2) is false.
Serialization is a method that transforms an object into an array of bytes. This byte array displays the class, variant, and internal condition object. JVM can transmit/read the object over a network with this byte array.
Following are the use cases of serialization:
• Communication: used for networking of an object between two devices.
• Persistence: The object state will be stored and then recovered from the database into a database.
• Caching: Caching can be used to boost output using serialization. We might have to create an object for ten minutes, but de-serializing it will take only ten seconds.
• Cross jvm syncing: It can be used on different jvm architectures in the same way.
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse process of serialization.
No, Java does not allow marking a method as transient. The transient keyword is valid only for member variables. Member variables of an object are marked transient to indicate that they should not be serialized. During the serialization process, the transient variables are not considered part of the persistent state of an object.
Serializable is a marker interface but Externalizable is not a marker interface. When we implement a Serializable interface, the class is serialized automatically by default. We can override writeObject() and readObject() methods to control more complex object Serialization processes.
In the case of Externalizable, we use readExternal() and writeExternal() methods to give control to the class for the serialization process of a class.
A serializable interface is based on a recursive algorithm. Serializable gives you two options. One option is to provide a custom way of serialization, the other default way. In Externalizable, you have to always implement readExternal() and writeExternal() methods. A public no-arg constructor is needed while using an Externalizable interface. In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be generated automatically based on all the fields, methods of the class.
We can use Reflection to access private methods of a class from outside the class. IN Java, we use getDeclaredMethod() to get instances of a private method. Then we mark this method accessible and finally invoke it.
In the following sample code, we are accessing the private method message() of class Foo by Reflection. The file name is Foo.java
public class Foo
{
private void message()
{
System.out.println(“hello java”);
}
}FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall
{
public static void main(String[] args)throws Exception
{
Class c = Class.forName(“Foo”);
Object o= c.newInstance();
Method m =c.getDeclaredMethod(“message”, null);
m.setAccessible(true);
m.invoke(o, null);}}
The mechanism by which Java programs perform automated memory storage is Java garbage collection. Java programs are compiled into bytecodes that can be executed on a virtual Java machine or for short, a JVM. As Java programs run on the JVM, objects are generated on the heap, which is the dedicated portion of the program’s memory.
In Java, there are many ways to do that, for example:
• By nulling the reference
Employee e=new Employee();
e=null;
• By assigning a reference to another
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
• By anonymous object
new Employee();
public class TestGarbage1
{
public void finalize()
{
System.out.println(“object is garbage collected”);
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
There are no pointers in Java. Control and Utilization of Memory is achieved by JVM. Because it is automatic to assign memory after some JVM could go low on memory time. JVM must be free at the moment so that memory from objects that are unused. To aid in the method of Java offers an automatic method called reclaiming memories, called Collector of Garbage.
Two methods are supported by Java: System.gc() and Runtime.gc() to order the JVM to run the garbage collection. Programmers can directly submit requests for garbage collection when using these tools. But the JVM process will deny this request and wait for the GC to run for some time.
In Java, there are four types of references:
1) Strong Reference
2) Soft Reference
3) Weak Reference
4) Phantom Reference
The purpose of the Runtime class is to provide access to the Java Runtime system. This class provides certain important methods like:
Runtime. free memory() – This method returns the value of free memory in JVM
Runtime. max memory() – This method returns the value of maximum memory that JVM can use.
Runtime.gc() – This method can invoke garbage collection.
Java supports four types of nested classes:
1) Member inner class
2) Local inner class
3) Anonymous inner class
4) Static nested class
Java’s Inner Class is a non-static class. It is a type of nested class that is identified with a Static modifier in another class but is not eligible. A Nested class is either a Static Nested class or a non-Static Inner class that may be a class. An Inner Class shall have access, even if declared confidential, to all members of the Enclosing Class. The other members of the enclosing class cannot be accessed by a Static Nesting class.
You cannot edit or alter an Immutable Object in Java. The String is an Immutable Java class. It cannot be modified once the String object is formed. A new object is generated when we allocate a string to a new value.
Let say there are 2 String variables A and B that reference a String object “TestData”. All these variables refer to the same String literal. If one reference variable A changes the value of the String literal from “TestData” to “real data”, then it will affect the other variable as well. Due to which String is considered Immutable. In this case, if one variable A changes the value to “real data”, then a new String literal with “real data” is created and A will point to a new String literal. While B will keep pointing to “TestData”.
String s1=”HelloWorld”;
String s2=” HelloWorld “;
String s3=” HelloWorld “;
The above code creates only one object. Since there is only one String Literal “HelloWorld” created, all the references point to the same object.
String s = new String(“HelloWorld”);
The above code creates two objects. One object is created in a String constant pool and the other is created on the heap in a non-pool area.
The string is an immutable object. Its value cannot change after creation. StringBuffer is a mutable object. We can keep appending or modifying the contents of a StringBuffer in Java.
In Java, we can declare a class final to make it immutable. Following are the detailed steps to make it Immutable:
1. Add final modifier to class to prevent it from getting extended
2. Add private modifier to all the fields to prevent direct access
3. Do not provide any setter methods for member variables
4. Add final modifier to all the mutable fields to assign value only once
5. Use Deep Copy to initialize all the fields by a constructor
6. In the clone method, return a copy of the object instead of the actual object reference
In Java, Object class has toString() method. This method can be used to return the String representation of an Object. When we print an object, Java implicitly calls the toString() method. Java provides a default implementation for toString() method. But we can override this method to return the format that we want to print.
Java provides an Exception Handling mechanism to handle runtime errors that occur in JVM. There are checked exceptions in a program that we expect to occur in certain situations. The exception handling mechanism catches these checked exceptions and takes relevant actions.
Checked Exceptions extend Throwable class, but they do not extend RuntimeException or Error classes. UncheckedException extends RuntimeException class. Checked Exceptions are checked at compile time in Java. Unchecked Exceptions happen at Runtime, so they are not checked at compile time.
IOException, SQLException, etc. are examples of Checked Exceptions. NullPointerException, ArithmeticException, etc. are examples of Unchecked Exceptions.
Error, as well as Exception class, is derived from the Throwable class in Java.
Java provides a final block with a try block. This is an optional block. But finally block is always executed after the execution of the try block. A final block includes all the critical statements that must be executed whether an exception exists or not. The statements present in this block will still execute regardless of whether an exception exists in a try block or not such as closing a connection, stream, etc.
There are two main scenarios in which finally block is not executed:
- Program exits by calling system. exit() call
- A fatal error causes JVM to crash
Yes, Java allows to re-throw an exception.
1.
Definition
Throws is a keyword used in the method signature used to declare an exception that might get thrown by the function while executing the code.
The throw is a keyword that is used to throw an exception explicitly in the program inside a function or inside a block of code.
2.
Internal implementation
Internally, the throw is implemented as it is allowed to throw only a single exception at a time i.e we cannot throw multiple exceptions with a throw keyword.
The throw is a keyword that is used to throw an exception explicitly in the program inside a function or inside a block of code.
3.
Type of exception
Throws is a keyword used in the method signature used to declare an exception that might get thrown by the function while executing the code.
The throw is a keyword that is used to throw an exception explicitly in the program inside a function or inside a block of code.
4.
Syntax
Throws is a keyword used in the method signature used to declare an exception that might get thrown by the function while executing the code.
The throw is a keyword that is used to throw an exception explicitly in the program inside a function or inside a block of code.
5.
Declaration
Throws is a keyword used in the method signature used to declare an exception that might get thrown by the function while executing the code.
The throw is a keyword that is used to throw an exception explicitly in the program inside a function or inside a block of code.
In Java, an object containing a number of similar elements in a single unit is an array. You may access these few objects by means of an object from the list. A framework that provides standard architecture to build, upgrade and access various types of collections is part of the Java Collections Framework. There are common methods in the collections system that developers mostly use to operate on an item in the array.
The Thread-safe classes in Java Collections framework are:
• Stack
• Properties
• Vector
• Hashtable
• Blocking
• Queue
• ConcurrentMap
• ConcurrentNavigableMap
• Performance: JSP works very well since it designs many requests with the same code.
• Fast: As JSP has been pre-compiled, the server will easily serve pages.
•Extendable: JSP is Java-based. This allows JSP architecture to be expanded using other Java technology such as JDBC, JMS, JNDI etc.
• Build: The user interface for JSP is easier to design since the interface is similar to HTML. UI designers can create a mock data JSP, and developers can implement dynamic data at a later date.
In Extra lazy fetching, the database only gathers individual components of a set as necessary. Hibernate does not recall the whole set in this technique until it is necessary. This is a good technique for fetching large object arrays.
To package a project into a distributable format we use following command:
mvn -package
Maven is mainly a plugin execution framework. At the code of Maven all the work is done by plugins. A Maven plugin can be used for following purposes:
1. Cleaning up the code
2. Compiling the code
3. Creating a JAR file
4. Deploying the artifacts
5. Running the unit tests
6. Documenting the project
7. Generating the site of a project
8. Generating a WAR file
9. Generate a checkstyle report
Many channels and streams are required for the assembling of a product or application. Java is the most preferred medium when we speak about technology and inculcating languages. Java is used in many applications for mobile, phone, tablet, and likewise systems. A secret to success is a beginner to advanced-level professional training in Java.
Java training at Codegnan follows learn by doing concept. The practical Java training ensures that you absorb the knowledge and skills that you require to apply at the workplace. Java is your language to go if you’re looking forward to a successful programming career. You will now continue to learn and practice the requisite skills to demand in this dynamic environment. Now you can find out more about this magical language, try out our Java programming course now and find out your way into a promising future. Enquire us now!
Sairam Uppugundla is the CEO and founder of Codegnan IT Solutions. With a strong background in Computer Science and over 10 years of experience, he is committed to bridging the gap between academia and industry.
Sairam Uppugundla’s expertise spans Python, Software Development, Data Analysis, AWS, Big Data, Machine Learning, Natural Language Processing (NLP) and more.
He previously worked as a Board Of Studies Member at PB Siddhartha College of Arts and Science. With expertise in data science, he was involved in designing the Curriculum for the BSc data Science Branch. Also, he worked as a Data Science consultant for Andhra Pradesh State Skill Development Corporation (APSSDC).