50 Best Java Basic Interview Questions for Freshers - onlyxcodes

Sunday 12 March 2023

50 Best Java Basic Interview Questions for Freshers

Are you a fresh graduate trying to get ready for a java interview? Use this extensive list of java basic interview questions and answers to get ready. With the help of these ideas, you'll be able to answer queries with assurance and stand out in your interview.


We have discussed the basic 50 basic core Java interview questions and answers in this tutorial for freshmen candidates.


java basic interview questions for freshers

1. What is Java?


In 1982, James Gosling introduced the high-level programming language known as Java. It may be used to build larger applications and is based on the concepts of object-oriented programming.


2. What is object-oriented programming?


A programming paradigm known as object-oriented programming (OOP) uses objects, which are instances of classes, to represent data and behavior. Encapsulation, inheritance, and polymorphism are the main features of OOP.


3. Is Java Pure Object Oriented Language?


Java does not follow the accepted definition of an object-oriented language because it allows the usage of primitive datatypes like int, byte, and long, among others, which are not objects.


4. What features does Java have?


Java has several features, including:


Object-oriented programming


Platform independence


Garbage collection


Multithreading


Exception handling


Security


5. What are Java's primary features?


Platform independence, object-oriented programming, automatic memory management, and security are some of Java's essential features.


6. What is the difference between JDK, JRE, and JVM?


JDK, or Java Development Kit, is a collection of tools for creating, testing, and troubleshooting Java programs.


JRE, or Java Runtime Environment, is a collection of libraries and the JVM that are required to run Java programs.


JVM, short for Java Virtual Machine, is the mechanism responsible for running Java code.


7. What is the difference between JDK and JRE?


JDK, or Java Development Kit, is a collection of tools for creating, testing, and maintaining Java programs. JRE, or the Java Runtime Environment, is a collection of only the equipment required to run Java programs.


8. What are the differences between C++ and Java?


JavaC++
Java supports both interpreters and compilers.only assists the compiler.
System-controlled memory managementThe programmer has access to memory management.
not compatible with multiple inheritancesAllow multiple inheritances.
provides limited assistance for the pointers.supports the pointers
shows a strong preference for automatic.The user must take manual action.
collection of the garbage but does not support destructors.Using the new and delete keywords in management.

9. What is a class?


A class is a template for building objects that specifies the properties and methods the objects will have.


10. What is an object in Java?


In Java, an object is an instance of a class. It has a state and behavior that the class defines. The "new" keyword is used to make objects from classes.


11. What is the difference between a class and an object?


An object is an instance of a class, whereas a class serves as a template for building objects.


12. Explain public static void main(String args[]) in Java.


Any Java program's entry point is called the main(). The syntax is always public static void main (String[] args).


public: Who can access this method is determined by the access modifier public. Any Class will be able to access this Method because it is public.


static: Java uses a keyword to indicate that it's class-based. Java makes main() static so that it can be accessed without having to create a Class object.


Main() is called by the JVM before any objects are defined, and only static methods can be directly invoked via the class, so if the main is not made static, the compiler will throw an error.


void:  It is the method's return type. The method that returns nothing is defined as void.


main: For an application with a specific identity alone, the JVM searches the name of the method as a starting point. The method's primary execution takes place there.


String args[]: That is the argument the main method received.


13. Why is the main method static in Java?


Java's main method is static since an object is not required to call static methods. The non-static main() method requires the Java Virtual Machine (JVM) to generate an object, which requires additional memory allocation.


14. What are the different types of variables in Java?


In Java, there are primarily three different kinds of variables available. These include:


1) Static Variables


2) Local Variables


3) Instance Variables


1) Static Variables: Static variables are those that have the static keyword in their declaration. Local variables cannot be static variables, as memory is only allocated once for them.


2) Local Variables: Local variables are variables that are declared inside the method body of the class. The static keyword cannot be used to declare a local variable.


3) Instance Variables: 


The instance variable is the name given to the variable that is declared inside the class but outside the method body. As its value is instance-specific and cannot be shared with other instances, this variable cannot be declared static.


 class Test
{  
	int number=10; //instance variable  

