Interview Questions On Class And Object In Java

Interview Questions On Class And Object In Java: Classes and Objects are fundamental concepts in Java programming, and understanding them is crucial to becoming a proficient Java developer. Classes are templates used to create objects that encapsulate data and methods to operate on that data.

Objects, however, are instances of classes that hold data and perform operations on the data as defined in the class. Classes and Objects Interview Questions in Java evaluate a candidate’s knowledge and proficiency in creating and using classes and objects in Java programming. These interview questions assess a candidate’s understanding of encapsulation, constructors, class methods, and instance methods, among other concepts related to classes and objects.

In this context, this article provides some commonly asked Classes and Objects Interview Questions in Java programming to help Java developers prepare for interviews and better understand classes and objects in Java programming.

Classed and Objects Interview Questions In Java

What is a class?
Ans: Contains both variables and methods.

  • Defines the structure and behavior of the objects that are going to be created from it.
  • Is a keyword.
  • It is similar to the ‘structure’ of the C language.
  • Represents a collection of objects.

What is an object in Java?
Ans: In Java, an object:

  • Is an instance of a class.
  • Is a fundamental unit of data representation in an object-oriented system.
  • Holds data and the code acts upon the data.

What are the properties of an object?
Ans: An object has chiefly three properties. They are:

  • State: Data members of an object and their current values put together are nothing but the state of the object. i.e., data about the object is known as the state of the object.
  • Behavior: The functional part of an object is nothing but object behavior. i.e. methods of object behavior.
  • Identity: The name of the object with which it is uniquely identified is known as the “identity of an object.”

How do you create a class?
Ans: The syntax to create a class is:

class classname
{
	accessibility mode datatype variblename1; //default
	accessibility mode is: default in Java
	accessibility mode datatype variblename2;
	accessibility mode datatype variblename3;
	.............
	...............
	accessibility mode return type methodname1(argument list)
	{
		// body

	}
	accessibility mode return type methodname2(argument list)
	{
		// body
	}
	accessibility mode return type methodname3(argument list)
	{
		// body
	}
}

Example:

class FirstProgram
{
	int number;
	byte num;
	char ch;
	public void display()
	{
		System.out.println(number);
		System.out.println(num);
		System.out.println(ch);
	}
}

How to create an object in Java?
Ans: We can create an object of a class using the following syntax:

ClassName reference name = new ConstructorName();

Where:

  • ClassName: it is the name of the class for which the object is to be created
  • reference name: it is a class-type variable pointing to the object of a class.
  • new: It is a dynamic memory allocation operator in Java used to allocate the memory for the class members and methods
  • ConstructorName: It is a special method having the same name as the class.
    Example: Object creation for the above class:
FirstProgram firstreference = new FirstProgram();

Note: In Java, all statements must be enclosed in a class.

How to access class data members and methods in Java?

Ans: In order to access the class members, we have to create a new class (not mandatory, but advisable). In the new class, define the public static void main() method and create an object of that class. Using the dot ‘.’(The member accessing operator) we can access both data and methods of an Object or a Class

For example:

class ClassDemo
{
	int number;
	byte num;
	char ch;
	public void display()
	{
		System.out.println(number);
		System.out.println(num);
		System.out.println(ch);
	}
}
class RunProgram
{
	public static void main(String args[]) 
	{
		ClassDemo firstreference = new ClassDemo ();
		firstreference.display();
	}
}

What are the steps involved in the object creation in Java?
Ans: The steps involved in the object creation process are:

  • Step -1: A new operator constructs the Java class object.
  • Step -2: JVM provides the default values to the instance variables of the object.
  • Step -3: JVM calls a special method called the constructor on the object.
  • Step -4: A new operator binds the object to the reference variable, returning the object address to be stored in a specialized pointer known as “reference.”

What are the instance variables in Java?
Ans: Instance variables in Java are the non-static data members of a class. They represent the structure of the object and contribute to its size. If the object does not exist, then the instance variables do not exist physically.
For each instance of a class, one separate copy of the variables is created; hence, we call them instance variables.

What are the instance methods in Java?
Ans: A class’s non-static methods are known as “instance methods.” These methods can be called on instances (objects), hence the name. One separate copy of an instance method is not created for each instance of a class.

What is the default value in Java?
Ans: Default values are the values provided by the JVM when no value is supplied to the class instance variables; by default, the JVM provides the initial values to them.

What are the default values provided by the JVM to the instance variables?
Ans: JVM provides the following default values to all primitive type variables:

  • All integral types (int, short, long, byte) are: zero (0)
  • All decimal types (float, double) are: 0.0
  • For char type, it is a null character: \u0000 (where u stands for Unicode)
  • For the Boolean type, it is: a false

What are the local variables?
Ans: The local variables are those declared in the class method. They should be initialized before being accessed. The scope of these variables is confined to their respective methods.

Does JVM provide any default values to the local variables?
Ans: No. JVM does not provide any default values to local variables.

How does JVM give default values for the user-defined variables?
Ans: For class-scoped user-defined variables, JVM provides null as the default value.

How can you classify variables based on the data types?

Ans: Variables are of two types based on its type:

  • Primitive type
  • A user-defined type (user-defined types are not objects in Java, unlike C++).

Example:

class VariableTypes
{
	int num; //primitive instance variable
	Integer number; //user-defined instance variable
	void method()
	{
		Float real; //user-defined local variable
		int b; //primitive local variable
		String name; //user-defined local variable
	}
}

Can a class be declared as static?
Ans: No. Classes cannot be declared static. Only methods, variables, and blocks of code can be declared static.

When will you define a method as static?
Ans: A method is defined as static when it needs to be accessed even before the class object is created.

What are the restrictions imposed on a static method or a static block of code?
Ans: A static method should not refer to instance variables without creating an instance and cannot use the “this” operator to refer to the instance.

I want to print “Hello” even before main() is executed. How will you achieve that?
Ans: Print the statement inside a static block of code. Static blocks are executed when the class is loaded into memory and even before an object is created. Hence, they will be executed before the main() method, and they will be executed only once.

What is the importance of static variables?
Ans: The static variables are the class-level variables, where all the class objects refer to the same variable. If one object changes the value, then the change is reflected in all the objects.

Can we declare a static variable inside a method?
Ans: The static variables are class-level variables, and they can’t be declared inside a method. If declared, the class will not be compiled.

What are the local, member, and class variables?
Ans: The variables declared within a method are called “local” variables. The variables declared within the class, i.e., not within any methods, are called “member” variables (or global variables). Similarly, the variables declared within the class, not within any methods and defined as “static,” are called class variables.

What is the difference between a static and a non-static inner class?
Ans: A non-static inner class may have object instances that are associated with the instances of the class’s outer class. A static inner class does not have any object instances.

What is an object’s lock, and which objects have locks?
Ans: An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.

Which non-Unicode characters may be used as the first character of an identifier?
Ans: ‘$’ and ‘_’ may appear as the first character of an identifier.

Can an anonymous class be declared as implementing an interface and extending a class?
Ans: An anonymous class may implement an interface or extend a superclass, but it may not be declared to do both.

What modifiers can be used with a local inner class?
Ans: ‘final’ or ‘abstract’ can be used with a local inner class.

When does the compiler supply a default constructor for a class?
Ans: If no other constructors are provided, the compiler supplies a default constructor for the class.

What are the legal operands of the instance of operator?
Ans: The left operand is an object reference or null value, and the right operand is a class, interface, or array type.

Are the values ‘true’ and ‘false’ can be classified as Java keywords?
Ans: No.

What happens when you add a double value to a String?
Ans: When you add a double value to a string, it results in a string object.

What is the difference between the inner class and the nested class?
Ans: When a class is defined within the scope of another class, then it becomes an inner class. If the access modifier of the inner class is static, then it becomes a nested class.