	static String name="england"; //static variable  

	public static void method(String args[])
	{  
		int a=50; //local variable  
	}  
}

15. What is Typecasting and its type?


In Java, typecasting is an explicit programming technique used to change one data type into another.


Widening (automatically) - changing a lower data type's size to a larger data type.


byte -> short -> char -> int -> long -> float -> double


Narrowing (manually) - altering the size of a larger type to a smaller type.


double -> float -> long -> int -> char -> short -> byte


16. What are the data types in Java?


The values and sizes that can be stored in variables are determined by the datatypes used in Java. The two main categories of data types are as follows:


1) Primitive Data Types


2) Non-primitive Data Types


17. What are primitive data types?


Primitive data types are the main building blocks of data handling in Java. The most fundamental data types offered by Java are those mentioned above. Integer, char, byte, float, double, long, short, and boolean are examples of primitive data types.


18. What are non-primitive data types?


The non-primitive data types are distinct from the primitive data types and include things like Strings, arrays, and structures.


19. Types of operators in Java?


Java offers eight different kinds of operators, and they are as follows:


1) Arithmetic operators


2) Assignment operators


3) Logical operators


4) Relational operators


5) Bitwise operators


6) Unary operators


7) Ternary operators


8) Shift operators


20. Define the JIT compiler in Java?


The JRE element known as Just In Time Compiler is utilized to translate the method's bytecodes into native machine code. JVM calls this method's compiled code direct without ever interpreting it.


21. What is a constructor?


When an object is formed, a constructor, a specific method, is invoked. The attributes of the object are initialized using it.


It needs to be given the same name as the class.


Two types of constructors arise:


Default Constructor: A default constructor in Java does not accept any inputs. In other words, default constructors are the no-argument constructors that are automatically produced if the user does not define another constructor.


Its primary function is to set the instance variables' default values. It is mostly employed for the manufacturing of objects. 


Parameterized Constructor: In Java, a constructor that may initialize instance variables with supplied values is known as a parameterized constructor.


Alternatively put, constructors that accept parameters are referred to as parameterized constructors.


22. What is Inheritance?


One class can obtain the attributes and methods of another class through inheritance. The class that is inheriting is known as the subclass, and the class from which it is inheriting is known as the superclass.


23. Types of inheritance in Java?


Java allows the following four types of inheritance:


Single Inheritance: With single inheritance, only one parent and one child class arise, and each class inherits the properties of the others.


Multilevel Inheritance: Multilevel inheritance is the process of deriving a class from another class that itself was inherited from another class, i.e., a class with several parent classes but at various levels.


Hierarchical Inheritance: A class is said to be hierarchical when it has more than one child class, or, to put it another way when more than one child class shares the same parent class.


Hybrid Inheritance: Combining two or more different inheritance types is known as hybrid inheritance.


24. What is Polymorphism?


The capacity of an object to adopt various forms is known as polymorphism. This is done in Java using method overloading and overriding.


25. What is an Interface?


An interface is a group of abstract methods that spells out the terms of a class's implementation agreement. Although classes can inherit from many classes, they can only implement one interface.


26. What are access modifiers in Java?


Access modifiers are special keywords in Java that are used to control a class's access to its constructor, data members, and methods. Java offers four different kinds of access modifiers:


Default


Private


Protected


Public


27. What is the difference between private, protected, and public access modifiers in Java?


private: The private access modifier restricts a class member's access to only other members of that class.


protected: Access to members of the same class and its subclasses is permitted by the protected access modifier.


public: A class's members can be accessed from anywhere in the program due to the public access modifier.


28. What is the difference between double and float variables in Java?


In Java, double requires 8 bytes of memory while float requires 4 bytes. While Double is a decimal number with double accuracy, Float is a floating point number with single accuracy.


29. What are Loops in Java? What are the three types of loops?


Programmers use looping to repeatedly run a statement or a collection of statements. In Java, there are three distinct loop types:


1) for loop


2) while loop


3) do while loop


30. What is a package in Java?


In Java, a package is a grouping of associated classes and interfaces. The code is made more manageable and organized as a result.


31. Advantages of Package.


Packages assist in preventing name conflicts.


They make access control to the code easy.


Moreover, hidden classes that are only utilized within the package and invisible to outer classes can be found in packages.


Helps to establish a correct hierarchical structure that makes it simpler to find related classes.


32. What is the difference between method overloading and method overriding?


Overloading occurs when there are two methods with the same name and properties but different parameters.


Overriding occurs when there are two methods with the same name and properties but one is in the child class and the other is in the parent class.


33. What is the Difference Between the equals() method and the == operator? 


Whereas the == operator compares the references of two string objects in Java, the equals() method compares the contents of two string objects and returns true if they have the same value.


The two string objects in the following example both have the same values, hence the equals() function returns true. Even so, since both string objects are references to distinct objects, the == operator returns false:


 public class Test 
{
    public static void main(String args[]) {

        String str1 = new String("Canada");

        String str2 = new String("Canada");

        if (str1.equals(str2))
        { 
			// this condition is true
            System.out.println("str1 and str2 are equal in terms of values");

        }

        if (str1 == str2) 
		{
            //This condition is true
            System.out.println("Both strings are referencing same object");

        } 
		else
        {
            // This condition is NOT true
            System.out.println("Both strings are referencing different objects");
        }
    }
}

34. Differentiate between StringBuffer and StringBuilder in Java.


StringBufferStringBuilder
Methods on the StringBuffer are synchronized.StringBuilder is non-synchronization.
The storage space is vast and flexible.Modifiable heap storage is available.
Thread-safe is StringBuffer.Since StringBuilder is not thread-safe, it is quick.
Performance is quite weak.The performance moves rather quickly.

35. What is Encapsulation in Java?


Encapsulation is the process of hiding an object's interior workings but still allowing for public interaction. This ensures the object is utilized properly and prevents unintended state changes.


36. What is an abstract class in Java?


An abstract class has the keyword abstract in its declaration. Both abstract and non-abstract approaches are possible.


Public, private, protected, constants, and default variables are all possible in this class.


Both its scope and methodology need to be put into practice. You can't instantiate it.


A class must be marked abstract if it contains at least one abstract method.


37. What is the Difference Between an Interface and an Abstract class?


An interface can only declare public static methods with no concrete implementation. In contrast, an abstract class can contain members with any access specifier (public, private, etc.) with or without a concrete implementation. This is the main distinction between an abstract class and an interface.


A class that implements an interface is required to implement every method of the interface, whereas a class that inherits from an abstract class is not required to implement every method of its superclass. This is another significant distinction between the use of abstract classes and interfaces.


A class may extend one or more abstract classes, but it may implement any number of interfaces.


38. What is the difference between the "this" and "super" keywords in Java?


In Java, the constructor is called using the special keywords this and super.


thissuper
A class's current instance is represented by this.The base class's current instance is represented by super.
used to invoke the same class's default constructor.used to invoke the base class's default constructor.
used to access the current class's methods.used to access base class methods.
to indicate the active class instance.used to indicate the instance of the superclass.
A block's opening line is required.A block's opening line is required.

39. What is an Array in Java?


A collection of related data types is an array. It cannot contain several types of data. It can store both object references and primitive types (such as int, float, and double).


It is a fixed thing and has a defined length.


Arrays are not built on the stack but rather on the heap memory.


Accessing an incorrect array index will result in an exception.


40. How to declare an Array in java?


Java allows you to declare an array in the following ways:


dataType[] arrayVariableName = new dataType[arraySize];


You can declare an int array, for instance, as follows:


int[] arr = new int[10]


41. What is the final keyword in Java?


Java has a unique keyword called final that is employed as a non-access modifier. A final variable may be applied in a variety of situations, including:


final variable:- After a variable's value has been assigned while using the final keyword, it cannot be modified. If the final variable has not yet been given a value, one can do it by using only the class constructor.


final method:- When a method is marked as final, the inheriting class cannot override it.


final class:- When a class in Java is marked as final, it can extend other classes but cannot be extended by any subclass classes.


42. What is the difference between an array and an array list?


ArrayArrayList
Cannot include values of many data typesCan include values of many data kinds.
At the time of declaration, the size must be specified.Dynamically changing size.
To add data, the index must be specified.The index need not be specified.
There are no type parameters for arrays.Arraylists belong to the only objects may be contained in ArrayList
Objects and primitive data types can both be contained in arrays.basic data types are not permitted.

43. What is a Thread in Java?


In a program, a thread is a quick procedure that operates alongside other threads. It permits parallelism and can enhance a program's performance.


44. Explain the various thread states or thread life cycles.


Java threads can be in one of the different states described below.


Ready: A thread is in the Ready state when it is first formed.


Running: A running thread is currently being used.


Waiting: A thread in a waiting state is waiting for another thread to release specific resources.


Dead: A thread is in a dead state if it stopped responding after being executed.


45. What is Multi-Threading?


The programming term for running numerous tasks concurrently within a single program is multi-threading. The same process stack is shared by all active threads. Any program's performance can be improved due to it.


46. Why is synchronization required in the thread? 


Java enables the execution of numerous threads. They might be using the same object or variable. Synchronization makes it possible to run threads sequentially.


It is crucial because it aids in the synchronized execution of all running concurrent threads. It avoids memory consistency mistakes brought on by shared memory access.


47. What is the difference between a local variable and an instance variable?


A local variable in Java normally only has local scope and is used within a method, constructor, or block. As a result, a block is the only place where this variable can be utilized. The fact that other methods in the class won't even be aware of a local variable is its finest advantage.


Example:


 if(i > 50)
{
	String test = "Canada";
}

In comparison, a Java instance variable is a variable that is connected to the object itself. These variables are defined outside of a method but inside of a class.


Each member of that class who uses the variable will make a new instance of it. Any modifications made to the variable will only affect that specific instance and won't affect any other instances of that class.


Example:


class Test
{
	public String studentName;
	public int studentAge;
}

48. Explain the types of Exceptions in Java?


In Java programming, there are two sorts of exceptions:


Built-in Exception: These exceptions are those included in the Java language standard package. They are employed for particular errors with the exceptions listed below:


AriththmeticException:- thrown for mistakes with the mathematical operations. 


IOException:- thrown when input-output operations go wrong. 


FileNotFourndException:- triggered when the file cannot be accessed or is missing. 


ClassNotFoundException:- When the compiler is unable to locate the class definition, an exception is raised.


InterruptedException:- invoked whenever a thread is cut off.


NoSuchFieldException:- called whenever a class or function lacks a variable declaration. 


NullPointerException:- thrown when a null object's variable or values are referenced. 


RuntimeException:- notified of the runtime errors that happened. Doing an invalid type conversion, for instance. 


IndexOutOfBoundsException:- triggered whenever an array, string, or vector's index is invalid or outside of its acceptable range.


User-defined Exceptions: Exceptions containing unique messages are known as user-defined exceptions. Sometimes the built-in Exception may not be able to define the error, they are utilized.


49. What are different exception-handling keywords in Java?


There are three exception-handling keywords in Java:


try: The try block can contain any code segment that might result in an error or other unusual. The try block will forward the exception to the catch block in the event of any errors.


catch: The exception produced by the try block is handled by catch. After the attempted block, it comes.


finally:  The finally keyword makes sure that the segments run even if the try & catch block encounters errors or exceptions. After the try block or after both the try and the catch block, the last keyword appears.


50. Difference between the throw and throws keywords?


The following are the main distinctions between the keywords throw and throws:


throwthrows
In a program or a block of code, the throw keyword is used to explicitly throw an exception.The throws keyword is used to specify an exception that might happen during the compilation or execution of a program in the method code.
Will just throw unchecked exceptions.both checked and unchecked exceptions may be utilized with this.
Followed by an instance variable and the throw keyword.The exception class names are followed by the keyword throws.
Only one exception may be thrown using the keyword throw.Throwing numerous exceptions is possible with throws.

No comments:

Post a Comment

Post Bottom Ad