What is the difference between a constructor and a method?
Ans: A constructor is a member function of a class used to create objects of that class. It has the same name as the class itself, no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is the purpose of garbage collection in Java, and when is it used?
Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

What is static in Java?
Ans: Static means one per class, not one for each object, no matter how many instances of a class might exist. This means that you can use them without creating an instance of a class. The static methods are implicitly final because
overriding is done based on the type of the object, and static methods are attached to a class, not to an object.

A static method in a superclass can be shadowed by another static method in a subclass as long as the original method is not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.

What if I do not provide the String array as the argument to the method?
Ans: The program gets compiled, but it also throws a runtime error: “NoSuchMethodError.”

What is the first argument of the String array in the main() method?
Ans: The String array is empty. It does not have any element. This is unlike C/C++, where the first element is the program name by default.

If I do not provide any arguments on the command line, will the String array of the main() method be empty or null?
Ans: It is empty. But not null.

How many objects are created in the following piece of code?
Ans: MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3, because the reference c2 is only declared but not initialized.

Can a public class MyClass be defined in a source file named YourClass.java?
Ans: No. If the source file contains a public class, the name must be the same as the public class name itself, with a ‘.java’ extension.

What are the wrapped classes?
Ans: The Wrapped classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory?
Ans: Garbage collection does not guarantee that a program will not run out of memory. Programs can use memory resources faster than they are garbage collected, and they can also create objects that are not subject to garbage collection.

Can an object’s finalize() method be invoked by the garbage collector while it is reachable?
Ans: An object finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object finalize() method may be invoked by other objects.

For which value a variable of the String type gets initialized automatically?
Ans: The default value of a String type is null.

Can a Byte object be cast to a double value?
Ans: No. A Byte object cannot be cast to a primitive value.

If a class is declared without any access modifiers, where may the class be accessed?
Ans: A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

What is a SimpleTimeZone class?
Ans: The SimpleTimeZone class provides support for the Gregorian calendar.

What modifiers can be used with a local inner class?
Ans: A local inner class may be final or abstract.

What is the difference between static and non-static variables?
Ans: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

What classes of exceptions may be thrown by a throw statement?
Ans: A throw statement may throw any expression that may be assigned to the Throwable type.

What are the Object and Class classes used for?
Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class represents the classes and interfaces that are loaded by a Java program.

Can an unreachable object become reachable again?
Ans: An unreachable object may become reachable again. This can happen when the objects finalize() method is invoked, and the object performs an operation that makes it accessible to reachable objects.

When is an object subject to garbage collection?
Ans: An object is subject to garbage collection when it becomes unreachable to the program that uses it.

What are Class, Constructor, and Primitive data types?
Ans: A class is a template for multiple objects with similar features, a blueprint for objects. It defines a type of object according to the data it can hold and the operations it can perform. A constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are eight types: byte, short, int, long, float, double, boolean, and char.

What is an Object, and how do you allocate memory to it?
Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using a new operator, memory is allocated to it.

What is the difference between a constructor and a method?
Ans: The constructor will be automatically invoked when an object is created, whereas the method has to be called explicitly.

What are the methods, and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes.

A method definition has four parts: the name of the method, the type of object or primitive type it returns, a list of parameters, and the body of the method. A method’s signature is a combination of the first three parts mentioned above.

What is Garbage Collection, and how do you call it explicitly?
Ans: When an object is no longer referred to by any variable, Java automatically reclaims the memory used by that object. This is known as garbage collection. The System.gc() method may be used to call it explicitly.

What is a finalize() method?
Ans: The finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.

What are the inner class and anonymous class?
Ans:
Inner Class: Classes defined in other classes, including those defined in methods, are called inner classes. An inner class can have any accessibility, including private.

Anonymous Class: An anonymous class is a class defined inside a method without a name is instantiated and declared in the same place and cannot have explicit constructors.

Can you have an inner class inside a method, and what variables can you access?
Ans: Yes, we can have an inner class inside a method and access the final variables.

Ref: article

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment