Basic Java Interview Questions in Java

List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Basic Java Interview Questions in Java

Question 1.
What are OOPs?
Answer:
Object-oriented programming organizes a program around its data, i.e. objects and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Question 2.
What is the difference between Procedural and OOPs?
Answer:
a) In a procedural program, programming logic follows certain procedures and the instructions are executed one after another.
In the OOPs program, a unit of the program is an object, which is nothing but a combination of data and code.
b) In procedural programs, data is exposed to the whole program whereas in OOPs programs, it is accessible within the object and which in turn assures the security of the code.

Question 3.
What is an Object?
Answer:
An object is an entity with certain attributes or qualities and behaviors, for a simple example, a ‘Laptop’ is an object which has certain attributes like weight, color, screen size, manufacturer, etc. It has various behaviors or activities to do or act upon, like play games, browse the Internet, write/check emails, watch movies, listen to music, etc.

Question 4.
What is a Class?
Answer:
A class is a collection of attributes and behaviors of objects with certain similarities and an instance of a class is represented by an object. A simple example of a class is a ‘Car’ which represents a variety of Car objects with different attribute values and behaviors. The different objects of the ‘Car’ class can be, for example, A Mercedes Car, a Toyota Car, two different objects from the same class but different attributes and different behaviors too.

Question 5.
What is OOAD?
Answer:
Object-Oriented Analysis and Design (OOAD) is a methodology to analyze, design, and develop applications using objects and their relations and message-based communication to each other. Everything in OOAD is visualized in terms of objects and classes. OOAD introduced a paradigm shift from thinking and programming procedurally to objects oriented programming. This approach helps in designing complex real-time systems with ease. The features like Data Abstraction and Encapsulation, Inheritance, and Polymorphism form fundamentals of object-oriented programming.
Advantages:

  • Enhanced Reusability
  • Modular approach towards problem-solving which will be
  • Better Maintainability Better Performance if the system is designed cautiously using OOAD concepts

Question 6.
What is Data Abstraction?
Answer:
Data Abstraction is the extraction of essential information for a particular purpose and ignoring the remainder of the information, e.g. a car consists of an engine, air filters, a carburetor, a gearbox, steering, a fuel tank, tires, etc. A driver of a car need not to be bothered about several finer points of the car, he/she should know what it requires to drive a car. Take another user, a car mechanic; he will require a different set of information in order to repair the car.

Question 7.
What is Data Encapsulation?
Answer:
Data Encapsulation is wrapping information (attributes and behaviors) within an object. A suitable example is a class as it wraps methods and data within itself. The attributes of a class correspond to its data members while behavior corresponds to member methods of the class.

Question 8.
What is the difference between Data Abstraction and Information Hiding?
Answer:
Data Abstraction is often confused with information hiding while they altogether are two different technical concepts.

Question 9.
What are Encapsulation, Inheritance, and Polymorphism?
Answer:
Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safes from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

Question 10.
What is the difference between Assignment and Initialization?
Answer:
Assignment can be done as many times as desired whereas initialization can be done only once.

Question 11.
What are Class, Constructor, and Primitive data types?
Answer:
Class is a template for multiple objects with similar features and it is a blueprint for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created.
Primitive data types are 8 types and they are:

  1. byte
  2. short
  3. int
  4. long
  5. float
  6. double
  7. boolean
  8. char

Question 12.
What is an Object and how do you allocate memory to it?
Answer:
The 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.

Question 13.
What are the supported platforms by Java Programming Language?
Answer:
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

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

Question 15.
What is the difference between object-oriented programming language and object-based programming language?
Answer:
Object-based programming languages follow all the features of OOPs except Inheritance. Examples of object-based programming languages are JavaScript, VBScript, etc.

Question 16.
What are methods and how are they defined?
Answer:
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. Method definition has four parts. They are the name of the method; type of object or primitive type the method 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.

Question 17.
What is the use of bin and lib in JDK?
Answer:
Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

Question 18.
What is casting?
Answer:
Casting is used to convert the value of one type to another.

Question 19.
How many ways can an argument be passed to a subroutine and explain them?
Answer:
An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

Question 20.
What is the difference between an argument and a parameter?
Answer:
While defining the method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

Question 21.
What is UNICODE?
Answer:
Unicode is used for the internal representation of characters and strings and it uses 16 bits to represent each other.

Question 22.
What are method overloading and method overriding?
Answer:
Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.
Method overriding: When a method in a class having the same method name with the same arguments is said to be method overriding.

Question 23.
What is the difference between overloading and overriding?
Answer:
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is the relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding, the subclass method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have the same signature.

Question 24.
What is Inheritance and what are the different types of it?
Answer:
Inheritance is a mechanism by which a specific object acquires attributes and behaviors of more general objects. In OOP terminology, Inheritance is the mechanism that allows a Class ‘A’ to inherit properties of Class ‘B’ and we say ‘A inherits from B’ or in other words B is a ‘Superclass’/Tarent class’ while A is a ‘Subclass’/’Child class’. A typical example of inheritance is a family tree which consists of son, father, grandfather, great grandfather, and so on. The different types of Inheritance are:

  1. Single Inheritance
  2. Multiple Inheritances
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

Question 25.
Why Java uses a singly rooted hierarchy?
Answer:
All objects in Java are inherited from the same base class called ‘Object’. In Java, all objects have a common interface to implement and it makes the implementation of Garbage collector a lot easier in Java. The necessary implementation is provided in the base class, and the garbage collector can then send the necessary messages to every object in the system. Without a singly rooted hierarchy, it would have been difficult to implement a garbage collection feature.

It enables a lot of ease to programmers not to be bothered about memory management while developing. It greatly simplifies argument passing amongst objects too on the heap. As Java started from scratch and has no backward compatibility issues with any existing language, it was a logical choice to use the singly-rooted hierarchy in common with most other object-oriented programming languages.

Question 26.
Why does Java not support Multiple Inheritance?
Answer:
Java does not support multiple inheritances at least not the way it does in the case of C++. In the designer’s view, Multiple Inheritance poses many more problems and confusion than it solves. E.g. famous Diamond problem. The diamond problem is an ambiguity that can occur when a class multiply inherits from two classes that both descend from a common superclass. In such scenarios assuming if Java implements multiple inheritances then it would be difficult to know which method is to be called by an inheriting class object of two of the superclasses.

In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritances of the interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use.

Question 27.
Why is Java not 100% pure OOP language?
Answer:
Java takes inspiration from C and C++. The native data types like ‘char’, ‘int’, ‘float’, ‘double’ are straight pick from C, which is not an Object-Oriented Language. Reasonably enough, Java is not a 100% pure Object-Oriented Language.

Question 28.
What is Early Binding?
Answer:
The assignment of types to variables and expressions at compilation time is known as ‘Early Binding’, it is also called ‘static binding’ and ‘static typing’.

Question 29.
What is Polymorphism/Late Binding?
Answer:
When an object is sent a message then it does not know itself what type it is, the runtime environment will decide about function calling over an object. This feature of connecting an object with its associated message at runtime is known as Polymorphism or Late binding or Dynamic binding.

Question 30.
What is meant by Inheritance and what are its advantages?
Answer:
Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are the reusability of code and accessibility of variables and methods of the superclass by subclasses.

Question 31.
What is the difference between this( ) and super( )?
Answer:
this( ) can be used to invoke a constructor of the same class whereas super( ) can be used to invoke a superclass constructor.

Question 32.
What is the difference between superclass and subclass?
Answer:
A superclass is a class that is inherited whereas a subclass is a class that does the inheriting.

Question 33.
What modifiers may be used with top-level classes?
Answer:
public, abstract and final can be used for top-level classes.

Question 34.
What are an interface and its use?
Answer:
The interface is similar to a class that may contain the method’s signature only but not bodies and it is a formal set of methods and constant declarations that must be defined by the class that implements it.
Interfaces are useful for:

a) Declaring methods that one or more classes are expected to implement
b) Capturing similarities between unrelated classes without forcing a class relationship.
c) Determining an object’s programming interface without revealing the actual body, of the class.

Question 35.
What is an abstract class?
Answer:
An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

Question 36.
Difference between Abstraction and Encapsulation.
Answer:
Abstraction is removing some distinctions between objects, so as to show their commonalities.
Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.

Question 37.
Why are there no global variables in Java?
Answer:
Global variables are considered bad form for a variety of reasons:
• Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables).

• State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up the global states into more easily understood collections of local states.

• When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once.

• For these reasons, Java decided to ban global variables.

Question 38.
what does it mean that a class or member is final?
Answer:
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass.

Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example,
public final double c = 2.998;
It’s also possible to make a static field final to get the effect of C++’s const statement
or some uses of C’s #define, e.g.
public static final double c = 2.998;

Question 39.
What does it mean that a method or class is abstract?
Answer:
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has nobody. For example,

public abstract float price( );

Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do.
Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

Question 40.
What is the difference between Integer and int?
Answer:
a) Integer is a class defined in java.lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other.
b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

Question 41.
What is a cloneable interface and how many methods does it contain?
Answer:
It is not having any method because it is a TAGGED or MARKER interface.

Question 42.
What is the difference between abstract class and interface?
Answer:
a) All the methods declared inside an interface are abstract whereas abstract classes must have at least one abstract method and others may be concrete or abstract.
b) In abstract class, keyword abstract must be used for the methods whereas interface we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can’t have subclasses.

Question 43.
Can you have an inner class inside a method and what variables can you access?
Answer:
Yes, we can have an inner class inside a method and final variables can be accessed.

Question 44.
What are wrapper classes?
Answer:
Wrapper classes are classes that allow primitive types to be accessed as objects.

Question 45.
What is the difference between C++ & Java?
Answer:
Both are Object Oriented. But Java does not support multiple inheritances; this is achieved in Java Through interfaces. In C++ there is no memory management; the developer has to allocate and free the Memory resources deliberately which is error-prone and cumbersome.

Question 46.
What is an Interface?
Answer:
An Interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies (abstract methods) means an Interface is a specification of a method prototype.
—> An Interface may or may not have any methods.
—> An Interface can contain variables that are public, static, and final by default.
—>Interfaces cannot be instantiated—they can only be implemented by classes or extended by other Interfaces.
—> We can use the Interface reference variable to refer to Implementation Class objects.
—>An Interface can’t implement another Interface.
—> An Interface can extend an already existing Interface.
—> A single Class can implement multiple Interfaces.

Question 47.
How can we achieve Multiple Inheritances in Java?
Answer:
Directly we can’t achieve Multiple Inheritance in Java. Indirectly there are two ways, those are :

  1. We can achieve Multiple Inheritance by implementing more than one Interface because we can have a chance to implement more than one Interface in Java.
  2. Another indirect way to achieve Multiple Inheritance is, doing by repeated use of Single Inheritance.

Example:

class z extends A', B - - -  invalid (bcz direct way) 
class B extends A
}  - - - those are vail id (bcz indirect way)
class z extends B

So, here Class z can have all the features of Class B and Class A, but here we are doing indirect ways with the help of Single Inheritance.

Question 48.
What is the difference between an abstract class and an interface?
Answer:
An abstract class allows its subclasses to override the methods defined in it. It is never instantiated and a class can inherit from a single class, as Java doesn’t support Multiple Inheritance. It may contain both abstract and non-abstract methods.

An interface has public, abstract methods and may have public, static, and final variables (read-only). It introduces multiple inheritances by a class implementing several interfaces.

Question 49.
What modifiers may be used with an interface declaration?
Answer:
An interface may be declared as public or abstract.

Question 50.
What is the use of the interface?
Answer:
An interface is a collection of public abstract methods and read-only i.e. public, static, and final variables. The concept of interfaces in Java makes Multiple Inheritance a reality. Two or more non-related classes can implement the same interface. A class can implement multiple interfaces.

Whenever there has to be an ancestry associated with classes along with some concrete behaviors then it is a good idea to come up with abstract classes in such scenario but when implementation is more generic in nature and not dependent upon class relations or type hierarchy then such behaviors should be packaged inside an interface. The methods defined inside an interface can be implemented by non-related classes.

Question 51.
What is the serializable interface?
Answer:
In the java.io package, there is an interface called java.io.Serializable, which is a syntactic way of serializing objects. This interface does not define any method. The purpose of serialization is persistence, communication over sockets, or RMI. In Object serialization, an object can be converted into a byte stream and vice versa.

Question 52.
Does a class inherit constructors from its superclass?
Answer:
No. Constructors cannot be inherited. Constructors are used to initializing a valid state of an object. Whenever a subclass instance is created then it calls no argument default constructor of the superclass. The following code will explain the implicit call to default constructor of the base class:-

class Base {
Base( ) {
system.out.print!n(“I am constructing Base”);
}
}
class Child extends Base {
Child( ) {
System.out.println(“ I am constructing child”);
}
}
public class A {
public static void main(String[ ] args) {
Child child = new Child( );
}
}

Once executed this code will print:
I am constructing Base
I am constructing Child
It means when a child class object is created it inherently calls the no-arg default constructor of the base class.

Question 53.
How many methods do u implement if implement the Serializable Interface?
Answer:
The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are

java.rmi.Remote , java.util.EventListener

Question 54.
What’s the difference between constructors and other methods?
Answer:
Constructors must have the same name as the class and cannot return a value. They are only called once while regular methods could be called many times.

Question 55.
What is constructor chaining and how is it achieved in Java?
Answer:
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java, it is done via an implicit call to the no-args constructor as the first statement.

Question 56.
If the method to be, overridden has access type ‘protected’, can subclass have the access type as ‘private’?
Answer:
No, it must have access type as protected or public, since an overriding method must restrict access of the method it overrides.

Question 57.
If you use super( ) or this( ) in a constructor where should it appear in the constructor?
Answer:
It should always be the first statement in the constructor.

Question 58.
What modifiers may be used with an inner class that is a member of an outer class?
Answer:
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

Question 59.
Can an inner class be defined inside a method?
Answer:
Yes, it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final.

Question 60.
what is an anonymous class?
Answer:
It is a type of inner class with no name. Once defined an object can be created of that type as a parameter all in one line. It cannot have an explicitly declared constructor. The compiler automatically provides an anonymous constructor for such a class.
An anonymous class is never abstract. An anonymous class is always an inner class; it is never static. An anonymous class is always implicitly final.

Question 61.
Why Java does not support Multiple Inheritance?
Answer:
Java design team strove to make Java as:
—> Simple, object-oriented, and familiar
—> Robust and secure
—> Architecture neutral and portable
—> High performance
—> Interpreted, threaded, and dynamic
—>The reasons for omitting Multiple Inheritance from the Java Language mostly stem from the “simple, object-oriented and familiar” goal.
—> Multiple Inheritance causes more problems and confusion than it solves. So the designers’ of Java Language cut Multiple Inheritance from the language (just as they cut Operator overloading).
—> Multiple Inheritance leads to confusion for programmers. This is against to the design principle of the Java to be a Simple Programming Language.

Question 62.
How many types of Inheritances does Java support?
Answer:
Yes, Ok but, basically there are two types of Inheritances are there, they are
1. Single Inheritance
2. Multiple Inheritances
And some other Inheritances are there those are
—> Multi-Level
—> Hierarchical
—> Hybrid
—> But these come under again Basic Inheritances Single and Multiple only. So we can leave these types, and we can say only two types that is Single and Multiple Inheritances.
—> And Java supports only Single Inheritance only.

Question 63.
What is JVM Heap Size? How does it affect the performance of the Application?
Answer:
The heap is the runtime data area from which memory for all class instances and arrays is allocated. The heap may be of a fixed size or may be expanded. The heap is created on a virtual machine start-up. If you have comp heated algorithms or big caching which might create a lot of objects in memory you may need a bigger heap size.

Question 64.
Is null a keyword?
Answer:
The null value is not a keyword.

Question 65.
What is the difference between the >> and >>> operators?
Answer:
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

Question 66.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Answer:
Unicode requires 16 bits and ASCII requires 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Question 67.
Is sizeof a keyword?
Answer:
The sizeof operator is not a keyword.

Question 68.
What are wrapped, classes?
Answer:
Wrapped classes are classes that allow primitive types to be accessed as objects.

Question 69.
What is the difference between the Boolean & operator and the && operator?
Answer:
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

Question 70.
What is the difference between a break statement and a continue statement?
Answer:
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.

Question 71.
What must a class do to implement an interface?
Answer:
It must provide all of the methods in the interface and identify the interface in its implements clause.

Question 72.
what is an abstract method?
Answer:
An abstract method is a method whose implementation is deferred to a subclass.

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

Question 74.
What is meant by Inheritance and what are its advantages?
Answer:
Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are the reusability of code and accessibility of variables and methods of the superclass by subclasses.

Question 75.
What is the difference between abstract class and interface?
Answer:
a) All the methods declared inside an interface are abstract whereas abstract classes must have at least one abstract method and others may be concrete or abstract.b) In abstract class, keyword abstract must be used for the methods whereas interface we need not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can’t have subclasses.

Question 76.
Can you have an inner class inside a method and what variables can you access?
Answer:
Yes, we can have an inner class inside a method and final variables can be accessed.

Question 77.
Does Java provide any construct to find out the size of an object?
Answer:
No there is not the size of the operator in Java. So there is no direct way to determine the size of an object directly in Java.

Question 78.
What t is the use of the main method?
Answer:
the main method is used to start the execution of the program.

Question 79.
What is overloading?
Answer:
Overloading is nothing but having the same name with different parameters, (or) The same function having different functionalities.

Question 80.
What restrictions are placed on method overriding?
Answer:
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

Question 81.
What is overriding?
Answer:
Overriding is nothing but having the same name and method signature. It is between parent class and child class. Child class will always override parent class.

Question 82.
What is method overriding?
Answer:
The method with the same signature but with changed implementation leads to method overriding and that can occur in a parent-child relation of classes. A method defined in parent class can be overridden in its child class with different implementation from its base class.

  1. Pointers are supported in C++ while not in Java. The memory management is done automatically with help of a part of JVM called Garbage Collector.
  2. Multiple inheritances are not supported in Java but supported in C++.
  3. There are no structures and unions in Java.
  4. There are no scope resolution operators in Java (::).
  5. There are no destructors in Java like C++.
  6. There is no virtual keyword in Java because all non-static methods use dynamic binding.

Question 83.
What are the access modifiers?
Answer:
Public, Private, Protected, and Default.

Question 84.
What is Method Signature?
Answer:
Method signature is nothing but (return type of function + function name + no.of arguments).

Question 85.
What are the rules we have to follow in overloading?
Answer:

  1. The no. of arguments must be different.
  2. the type of arguments must be different
  3. It will not depend on the return type.

Question 86.
What are the Secondary Access Modifiers?
Answer:
Static, abstract, final, transient, and volatile.

Question 87.
What is Shadowing?
Answer:
Declaring the same variables of parent class in the subclass is known as Shadowing.
Eg: e.super.x;

Question 88.
What are the types of data types in Java?
Answer:
byte, short, int, float, long, double, char, and Boolean

Question 89.
Can we call the nonstatic variables into static methods?
Answer:
No, vice versa is also not possible.

Question 90.
What is numeric promotion?
Answer:
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

Question 91.
What is the difference between a public and a non-public class?
Answer:
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

Question 92.
To what value is a variable of the boolean type automatically initialized?
Answer:
The default value of the boolean type is false.

Question 93.
Is delete, next, main, exit, or null keyword in java?
Answer:
No.

Question 94.
What is the basic difference between overloading and overriding?
Answer:
It is necessary to check the method signature in overloading, whereas it is not necessary in overriding. Method overloading between the same class methods and method overriding is between parent class method and child class method.’

Question 95.
What is Java bytecode?
Answer:
Bytecode is a highly optimized set of instructions designed to be executed by the java run time system, which is called the Java Virtual Machine (JVM)

Question 96.
What is a java virtual machine?
Answer:
Java VM is an interpreter for the bytecode.

Question 97.
What is Encapsulation?
Answer:
Encapsulation is the mechanism that binds together code and the data it manipulates and keeps them safe from outside interference and misuse.

Question 98.
What is Data Abstraction?
Answer:
Abstraction is nothing but keeping the data and methods in a single object.

Question 99.
What is inheritance?
Answer:
Inheritance is the process by which one object acquires the properties of another object.

Question 100.
What are the types of inheritance?
Answer:

  • Single inheritance.
  • Multiple inheritances
  • Multi-level inheritance
  • Hybrid inheritance.

Question 101.
Does dose Java support multiple inheritances?
Answer:
No. interfaces are used for this purpose.

Question 102.
What is polymorphism?
Answer:
Polymorphism is a feature that allows one interface to be used for a general class of actions.

Question 103.
What is Type Costing?
Answer:
The conversion of one data type to another data type is known as Type Costing. It is possible in higher data types to lower.

Question 104.
What is the range and width of long?
Answer:
Range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 and the width is 64.

Question 105.
What is the range and width of int?
Answer:
Range is -2,147,483,648 to 2,147,483,647 and width is 32.

Question 106.
What is the range and width of short?
Answer:
Range is -32,768 to 32,767 and width is 16.

Question 107.
What is the range and width of the byte?
Answer:
The range is -128 to 127 and the width is 8.

Question 108.
What is the declaration of an Array?
Answer:
int Array [ ] = new int [5];

Question 109.
What is a class?
Answer:
A class is a template for an object.

Question 110.
What is an Object?
Answer:
The object is an instance of a class.

Question 111.
What are called instance variables?
Answer:
The data or variables defined within a class are called instance variables.

Question 112.
What is a Constructor?
Answer:
Constructor is used to initializing the object. Constructors have no return type, not even void.

Question 113.
What are the types of Constructors?
Answer:
Constructors are divided into two types: I) Implicit and 2) Explicit.

Question 114.
What are the types of explicit constructors?
Answer:
Argument constructors and Default constructors.

Question 115.
Where do we use the keyword ‘this’?
Answer:
‘this is always a reference to the object on which the method was invoked.

Question 116.
Can we get the output using Constructors?
Answer:
No, These are used only for assigning values.

Question 117.
What is call by value and call by reference?
Answer:
When a simple type is passed to a method, it is done by use of call-by-by-value. Objects are passed call by reference.

Question 118.
What is Recursion?
Answer:
It is a process of defining something in terms of itself.

Question 119.
What is recursive?
Answer:
A method that calls itself is said to be recursive.

Question 120.
What is Static?
Answer:
Static is the keyword, which is used to create a member that can be used by itself, without reference to a specific instance. It is a class-level variable. It is illegal to refer to any instance variables inside of a static method.

Question 121.
Can we refer to instance variables inside of a static method?
Answer:
No. We can’t.

Question 122.
What is final?
Answer:
The final prevents its contents from being modified.

Question 123.
What is Dynamic Method Dispatch?
Answer:
Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at run time, rather than at compile time.

Question 124.
What is an abstract class?
Answer:
Restriction of data is called Abstract. We can’t create the instance. These are virtual classes. It is the same as the interface but we can implement the methods.

Question 125.
What does the “abstract” keyword mean in front of a method? A class?
Answer:
Abstract keyword declares either a method or a class. If a method has an abstract keyword in front of it, it is called an abstract method. An abstract method has nobody. It has only arguments and returns types. Abstract methods act as placeholder methods that are implemented in the subclasses.
Abstract classes can’t be instantiated. If a class is declared as abstract, no objects of that class can be created. If a class contains any abstract method it must be declared as abstract

Question 126.
Which keyword is used to prevent Overriding?
Answer:
Final

Question 127.
What is an interface?
Answer:
It is a task for a specific contract. It does not actually define any implementations. It is not at all a class. It won’t allow constructors.

Question 128.
What is public?
Answer:
If we declare it as a public, classes, subclasses within the package and outside the package, can access it.

Question 129.
What is private?
Answer:
It can’t be accessed anywhere other than the same class.

Question 130.
What is protected?
Answer:
It can be accessed in the same class, a subclass of the same package but not, another side of that package.

Question 131.
What is pass by reference and pass by value?
Answer:
Pass by Reference means passing the address itself rather than passing – the value. Pass by Value means passing a copy of the value to be passed.

Question 132.
What is passed by the ref and what by value?
Answer:
All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references

Question 133.
What is an abstract class?
Answer:
Abstract class must be extended /subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (i.e., you may not call its constructor), an abstract class may contain static data. Any class with an abstract method is automatically abstract itself and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Question 134.
Can an abstract class be final?
Answer:
An abstract class may not be declared as final

Question 135.
What is static in java?
Answer:
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. 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 an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a nonstatic method. In other words, you can’t change a static method into an instance method in a subclass.

Question 136.
What is the difference between the static (class) method and the instance method?
Answer:

Static or class method Instance method
1. A method i.e. declared as static is known as a static method. A method i.e. not declared as static is known as an instance method.
2. Object is not required to call a static method. The object is required to call instance methods.
3. Non-static (instance) members cannot be accessed in static context (static method, block, and static nested class) directly. Static and non-static variables both can be accessed in instance methods.
4. For example: public static int cube (int n) { return n*n*n;} For Example: public void msg( ){…..}

Question 137.
Difference between method Overloading and Overriding.
Answer:

Method Overloading Method Overriding
1. Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its superclass.
2. Method overloading occurs within the class. Method overriding occurs in two classes that have an IS-A relationship.
3. In this case, the parameter must be different. In this case, the parameter must be the same.

Question 138.
Why we cannot override the static method?
Answer:
It is because the static method is the part of the class and it is bound with class whereas the instance method is bound with the object and static gets memory in the class area and instance gets memory in heap.

Question 139.
What is final?
Answer:
A final class can’t be extended i.e. final class may not be subclassed. A final method can’t be overridden when its class is inherited. You can’t change the value of a final variable (is a constant).

Question 140.
What does the “final” keyword mean in front of a variable? A method? A class?
Answer:
FINAL for a variable: value is constant FINAL for a method: cannot be overridden FINAL for a class: cannot be derived

Question 141.
What is the difference between instanceof and instance?
Answer:
instanceof is used to check to see if an object can be cast into a specified
type without throwing a cast class exception.
islnstance( )
Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

Question 142.
What is the output from System. out.println(“Hello”+null);
Answer:
Hellonull

Question 143.
Can you have virtual functions in Java?
Answer:
Yes, all functions in Java are virtual by default.

Question 144.
What if the main method is declared private?
Answer:
The program compiles properly but at runtime, it will give a “Main method not public.” message.

Question 145.
What if the static modifier is removed from the signature of the main method?
Answer:
Program compiles. But at runtime throws an error “NoSuchMethodError”.

Question 146.
What if I write static public void instead of the public static void?
Answer:
The program compiles and runs properly.

Question 147.
What if I do not provide the String array as the argument to the method?
Answer:
Program compiles but throws a runtime error “NoSuchMethodError”.

Question 148.
How many different ways to create an object?
Answer:
There are 4 ways of creating objects in java
• By using the new keyword, this common and mostly used to create an object
My class object=new MyClass( );
• If you know the class name and it has public default constructor, you can create an object by
class.former My class object= (My class) class.forName(“My class”).
newlnstance( );
• Using clone( ).it can be used to create a copy of an existing object.
MyClass object=new MyClass( ); .
Myclass anotherObject=object.clone( );
• Using object deserialization
ObjectlnputStream oi = new objectlnputsteram(inputstream);
Myclass object = (MyClass) oi.readObject( );

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

Question 150.
Why can’t I say just abs() or sin() instead of Math.abs() and Math. sin()?
Answer:
The import statement does not bring methods into your local namespace. It lets you abbreviate class names, but not get rid of them altogether. That>s just the way it works, you>ll get used to it. It>s really a lot safer this way. <br> However, there is actually a little trick you can use in some cases that get you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local namespace.

But you can>t use this trick in an applet because you have to inherit from Java.awt. Applet. And actually, you can>t use it on java.lang.Math at all, because Math is a «final» class which means it ean>t be extended.

Question 151.
Is “abc” a primitive value?
Answer:
The String literal “abc” is not a primitive value. It is a String object.

Question 152.
Can an application have multiple classes having main method?
Answer:
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is no conflict amongst the multiple classes having main method.

Question 153.
What are the Object and Class classes used for?
Answer:
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

Question 154.
What is overriding?
Answer:
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called and not the method definition from superclass. Methods may be overridden to be more public, not more private.

Question 155.
What are different types of inner classes?
Answer:
Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. E.g, outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes – Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes – Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members; the modifiers public, protected, private, and static are not usable.

Anonymous classes – Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Question 156.
Are the imports checked for validity at compile time? For E.g. will the code containing an import such as java. lang.ABCD compile?
Answer:
Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying, cannot resolve symbol: class ABCD location: package io import java.io.ABCD;

Question 157.
What does it mean that a method or field is “static”?
Answer:
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. /
Static methods can be referenced with the name of the class rather than thaiythe name of a particular object of the class (though that works too). That’s how library methods like System.out.println( ) work out is a static field in the java.lang. System class.

Question 158.
What is the difference between declaring a variable and defining a variable?
Answer:
In declaration we just mention the type of the variable and its name. We do not initialize it. But defining means declaration + initialization, e.g. String s; is just a declaration while String s = new String (“abed”); Or String s = “abed”; are both definitions.

Question 159.
What is the default value of an object reference declared as an instance variable?
Answer:
null unless we define it explicitly.

Question 160.
Can a top-level class be private or protected?
Answer:
No. A top level class cannot be private or protected. It can have either “public” or no modifier. If it does not have a modifier it is supposed to have a default access. If a top-level class is declared as private the compiler will complain that the “modifier private is not allowed here”. This means that a top-level class cannot be private. Same is the case with protected.

Question 161.
What type of parameter passing does Java support?
Answer:
In Java the arguments are always passed by value.

Question 162.
Primitive data types are passed by reference or pass by value?
Answer:
Primitive data types are passed by value.

Question 163.
Objects are passed by value or by reference?
Answer:
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Question 164.
How does Java handle integer overflows and underflows?
Answer:
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Question 165.
What is the difference between a while statement and a do statement?
Answer:
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Question 166.
What is the difference between the prefix and postfix forms of the ++ operator?
Answer:
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value of all of the expressions and then performs the increment operation on that value.

Question 167.
What is the purpose of a statement block?
Answer:
A statement block is used to organize a sequence of statements as a single statement group.

Question 168.
How many ways can one write an infinite loop?
Answer;
Personally, I would recommend the following ways to implement an infinite loop in Java but there can be other ways like calling a method recursively, though I never tested that.

- while (true)

- for (;;) { }

Question 169.
When do you use ‘continue’ and ‘break’ statements?
Answer:
When one wants to complete the iteration of a loop prematurely then ‘continue’ statement is used. While the ‘break’ statement is used to exit the entire loop whenever encountered.

Question 170.
What is the difference between ‘while’ and ‘do-while loop?
Answer:
In the case of the ‘do-while ‘ loop, body is always executed at least once, since test is performed at the end of the body. It should usually be ignored while coding.

Question 171.
What restrictions are placed on the values of each case of a switch statement?
Answer:
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

Question 172.
What is the difference between an if statement and a switch statement?
Answer:
If statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

Question 173.
Can a for statement loop indefinitely?
Answer:
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;);

Question 174.
What is the range of the short type?
Answer:
The range of the short type is – (2A15) to 2A15 – 1.

Question 175.
To what value is a variable of the String type automatically initialized?
Answer:
The default value of a String type is null.

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

Question 177.
What is the difference between static and non-static variables?
Answer:
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.

Question 178.
How are this() and super( ) used with constructors?
Answer:
this( ) is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

Question 179.
Can an unreachable object become reachable again?
Answer:
An unreachable object may become reachable again. This can happen when the object’s finalize!) method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

Question 180.
What modifiers are allowed for methods in an Interface?
Answer:
Only public and abstract modifiers are allowed for methods in interfaces.

Question 181.
What are some alternatives to inheritance?
Answer:
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the superclass: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Question 182.
Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
Answer:
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

Question 183.
How does Java handle integer overflows and underflows?
Answer:
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Question 184.
What is Downcasting?
Answer:
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy

Question 185.
Can a method be overloaded based on a different return types but the same argument type?
Answer:
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler

Question 186.
What happens to a static var that is defined within a method of a class?
Answer:
Can’t do it. You’ll get a compilation error

Question 187.
How many static init can you have?
Answer:
As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.

Question 188.
What modifiers may be used with an inner class that is a member of an outer class?
Answer:
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

Question 189.
What restrictions are placed on the location of a package statement within a source code file?
Answer:
A package statement must appear as the first line in a source code file (excluding blank lines and comments).

Question 190.
A variable can be declared to be final, as in the declaration “static final int ballCount = 25;” What does it mean to declare the variable to be “final”? Why would you want to use such a variable in a program? (For extra credit: Why do you suppose that “final” variables are generally declared to be “static” as well?)
Answer:
When a variable is declared to be “final,” its value can never be changed from the value that is initially assigned to it. The variable is said to be a named constant. The two main reasons for using final variables are:
Using a meaningful name such as “ballCount” to represent a quantity, rather than an actual value such as 25, makes the program easier to read and understand. Suppose you want to modify your program to use a different value for the constant (for example, ballpoint = 50 instead of ballCount = 25).

It is easy to change the value of a final variable in the single fine where it is declared. In general, it would be much harder to find and change an actual value every place it occurs in the program. Extra credit: If a variable is non-static, then every object that belongs to the class gets its own copy of the variable. In the case of a final variable, all these copies would have the same value. It makes more sense to have a single copy, associated with the class. So final variables are usually declared to be static.

Question 191.
Explain what is meant by polymorphism, and give an example.
Answer:
Polymorphism refers to the fact that a method call, such as shape.draw( ), can call different methods, depending on the actual type of the object. If the variable, shape, is declared to be of type Shape, then it can refer to an object belonging to the class Shape or to any subclass of that class. Each of these subclasses might have its own version of the draw( ) method. The method is actually called by the command shape.draw( ) depends on which class the shape object actually belongs to.

Question 192.
What is HotJava?
Answer:
HotJava is a Browser provided by Sun. It is a modular, applet-aware, extensible WorldWide Web browser written entirely in Java. The security in HotJava provides a safe environment for the execution of imported code. The security is based on interlocking layers of security that range from the design of the Java language at the base to the file and network access protections at the top.

Question 193.
What is the sequence of interpretation, compilation of a java applet?
Answer:
A java program is first compiled to byte code which is stored in a ‘.class file’. This file is downloaded as an applet to a browser which then interprets it by converting it into machine code appropriate to the hardware platform on which it is running.

Question 194.
How JAVA achieves platform independence?
Answer:
Java is platform-independent because of the consistent data sizes at all the platforms on which Java code is run. The output of a Java compiler is not an executable code it is bytecode, bytecode is a highly optimized set of instructions designed to be executed by a virtual machine that the Java run-time system emulates. As Java programs are interpreted, rather than compiled it is much easier to run them in a variety of run-time environments.

Question 195.
Does Java support virtual functions?
Answer:
No, Java does not support virtual functions directly as supported by C++. Virtual functions can be implemented in Java using abstract classes and interfaces. An abstract class is a class with the declaration of methods, but without their implementation. The implementation of the methods takes place in the subclasses. Another example of virtual functions is interfaces. The only difference between an abstract class and an interface is that abstract classes can be used only when they are superclasses and the subclass implements their methods. Whereas in an interface the methods can be implemented even by classes, which are not inherited.

Question 196.
What software is needed to learn Java?
Answer:
A Java compiler/development environment such as VJ++ is needed to learn Java.

Question 197.
What are the different int data types provided by Java?
Answer:
The different data types supported by Java are– int, short, long, and byte. The bytewise representations are as follows:

  • byte-8 byte
  • short-16 byte
  • int-32 byte
  • long-64 byte.

Question 198.
What are the different data types in Java?
Answer:
Java supports the following 8 primitive data types:
(click this picture to enlarge)

Data Type Size Default value (for fields) Range of Value (Min-Max)
Byte 8 bits 0 -128(-2∧7) to 127(2∧7-1)
Short 16 bits 0 -32,728(-2∧15) to 32,767(2∧15-1)
Int 32 bits 0 -2,147,483,648(-2∧31) to 2,147,483,647(2∧3-1)
Long 64 bits 0L -9,223,372,036,854,775,808(-2∧63) to 9,233,372,036,854,775,807(2∧63-1)
Float 32 bits 0.0f N/A
Double 64 bits 0.0d N/A
Char 16 bits ‘u0000’ (U000 or 0) to uffff (or 65,535 –>(2∧16-1) inclusive)
boolean 1 bit false True or faslse

Question 199.
What are expressions, statements, and blocks in Java?
Answer:
An expression is a construct made up of variables, operators, and method invocations, which are built-up according to the syntax of the language that evaluates to a single value.
Some examples of expression:

int val = 0; 
iArr[0] = 20;
int var =4+2; // var is now 6

A statement is complete unit of execution. Any expression which is:

  • An assignment expression
  • ++ or – –
  • Method invocation
  • Object creation

Question 200.
What is the difference between Java and HTML?
Answer:
Java is a full-fledged object-oriented programming language. It is derived from C++ and shares the same basic syntax as that language. HTML (HyperText Markup Language) is not a programming language. It is simply used as a scripting tool to develop web pages. It is not an editor – it is a simple scripting language that defines how the text and images will appear on the web page. Java is used to create small applications (called applets) that run in the browser. It can also be used to develop full-fledged applications.

Question 201.
Which would be faster – an application developed in Java or an application developed in C++?
Answer:
An application developed in C++ would be about 30 times faster than Java.

Question 202.
What is the difference between the » and »> operators?
Answer:
The >> operator carries the sign bit when shifting right. The »> zero-fills bits that have been shifted out. .

Question 203.
How are memory leaks possible in Java
Answer:
If any object variable is still pointing to some object which is of no use, then JVM will not garbage collect that object and object will remain in memory creating memory leak.

Question 204.
What would happen if you say this = null
Answer:
this will give a compilation error as follows cannot assign value to final variable this.

Question 205.
How would you pass a java integer by reference to another function?
Answer:
Passing by reference is impossible in JAVA but Java supports the object reference so. Object is the only way to pass the integer by reference.

Question 206.
Do multiple inheritances in Java?
Answer:
It’s not possible directly. That means this feature is not provided by Java, but it can be achieved with the help of Interface. By implementing more than one interface.

Question207.
What is data encapsulation? What does it buy you?
Answer:
The most common example I can think of is a java bean. Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class which is used to access the fields of the object. Typically the fields are made private while the get and set methods are public.
encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using java beans in Struts, for instance).

Question 208.
What are the primitive types in Java?
Answer: According to Java in a Nutshell, 5th ed: boolean, byte, char, short, long float, double, int

Question 209.
What is a heap in Java?
Answer:
JAVA is a fully Object-oriented language. It has two phases first one is the Compilation phase and the second one is the interpretation phase. The Compilation phase converts the java file to a class file (byte code is the only readable format of JVM) then the Interpretation phase interoperates the class file line by line and gives the proper result.

Question 210.
In Java, how are objects/values passed around?
Answer:
In Java Object are passed by reference and Primitive data is always pass by value

Question 211.
Do primitive types have a class representation?
Answer:
The primitive data type has a wrapper class to present.
Like for int – Integer, for byte Byte, for long-Long, etc …

Question 212.
How can you free memory?
Answer:
With the help of finalize( ) method.
If a programmer really wants to explicitly request a garbage collection at some point, System.gc( ) or Runtime.gc( ) can be invoked, which will fire off a garbage collection at that time.

Question 213.
Does java do reference counting?
Answer:
It is more likely that the JVMs you encounter in the real world will use a tracing algorithm in their garbage-collected heaps.

Question 214.
What does a static inner class mean? How is it different from any other static member?
Answer:
A static inner class behaves like any “outer” class. It may contain methods and fields.
It is not necessarily the case that an instance of the outer class exists even when we have created an instance of the inner class. Similarly, instantiating the outer class does not create any instances of the inner class.
The methods of a static inner class may -access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access field x, but it cannot access field y.

Question 215.
What is the restriction imposed on a static method or a static block of code?
Answer:
A static method should not refer to instance variables without creating an instance and cannot use the “this” operator to refer to the instance.

Question 216.
How do you declare constant values in java?
Answer:
Using Final keyword we can declare the constant values. How all can you instantiate final member’s Final member can be instantiate only at the time of declaration. Null.

Question 217.
What is the difference between the operator and the operator?
Answer:
*&&’ is a Logical operator while is a Bitwise operator.
e.g.
int x=12; binary represenation of 12- – – – – – > 1100
int y=10; 1010 binary represenation of 10- – – – – > 1010
int z=x & y; binary represenation of (x & y)- – – – – > 1000
Here value of z will be 8.
In the case of logical operator “&&’;
condition 1 && condition2
if condition 1 is false then (condition 1 &amp; amp; amp; amp; & condition2) will always be false, that is the reason why this logical operator is also known as short circuit operator, if condition 1 is true then condition2 is to be evaluated, if it is true then the overall result will be true else it will be false.

Question 218.
Why the main method of Java has a public static void?
Answer:
It is the main entry point of a java file. Every java file has just a single copy of the main method from where the main thread is invoked and that’s why the main method is static. This method can be overloaded but JVM will distinguish public static void main from the rest of the overloaded main methods.

Question 219.
What are the command line arguments?
Answer:
Whenever a java file is executed it is done by java command given as below:

java usage: java [-options] class [args...]

(to execute a class)

or java -jar [-options] jar-file [args...]

(to execute a jar file)
when some arguments are also passed with execution command then these arguments are called command-line arguments as they are taken as an array of String as a parameter in the main method.

Question 220.
Does Java support multidimensional arrays?
Answer:
The Java programming language does not really support multi-dimensional arrays. It does, however, support arrays of arrays. In Java, a two-dimensional array ‘arr’ is really an array of one-dimensional arrays:

int [ ][ ] arr = new int[4][6];

The expression arr[i] selects the one-dimensional array; the expression arr[i][j] selects the element from that array.
The built-in multi-dimensional arrays suffer the same indignities that simple one-dimensional arrays do: Array indices in each dimension range from zero to, where length is the array length in the given dimension. There is no array assignment operator. The number of dimensions and the size of each dimension is fixed once the array has been allocated.

Question 221.
What are the restrictions for the static method?
Answer:
Whenever you say something is static that means data or method is not associated with an object instance of that class. They are allocated when a class is loaded, during compile time. Only a single copy of that will be created for that class. So even if you have never created an object of a class you can always access static data and method of that class. If you have class by name ‘Vehicle’ and you have a static method ‘drive( )’ then it can simply be invoked by ‘ Vehicle.drive( )’, no need for object creation in this scenario. A static method cannot access non static data and can invoke other static methods. All static methods are automatically final. It is redundant to make the final.

Question 222.
Why an abstract method cannot be static?
Answer:
An abstract method is usually defined in an abstract class or an interface, for which implementation is provided in a subclass or a class implementing the interface. As static methods just have a single copy per class and are interpreted at code compile time, not at runtime, so it is impossible to have polymorphic behavior out of them. In other words, they cannot be overridden.
An abstract class is one that cannot be instantiated but a static method defined in an abstract class can be invoked without creating an instance. So there is no mechanism to ensure the call of an abstract static method.
Moreover, this is a design decision by language designers. 🙂

Question 223.
Why Java does not support pointers?
Answer:
As per the design decision, Java does not support pointers explicitly. This greatly reduces the burden of dynamic memory management while coding from programmers. Though programmers dynamically allocate memory while coding but they need not worry about de-allocating this memory. The automatic garbage collection feature of Java collects dangling references of objects though it has a trade-off on performance as programmer managed memory management will be efficient as compared to JVM-driven automatic garbage collection.

Question 224.
Is ‘size of a keyword?
Answer:
No, ‘size is an operator used in C and C++ to determine the bytes of a data item, but it is not used in Java as all data types are standard-sized in all machines as per specifications of the language. A JVM is free to store data any way it pleases internally, big or little-endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes. In JDK 1.5+ you can use java.lang.instrument. Instrumentation. getObjectSize( ) to get the object size. On Java World, I have found an interesting article on Objects’ size determination, read.

Question 225.
What is the precedence of operators in Java?
Answer:
The precedence of operators suggests the sequence in which operators will be work upon in case of compounded statements containing several operators.
For example, in the expression

x = a + b * c;

the first “+” operator still first determines its left operand (“a” in this case) and then it’s a right operand. But in this case, the right operand consists of the expression “b*c”. The multiplication operator has higher precedence than the additive “+”. Precedence can be overridden with parentheses, e.g.

x = (a + b) * c;

will force the addition of b to a, and then this sum is multiplied by c.
The table shown in the image below is organized from higher precedence to low when you traverse from top to the bottom of the table.

Operator Types Operator
Unary ++X, –X, +X, -X,∼, !
Arithmetic (and shift) =, / , %, +, -, <<->>
Relational >,<, >=, <=, ==, !=
Logical (and bitwise) &&, ||, &, |,
Conditional (termary) A>B ?X:Y
Assignment =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ∧=,|=

Question 226.
How is an argument passed in Java methods?
Answer:
In Java no matter if the variable is a primitive data type or an object when passed as an argument to a method; they are always passed by value. This is a most common error that most newcomers to language and even veterans do in understanding this concept. Please go through to following link onjava.sun.com website for a detailed discussion and understanding of this concept.

Question 227.
What is the difference between class variable, member variable, and automatic (local) variable?
Answer:
The class variable is a static variable and it does not belong to any instance of the class but shared across all the instances.
The member variable belongs to a particular instance of the class and can be called from any method of the class. ,
The automatic or local variable is created on a method entry and valid within method scope and they have to be initialized explicitly.

Question 228.
When are static and nonstatic variables of a class initialized?
Answer:
The static variables are initialized at class load time during compilation and nonstatic variables are initialized just before the constructor is called.

Question 229.
Can shift operators be applied to float types?
Answer:
No, shift operators are applicable only on integer or long types.

Question 230.
What are different Java declarations and their associated rules?
Answer:
All variables in Java are introduced/declared with some basic data types with some basic values, e.g. every decimal value by default is a double. The names of variables must avoid reserved Java keywords. The local variables are explicitly initialized.

Question 231.
What are Java Modifiers?
Answer:
Java classes, interfaces, and their members can be declared with one or ^ more modifiers. They can be categorized as:
Class Modifiers
ClassModifier: one of public-private (for inner classes) protected (for inner classes) abstract static final strictfp Any top-level class can either be public or package-private (no explicit modifier)

Field Modifiers
* FieldModifier: one of public protected private static final transient volatile
Method Modifiers
MethodModifier: one of public protected private abstract static final synchronized native strictfp .
Constructor Modifiers
ConstructorModifier: one of public protected private The following matrix of the all modifiers in Java shows which modifier maps to which element:-
Basic Java Interview Questions in Java chapter 3 img 1

Question 232.
Explain the final modifier.
Answer:
‘final’ modifier can be applied to classes, methods, and variables and the features cannot be changed, the final class cannot be subclassed, methods cannot be overridden.

Question 233.
Can you change the reference of the final object?
Answer:
No, the reference cannot be changed, but the data in that object can be changed.

Question 234.
Can an abstract class be instantiated?
Answer:
No, an abstract class cannot be instantiated i.e. you cannot create a new object of this class. When does the compiler insist that the class must be abstract? In the following conditions, the compiler insists ‘abstract’ keyword with a class:

  • If one or more methods of the class are abstract.
  • If a class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
  • If a class implements an interface and provides no implementation for those methods

Question 235.
Where can static modifiers be used?
Answer:
They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of the class. They are loaded at the class compile time.

Question 236.
Why is not recommended to have instance variables in Interface
Answer:
By Default, All data members and methods in an Interface are public. Having public variables in a class that will be implementing will be a violation of the Encapsulation principle.

Question 237.
Can there be an abstract class with no abstract methods in it?
Answer:
Yes

Question 238.
Can an Interface be final?
Answer:
No

Question 239.
Can an Interface have an inner class?
Answer:
Yes.

public interface abc {
static int i=0;
void dd( );
class al { 
al( ) {
int j;
System.out.println(“in interfia”);
};
public static void mainfstring a1[ ]) {
System.out.println(“in interfia”);
}
}
}

Question 240.
What is a Nested Interface?
Answer:
An interface that is declared within another interface or class is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can’t be accessed directly.
Points to remember for nested interfaces
There are given some points that should be remembered by the java programmer.

  • Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static implicitly.

Syntax of nested interface which is declared within the interface

interface interface_name{
... 
interface nested_interface_name{
       ... 
}
}
Syntax of nested interface which is declared within the class class_name{
... 
interface nested_interface_name{
}
}

Example of nested interface which is declared within the interface

In this example, we are going to learn how to declare the nested interface and how we can access it.

interface Showable{
void show( );
interface Message{
void rnsg( );
}
}
class Test implements showable.Message{
public void msgC){System.out.println(“Hello nested interface”);}
public static void main(String args[ ]){
showable.Message message=new Test( );//upcasting here message.msg( );
}
}

Output: hello nested interface
As you can see in the above example, we are accessing the Message interface by its outer interface Showable because it cannot be accessed directly. It is just like the almirah inside the room, we cannot access the almirah directly because we must enter the room first. In the collection frame word, the sun microsystem has provided a nested interface Entry. Entry is the subinterface of Map i.e. accessed by Map. Entry. Internal code generated by the java compiler for nested interface Message The java compiler internally creates public and static interface is displayed below;

public static interface Showable$Message
{
public abstract void msg( );
}

Example of nested interface which is declared within the class

Let’s see how can we define an interface inside the class and how can we access it.

class A{
interface Message{
void msg( );
}
}
class Test implements A.Message{
public void msg( ){System.out.println(“Hello nested interface”);}
public static void main(string args[ ]){
A.Message message=new Test( );//upcasting here
message. msg( );
}
}

Output: hello nested interface

Question 241.
Can we define private and protected modifiers for variables in interfaces?
Answer:
No

Question 242.
What are some alternatives to inheritance?
Answer:
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the superclass: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Question 243.
Why isn’t there operator overloading?
Answer:
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print( )- Note that some of the classes like DataOutputStream have unoverloaded methods like writelnt( ) and write bytes( ).

Question 244.
what does it mean that a method or field is “static”?
Answer:
Static variables and methods are instantiated only once per class. In other words, they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println( ) work, out is a static field in the java. lang.System class.

Question 245.
What is static initializer code?
Answer:
A class can have a block of initializer code that is simply surrounded by curly braces and labeled as

static e.g.
public class Demo{
static int =10;
static{
System.out.println(“Hello world’);
}
}

And this code is executed exactly once at the time of class load.

Question 246.
Can an anonymous class implement an interface and extend a class at the same time?
Answer:
No, an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time.

Question 247.
What are the differences between JIT and HotSpot?
Answer:
The Hotspot VM is a collection of techniques, the most significant of which is called “adaptive optimization.
The original JVMs interpreted byte codes one at a time. Second-generation JVMs added a JIT compiler, which compiles each method to native code upon first execution, then executes the native code. Thereafter, whenever the method is called, the native code is executed. The adaptive optimization technique used by Hotspot is a hybrid approach, one that combines byte code interpretation and run-time compilation to native code.
Hotspot, unlike a regular JIT compiling VM, doesn’t do “premature optimization”.

Question 248.
How Java enabled High Performance?
Answer:
Java uses a Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode, which is a program that contains instructions that must be interpreted into instructions that can be sent directly to the processor.

Question 249.
What is a memory footprint? How can you specify the lower and upper limits of the RAM used by the JVM? What happens when the JVM needs more memory?
Answer:
When JVM needs more memory then it does the garbage collection and sweeps all the memory which is not being used.

Question 250.
What is the difference between JVM Spec, JVM Implementation, and JVM Runtime?
Answer:
The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation.

Question 251.
What is the JIT compiler?
Answer:
Just-In-Time (JIT) compiler: It is used to improve performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Question 252.
What is Java Virtual Machine and how it is considered in the context of Java’s platform independent feature?
Answer:
When Java is compiled, it is not compiled into the platform-specific machines, rather into platform-independent byte code. This byte code is distributed over the web and interpreted by a Virtual Machine (JVM) on whichever platform it is being run.

Question 253.
What is the main difference between the Java platform and other platforms?
Answer:
The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms. It has two components:

  1. Runtime Environment
  2. API(Application Programming Interface)

Question 254.
What gives Java its ‘write once and run anywhere nature?
Answer:
Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform-specific machine code is generated thus making the java platform independent.

Question 255.
Describe what happens when an object is created in Java?
Answer:
Several things happen in a particular order to ensure the object is constructed properly:
1. Memory is allocated from the heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java. lang. The object is called java. lang. The object is the base class for all objects in the java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is
executed. Thus, the constructor for the base class completes first and the constructor for the most derived class completes last.

Question 256.
Can we declare multiple main() methods in multiple classes, ie can we have each main method in its class in our program?
Answer:
YES

Question 257.
Can you run the product development on all operating systems?
Answer:
The product which was developed in Java can run on all platforms if there exists a Platform-specific JVM.

Question 258.
What is polymorphism?
Answer:
Polymorphism is the feature of OOPs. One interfaces multiple implementations. Designing a generic interface for a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. Polymorphism is achieved in a class by method overloading. Run time Polymorphism is achieved in a class hierarchy by method overriding.

Question 259.
Suppose if we have variable ‘ I ‘ in the run method if I can?
Answer:
Create one or more threads each thread will occupy a separate copy or same variable will be shared?
Threads will share the data and code. So if T is an instance variable then it will be shared by all threads. If T is a static variable then it will have the same copy of it.

Question260.
What are native methods? How do you use them?
Answer:
Native methods are methods written in other languages like C, C++, or even assembly language. You can call native methods from Java using JNI. Native methods are used when the implementation of a particular method is present in languages other than Java say C, C++. To use the native methods in java we use the keyword native public native method_a( ).

This native keyword signals to the java compiler that the implementation of this method is in a language other than java. Native methods are used when we realize that it would take up a lot of rework to write that piece of already existing code in another language to Java.

Question 261.
what are the four corner stones of OOP?
Answer:
Abstraction, Encapsulation, Polymorphism, and Inheritance.

Question 262.
what do you understand by private, protected, and public?
Answer:
These are accessibility modifiers. Private is the most restrictive, while the public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package; however, the protected keyword allows visibility to a derived class in a different package.

Question 263.
Difference between a Class and an Object?
Answer:
A class is a definition or prototype whereas an object is an instance or living representation of the prototype.

Question 264.
What is Downcasting?
Answer:
Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.

Question 265.
Can a top-level class be private or protected?
Answer:
No, a top-level class cannot be private or protected. It can have either “public” or no modifier.

Question 266.
What is the difference between method overriding and overloading?
Answer:
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.

Question 267.
What is the restriction on an Overridden methods’ accessibility?
Answer:
Overriding methods cannot reduce accessibility – they can either have the same or greater accessibility.

Question 268.
Can a method be overloaded based on different return types but the same argument type?
Answer:
No, because the methods can be called without using their return type in which case there is ambiguity for the compiler.

Question 269.
What is a “stateless” protocol?
Answer:
Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request-response combination.

Question 270.
What happens to a static var that is defined within a method of a class?
Answer:
Can’t do it. You’ll get a compilation error.

Question 271.
What is constructor chaining and how is it achieved in Java?
Answer:
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java, it is done via an implicit call to the no-args constructor as the first statement.

Question 272.
How many static init can you have?
Answer:
As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.

Question 273.
What is passed by the ref and what by value?
Answer:
All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references.

Question 274.
How do you ensure the size of a primitive data type?
Answer:
You can’t.

Question 275.
Where and how can you use a private constructor?
Answer:
A private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.

Question 276.
what is Dynamic Binding (late binding)?
Answer:
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.

Question 277.
What is the difference between JVM Spec, JVM Implementation, JVM Runtime?
Answer:
The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation.

Question 278.
Give a few reasons for using Java?
Answer:
Java is a fun language. Let’s look at some of the reasons:

  • Built-in support for multi-threading, socket communication, and memory management (automatic garbage collection).
  • Object-Oriented (00).
  • Better portability than other languages across operating systems.
  • Supports Web-based applications (Applet, Servlet, JSP), distributed applications (sockets, RMI, EJB, etc), and network protocols (HTTP, JRMP, etc) with the help of extensive standardized APIs (Application Programming Interfaces).

Question 279.
what are the advantages of Object-Oriented Languages (OOPL)?
Answer:
The Object-Oriented Languages directly represents the real-life objects like car, Jeep, Account, Customer, etc. The features of the 00 programming languages like polymorphism, inheritance, and encapsulation make it powerful.

Question 280.
which would be faster – an application developed in Java or an application developed in C++?
Answer:
An application developed in C++ would be about 30 times faster than Java.

Question 281.
How is Java different from C++?
Answer:
Java is a platform-independent, object-oriented language while C++ is having some of its features from C, which is a procedural language so it is not pure object-oriented. Even Java is not 100% pure object-oriented.

  1. Pointers are supported in C++ while not in Java. The memory management is done automatically with help of a part of the JVM called Garbage Collector.
  2. Multiple inheritances are not supported in Java but supported in C++.
  3. There are no structures and unions in Java. i
  4. There are no scope resolution operators in Java (::).
  5. There are no destructors in Java like C++.
  6. There is no virtual keyword in Java because all non-static method uses the dynamic binding.

Question 282.
How can an animation using images be created with the help of Java?
Answer:
An animation can be created by loading all the images in a browser and displaying them one by one in the paint function.

Question 283.
What is the difference between Java and HTML?
Answer:
Java is a full-fledged object-oriented programming language. It is derived from C++ and shares the same basic syntax as that language. HTML (HyperText Markup Language) is not a programming language. It is simply used as a scripting tool to develop web pages. It is not an editor – it is a simple scripting language that defines how the text and images will appear on the web page. Java is used to create small applications (called applets) that run in the browser. It can also be used to develop full-fledged applications.

Question 284.
What software is needed to learn Java?
Answer:
A Java compiler/development environment such as VJ++ is needed to learn Java.

Question 285.
What are the different int data types provided by Java?
Answer:
The different data types supported by Java are- int, short, long, and byte. The bytewise representations are as follows:

  • byte-8 byte
  • short-16 byte
  • int-32 byte
  • long-64 byte.

Question 286.
Does Java support virtual functions?
Answer:
No, Java does not support virtual functions directly as supported by C++. Virtual functions can be implemented in Java using abstract classes and interfaces. An abstract class is a class with the declaration of methods, but without their implementation. The implementation of the methods takes place in the subclasses. Another example of virtual functions is interfaces. The only difference between an abstract class and an interface is that abstract classes can be used only when they are superclasses and the subclass implements their methods. Whereas in an interface the methods can be implemented even by classes, which are not inherited.

Question 287.
How JAVA achieves platform independence?
Answer:
Java is platform-independent because of the consistent data sizes at all the platforms on which Java code is run. The output of a Java compiler is not an executable code it is bytecode, bytecode is a highly optimized set of instructions designed to be executed by a virtual machine that the Java run-time system emulates. As Java programs are interpreted, rather than compiled it is much easier to run them in a variety of run-time environments.

Question 288.
What is a Java Virtual Machine (JVM)?
Answer:
A Java Virtual Machine is a runtime environment required for the execution of a Java application. Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM. It is JVM which is the crux of ‘platform-independent nature of the language.

Question 289.
What is a JVM consisted of?
Answer:
Each time a Java Application is executed then an instance of JVM, responsible for its running, is created. A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.

Question 290.
What is a class loader and what are its responsibilities?
Answer:
The Classloader is a subsystem of a JVM which is responsible, predominantly for loading classes and interfaces in the system. Apart from this, a class loader is responsible for the following activities:

  1. Verification of imported types (classes and interfaces)
  2. Allocating memory for class variables and initializing them to default values. Static fields for a class are created and these are set to standard default values but they are not explicitly initialized. The method tables are constructed for the class.

Question 291.
What are heap and stack?
Answer:
The heap is the part of the memory of JVM where all objects reside. The stack consists of stack frames. When a thread invokes a method, the JVM pushes a new frame onto that thread’s Java stack. Each stack frame consists of the operand stack and the local variable array.

All arguments, local variables, intermediate computations and return values if any are kept in this stack
corresponding to the method invoked. The stack frame on the top of the stack is called the active stack frame, which is the current place of execution. When the method completes, the virtual machine pops and discards the frame for that method.

Question 292.
How is your Java program executed inside JVM?
Answer:
When JVM executes a Java application, a runtime instance of JVM is bom. This runtime instance invokes a main( ) method of the Java application. The main( ) method of application semes as the starting point for that application’s initial thread. The initial thread can in turn fire off other threads. This thread has a program counter (PC) and Java stack. Whenever the main( ) method is invoked, a stack frame is pushed onto the stack, this then becomes the active tack frame. The program counter in the new Java stack frame will point to the beginning of the method.

If there are more method invocations within the main( ) method then this process of pushing new stack frames onto the stack for each method call is repeated as and when they are invoked. When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame. The PC is set to the instruction after the method call and the method continues.

There is only one heap corresponding to an instance of JVM and all objects created are stored here. This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non-daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application- -the one that begins at main( )–is a non-daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit( ) method of class Runtime or System.
When mainO returns, it terminates the application’s only non-daemon thread, which causes the virtual machine instance to exit.

Question 293.
What is the Java class file’s magic number?
Answer:
A Magic-Number of a class file is a unique identifier for tools to quickly differentiate class files from nonclass files. The first four bytes of each Java class file have the magic value as OxCAFEBABE.And the answer to why this number, I do not actually know but there may be very few sensible and acceptable options possible constructed from letters A-F which can surely not be ‘CAFEFACE’ or ‘FADECAFE’.

Question 294.
How JVM performs Thread Synchronization?
Answer:
JVM associates a lock with an object or a class to achieve multithreading. A lock is like a token or privilege that only one thread can “possess” at any one time. When a thread wants to lock a particular object or class, it asks the JVM.

JVM responds to the thread with a lock may be very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread. If a thread has a lock, no other thread can access the locked data until the thread that owns the lock releases it.

Question 295:
How JVM performs Garbage Collection?
Answer:
One of the most frequently asked questions during interviews and it seeks a precise and clear understanding of the concept. Whenever a reference to an object on heap lies dangling or no longer in use by an active program then it becomes eligible for being garbage collected by JVM. JVM specifications do not force any specific kind of garbage collection algorithm though there are several algorithms like a reference.

Question 296.
How to profile heap usage?
Answer:
Try using -Xaprof to get a profile of the allocations (objects and sizes) of your application.
Also try -agentlib:hprof=heap=all (or other option, try -agentlib:hprof=help for a list) What will you do if VM exits while printing “OutOfMemoryError” and increasing max heap size doesn’t help?
The Java HotSpot VM cannot expand its heap size if memory is completely allocated and no swap space is available. This can occur, for example, when several applications are running simultaneously. When this happens, the VM will exit after printing a message similar to the following.

Exception java. lang. Out Of Memory Error: requested bytes
If you see this symptom, consider increasing the available swap space by allocating more of your disk for virtual memory and/or by limiting the number of applications you run simultaneously. You may also be able to avoid this problem by setting the command-line flags -Xmx and -Xms to the same value to prevent the VM from trying to expand the heap. Note that simply increasing the value of -Xmx will not help when no swap space is available.

Question 297.
What is a Java virtual machine?
Answer:
It is the component of the Java technology responsible for Java’s cross-platform delivery, the small size of its compiled code, and Java’s ability to protect users from malicious programs. The Java Virtual Machine is an abstract computing machine. Like a real computing machine, it has an instruction set and uses various memory areas. It is reasonably common to implement a programming language using a virtual machine.

The Java Virtual machine does not assume any particular implementation technology or host platform. It is not inherently interpreted, and it may just as well be implemented by compiling its instruction set to that of a real CPU, as for a conventional programming language. It may also be implemented in microcode, or directly in silicon.

The Java Virtual Machine knows nothing of the Java programming language, only of a particular file format, the class file format. A class file contains Java Virtual Machine instructions (or bytecodes) and a symbol table, as well as other ancillary information.
For the sake of security, the Java Virtual Machine imposes strong format and structural constraints on the code in a class file. However, any language with functionality that can be expressed in terms of a valid class file can be hosted by the Java Virtual Machine.

Question 298.
What is a classloader?
Answer:
The basics of Java class loaders:
Class loaders are one of the cornerstones of the Java virtual machine (JVM) architecture. They enable the JVM to load classes without knowing anything about the underlying file system semantics, and they allow applications to dynamically load Java classes as extension modules. Describes the behavior of converting a named class into the bits responsible for implementing that class.

Question 299.
What is Byte code verification?
Answer:
The Byte Code Verification Process
What about the concept of a “hostile compiler”? Although the Java compiler ensures that Java source code doesn’t violate the safety rules, when an application such as the HotJava Browser imports a code fragment from anywhere, it doesn’t actually know if code fragments follow Java language rules for safety: the code may not have been produced by a known-to-be trustworthy Java compiler. In such a case, how is the Java run-time system on your machine to trust the incoming byte code stream? The answer is simple: the Java run-time system doesn’t trust the incoming code but subjects it to byte code verification.

The tests range from simple verification that the format of a code fragment is correct, to passing each code fragment through a simple theorem prover to establish that it plays by the rules:

  • it doesn’t forge pointers,
  • it doesn’t violate access restrictions,
  • it accesses objects as what they are (for example, InputStream objects are always used as InputStreams and never as anything else).

A language that is safe, plus run-time verification of generated code, establish a base set of guarantees that interfaces cannot be violated.
The Byte Code Verifier:
The byte code verifier traverses the byte codes, constructs the type state information, and verifies the types of the parameters to all the byte code instructions.

Basic Java Interview Questions in Java chapter 3 img 2

The illustration shows the flow of data and control from Java language source code through the Java compiler, to the class loader and bytecode verifier and hence on to the Java virtual machine, which contains the interpreter and runtime system. The important issue is that the Java class loader and the bytecode verifier make no assumptions about the primary source of the bytecode stream–the code may have come from the local system, or it may have traveled halfway around the planet. The bytecode verifier acts as a sort of gatekeeper: it ensures that code passed to the Java interpreter is in a fit state to be executed and can run without fear of breaking the Java interpreter. Imported code is not allowed to execute by any means until after it has passed the verifier’s tests. Once the verifier is done, a number of important properties are known:

  • There are no operand stack overflows or underflows
  • The types of the parameters of all bytecode instructions are known to always be correct
  • Object field accesses are known to be legal-private, public, or protected While all this checking appears excruciatingly detailed, by the time the bytecode verifier has done its work, the Java interpreter can proceed, knowing that the code will run securely. Knowing these properties makes the Java interpreter much faster because it doesn’t have to check anything. There are no operand-type checks and no stack overflow checks. The interpreter can thus function at full speed without compromising reliability.

Question 300.
How many types of memory areas are allocated by JVM?
Answer:
Many types:

  • Class (Method) Area
  • Heap
  • Stack
  • Program Counter Register
  • Native Method Stack

Question 301.
What is a compilation unit?
Answer:
A compilation unit is a Java source code file.

Question 302.
Should one pool objects to help GC? Should one call System.gc( ) periodically?
Answer:
No!
Pooling objects will cause them to live longer than necessary. The garbage collection methods will be much more efficient if you let it do memory management. The strong advice is to take out object pools.
Don’t call System.gc( ), HotSpot will make the determination of when it’s appropriate and will generally do a much better job.

Question 303.
An application has a lot of threads and is running out of memory, why?
Answer:
You may be running into a problem with the default stack size for threads. In Java SE 6, the default on Sparc is 512k in the 32-bit VM and 1024k in the 64-bit VM. On x86 Solaris/Linux it is 320k in the 32-bit VM and 1024k in the 64-bit VM. On Windows, the default thread stack size is read from the binary (java.exe). As of Java SE 6, this value is 320k in the 32-bit VM and 1024k in the 64-bit VM.
You can reduce your stack size by running with the -Xss option. For example java -server -Xss64k
Note that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by IK or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB.
64k is the least amount of stack space allowed per thread.

Question 304.
If your program is I/O bound or running in native methods, do these activities engage JVM?
Answer:
The answer is ‘No’. If the program is I/O bound or running in native methods, then the VM is not involved in the consumption of CPU time. The VM technology will engage the CPU for running byte codes. Typical examples of time spent not running byte code are graphical operations that make heavy use of native methods, and I/O operations such as reading and writing data to network sockets or database files.

Question 305.
What is the difference between interpreted code and compiled code?
Answer:
An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in the case of Java from byte codes. The scripting languages like JavaScript, Python, etc. require an Interpreter to execute them. So a program written in scripting language will directly be executed with an interpreter installed on that computer, if it is absent then this program will not execute. While in the case of compiled code, an assembler or a virtual machine in the case of Java is required to convert assembly-level code or byte codes into machine-level instructions/commands. Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise.

Question 306.
Why Java-based GUI intensive program has performance issues?
Answer:
GUI intensive Java application mostly runs underlying OS-specific native libraries which is time and more CPU cycles consuming.
The overall performance of a Java application depends on four factors:

  • The design of the application
  • The speed at which the virtual machine executes the Java bytecodes
  • The speed at which the libraries that perform basic functional tasks execute (in native code)
  • The speed of the underlying hardware and operating system

The virtual machine is responsible for byte code execution, storage allocation, thread synchronization, etc. Running with the virtual machine are native code libraries that handle input and output through the operating system, especially graphics operations through the window system. Programs that spend significant portions of their time in those native code libraries will not see their performance on HotSpot improved as much as programs that spend most of their time executing byte codes.

Question 307.
What is 64 bit Java?
Answer:
A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. The primary advantage of running Java in a 64-bit environment is the larger address space.

This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.

Within the parts of the SDK written in Java, things are simpler since Java specifies the sizes of its primitive data types precisely. However, even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.

Question 308.
What is the difference between JVM and JRE?
Answer:
A Java Runtime Environment (JRE) is a prerequisite for running Java applications on any computer. A JRE contains a Java Virtual Machine (JVM), all standard, core java classes, and runtime libraries. It does not contain any development tools such as compiler, debugger, etc. JDK (Java Development Kit) is a whole package required for Java Development which essentially contains JRE+JVM, and tools required to compile and debug, execute Java applications.

Question 309.
What is Hot Java?
Answer:
Hot Java is a Browser provided by Sun. It is a modular, applet-aware, extensible World Wide Web browser written entirely in Java. The security in Hot Java provides a safe environment for the execution of imported code. The security is based on interlocking layers of security that range from the design of the Java language at the base to the file and network access protections at the top.

Question 310.
What are the differences between JRE And JVM AND JDK?
Answer:
The “JDK” is the Java Development Kit. I.e., the JDK is a bundle of software that you can use to develop Java-based software. The “JRE” is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.

Question 311.
Give the simplest way to find out the time a method takes for execution without using any profiling tool?
Answer:
Read the system time just before the method is invoked and immediately after the method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…

long start = System.currentTimeMillis ( ); 
method ( );
long end = System.currentTimeMillis ( );

System.out.println (“Time taken for execution is” + (end – start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing a considerable amount of processing.

Question 312.
What is a package?
Answer:
A package stores a group of related classes and interfaces. They eliminate the conflicts in class names in a different groups of classes.

Question 313.
When can an object reference be cast to an interface reference?
Answer:
An object reference is cast to an interface reference when the object implements the referenced interface.

Question 314.
Which class is extended by all other classes?
Answer:
The Object class is extended by all other classes.

Question 315.
Can an object be garbage collected while it is still reachable?
Answer:
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

Question 316.
Is the ternary operator written x:y? z or x? y:z?
Answer:
It is written x? y: z.

Question 317.
How is rounding performed under integer division?
Answer:
The fractional part of the result is truncated. This is known as rounding toward zero.

Question 318.
What is the purpose of the System class?
Answer:
The purpose of the System class is to provide access to system resources.

Question 319.
Is &&= a valid Java operator?
Answer:
No, it is not.

Question 320.
What modifiers may be used with an interface declaration?
Answer:
An interface may be declared as public or abstract.

Question 321.
Is a class a subclass of itself?
Answer:
A class is a subclass of itself.

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

Question 323.
What is the difference between static and non-static variables?
Answer:
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.

Question 324.
Which Math method is used to calculate the absolute value of a number?
Answer:
The abs( ) method is used to calculate absolute values.

Question 325.
When does the compiler supply a default constructor for a class?
Answer:
The compiler supplies a default constructor for a class if no other constructors are provided.

Question 326.
If a method is declared as protected, where may the method be accessed?
Answer:
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

Question 327.
Which non-Unicode letter characters may be used as the first character of an identifier?
Answer:
The non-Unicode letter characters $ and _ may appear as the first character of an identifier.

Question 328.
What restrictions are placed on method overloading?
Answer:
Two methods may not have the same name and argument list but different return types.

Question 329.
What is casting?
Answer:
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Question 330.
What is the return type of a program’s main() method?
Answer:
A program’s main() method has a void return type.

Question 331.
What if the static modifier is removed from the signature of the main method?
Answer:
Program compiles. But at runtime throws an error “NoSuchMethodError”.

Question 332.
What is the difference between a field variable and a local variable?
Answer:
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

Question 333.
Under what conditions is an object’s finalize( ) method invoked by the garbage collector?
Answer:
The garbage collector invokes an object’s finalize( ) method when it detects that the object has become unreachable.

Question 334.
How is this ( ) and super ( ) used with constructors?
Answer:
this( ) is used to invoke a constructor of the same class. super( ) is used to invoke a superclass constructor.

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

Question 336.
How are these and super used?
Answer:
this is used to refer to the current object instance, super is used to refer to the variables and methods of the superclass of the current object instance.

Question 337.
What is a compilation unit?
Answer:
A compilation unit is a Java source code file.

Question 338.
What restrictions are placed on method overriding?
Answer:
Overridden methods must have the same name, argument first, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

Question 339.
Can an abstract class be final?
Answer:
An abstract class may not be declared as final.

Question 340.
What is numeric promotion?
Answer:
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

Question 341.
What is the difference between a public and a non-public class?
Answer:
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

Question 342.
What is a pointer? Does Java support pointers?
Answer:

  1. Pointer means a reference handle to a memory location.
  2. Java doesn’t support the use of pointers as their improper handling causes memory leaks and compromises reliability.

Question 343.
Differentiate between Path and Classpath?
Answer:

  • Path and Classpath both are operating system-level environment variables.
  • Path tells where the system can find the executable (.exe) files while classpath provides the location .class files.

Question 344.
Is it necessary to declare the main( ) method compulsorily in all java classes?
Answer:

  • No, it is not.
  • the main( ) method needs to be defined only if the source class is a java application.

Question 345.
What modifiers may be used with a top-level class?
Answer:
A top-level class may be public, abstract, or final.

Question 346.
What are the Object and Class classes used for?
Answer:
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

Question 347.
Can an unreachable object become reachable again?
Answer:
An unreachable object may become reachable again. This can happen when the object’s finalize( ) method is invoked and the object performs an operation that causes it to become accessible to reachable objects.

Question 348.
Isa class a subclass of itself?
Answer:
A class is a subclass of itself.

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

Question 350.
How would you pass a java integer by reference to another function?
Answer:
Passing by reference is impossible in JAVA but Java supports the object reference so. The object is the only way to pass the integer by reference.

Question 351.
What is data encapsulation? What does it buy you?
Answer:
The most common example I can think of is a JavaBean. Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class that is used to access the fields of the object. Typically the fields are made private while the get and set methods are public.
Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using JavaBeans in Struts, for instance).

Question 352.
Can we declare multiple main() methods in multiple classes? I.e. can we have each main method in its class in our program?
Answer:
YES

Question 353.
Why are multiple inheritances not possible in Java?
Answer:
It depends on how you understand “inheritance”. Java can only “extends” one superclass, but can “implements” many interfaces; that doesn’t mean multiple inheritances is not possible. You may use interfaces to make inheritance work for you. Or you may need to workaround. For example, if you cannot get a feature from a class because your class has a superclass already, you may get that class’s feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritances in Java are possible.

Question 354.
Can Java code be compiled to machine-dependent executable files?
Answer:
Yes. There are many tools out there. If you did so, the generated Exe file would be run in the specific platform, not cross-platform.

Question 355.
What are the drawbacks of inheritance? (donated by RS in Mar. 2005)
Answer:
Since inheritance inherits everything from the superclass and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situations. In addition, the inheritance may make peers hardly understand your code if they don’t know how your super-class acts.
Usually, when you want to use a functionality of a class, you may use a subclass to inherit such function or use an instance of this class in your class. Which is better, depends on your specification.

Question 356.
Is there any other way that you can achieve inheritance in Java
Answer:
There are a couple of ways. As you know, the straight way is to “extends” and/or “implements”. The other way is to get an instance of the class to achieve the inheritance. That means to make the supposed-super-class be a field member. When you use an instance of the class, actually you get every function available from this class, but you may lose the dynamic features of OOP.

Question 357.
Can a private method of a superclass be declared within a subclass?
Answer:
Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. There is no way for private stuff to have runtime overloading or overriding (polymorphism) features.

Question 358.
What is a platform?
Answer:
A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and macOS.

Question 359.
What is the main difference between the Java platform and other platforms?
Answer:
The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:

a) The Java Virtual Machine (Java VM)
b) The Java Application Programming Interface (Java API)

Question 360.
What is the Java Virtual Machine?
Answer:
The Java Virtual Machine is software that can be ported onto various hardware-based platforms.

Question 361.
What is the Java API?
Answer:
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

Question 362.
What is native code?
Answer:
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

Question 363.
Is Java code slower than native code?
Answer:
Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.

Question 364.
Can main( ) method be overloaded?
Answer:
Yes. the main( ) method is a special method for a program entry. You can overload main( ) method in any ways. But if you change the signature of the main method, the entry point for the program will be gone. For example:

//the following are legal methods for entry point
 public static void main(String[] args) { } // standard 
static public void main(String[] args) { } // unconventional
 private static void main(String[] args) { } // unconventional 
//the following are legal overloaded methods 
public static int main(string arg) { } 
public void main(string strl, string str2) { } 
public String mainfstring arg, int i) { }

For good practice, don’t overload the main method or use a similar main method in a class which is not served as an entry point for your program.

Question 365.
How does Java handle integer overflows and underflows?
Answer:
It uses those low-order bytes of the result that can fit into the size of the type allowed by the operation.

Question 366.
What modifiers may be used with an inner class that is a member of an outer class?
Answer:
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

Question 367.
If a method is declared as protected, where may the method be accessed?
Answer:
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

Question 368.
What are wrapped, classes?
Answer:
Wrapped classes are classes that allow primitive types to be accessed as objects.

Question 369.
If I don’t provide any arguments on the command line, then the String array of the Main method will be empty or null?
Answer:
It is empty. But not null.

Question 370.
What is the difference between the Boolean & operator and the && operator?
Answer:
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why give details as above.

Question 371.
What is the purpose of the Runtime class?
Answer:
The purpose of the Runtime class is to provide access to the Java runtime system.

Question 372.
What is the purpose of the System class?
Answer:
The purpose of the System class is to provide access to system resources.

Question 373.
What must a class do to implement an interface?
Answer:
It must provide all of the methods in the interface and identify the interface in its implements clause.

Question 374.
What is a static method?
Answer:
A static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even requires that any objects of the class have been instantiated.

Question 375.
What is a protected method?
Answer:
A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.

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

Question 377.
When can an object reference be cast to an interface reference?
Answer:
An object reference is cast to an interface reference when the object implements the referenced interface.

Question 378.
What if the main method is declared private?
Answer:
The program compiles properly but at runtime, it will give a “Main method not public.” message.

Question 379.
What if the static modifier is removed from the signature of the main method?
Answer:
Program compiles. But at runtime throws an error “NoSuchMethodError”.

Question 380.
What if I write static public void instead of the public static void?
Answer:
The program compiles and runs properly.

Question 381.
What if I do not provide the String array as the argument to the method?
Answer:
Program compiles but throws a runtime error “NoSuchMethodError”.

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

Question 383.
If 1 does not provide any arguments on the command line, then the String array of the Main method will be empty or null?
Answer:
It is empty. But not null.

Question 384.
How can one prove that the array is not null but empty using one line of code?
Answer:
Print args. length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args. length.

Question 385.
What environment variables do I need to set on my machine in order to be able to run Java programs?
Answer:
CLASSPATH and PATH are the two variables.

Question 386.
Can an application have multiple classes having the main method?
Answer:
Yes, it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is no conflict amongst the multiple classes having a main method.

Question 387.
Can I have multiple main methods in the same class?
Answer:
No, the program fails to compile. The compiler says that the main method is already defined in the class.

Question 388.
Do I need to import java.lang package any time? Why?
Answer:
No. It is by default loaded internally by the JVM.

Question 389.
Can I import the same package/class twice? Will the JVM load the package twice at runtime?
Answer:
One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

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

Question 391.
Does a class inherit the constructors of its superclass?
Answer:
A class does not inherit constructors from any of its superclasses.

Question 392.
Which class should you use to obtain design information about an object?
Answer:
The Class class is used to obtain information about an object’s design.

Question 393.
What are the problems faced by Java programmers who don’t use layout managers?
Answer:
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

Question 394.
What is the difference between static and non-static variables?
Answer:
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.

Question 395.
What restrictions are placed on method overloading?
Answer:
Two methods may not have the same name and argument list but different return types.

Question 396.
What restrictions are placed on method overriding?
Answer:
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

Question 397.
What is casting?
Answer:
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Question 398.
How is this( ) and super( ) used with constructors?
Answer:
this( ) is used to invoke a constructor of the same class. super( ) is used to invoke a superclass constructor.

Question 399.
How is it possible for two String objects with identical values not to be equal under the == operator?
Answer:
The = operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located in different areas of memory.

Question 400.
Does importing a package import the subpackages as well? e.g. Does import com.MyTest.* also import com.MyTest.UnitTests.*?
Answer:
No, you will have to import the subpackages explicitly. Importing com.
MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackage.

Question 401.
What is the difference between declaring a variable and defining a variable?
Answer:
In a declaration, we just mention the type of the variable and its name. We do not initialize it. But defining means declaration + initialization, e.g String s; is just a declaration while String s = new String (“abed”), Or String s = “abed”; are both definitions.

Question 402.
is the default value of an object reference declared as an instance variable?
Answer:
null unless we define it explicitly.

Question 403.
Can a top-level class be private or protected?
Answer:
No. A top-level class cannot be private or protected. It can have either “public” or no modifier. If it does not have a modifier it is supposed to have default access. If a top-level class is declared as private the compiler will complain that the “modifier private is not allowed here”. This means that a top-level class cannot be private. The same is the case with protection.

Question 404.
What type of parameter passing does Java support?
Answer:
In Java, the arguments are always passed by value.

Question 405.
Primitive data types are passed by reference or pass by value?
Answer:
Primitive data types are passed by value.

Question 406.
Objects are passed by value or by reference?
Answer:
Java only supports pass-by values. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Question 407.
What is a Java package and how is it used?
Answer:
A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

Question 408.
What are the Object and Class classes used for?
Answer:
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

Question 409.
How does the object-oriented approach help us keep the complexity of software development under control?
Answer:
We can discuss such issues from the following aspects:

  • Objects allow procedures to be encapsulated with their data to reduce potential interference.
  • Inheritance allows well-tested procedures to be reused and enables changes to make once and have an effect in all relevant places.
  • The well-defined separations of interface and implementation allow constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

Question 410.
What is design by contract?
Answer:
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the postconditions.

In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

Question 411.
What is the benefit of subclass?
Answer:
Generally:

  • The sub-class inherits all the public methods and the implementation.
  • The sub-class inherits all the protected methods and their implementation.
  • The sub-class inherits all the default(non-access modifier) methods and their implementation.
  • The subclass also inherits all the public, protected, and default member variables from the superclass.
  • The constructors are not part of this inheritance model.

Question 412.
Where and how can you use a private constructor.
Answer:
A private constructor can be used if you do not want any other class to instantiate it by using new. The instantiation is done from a static public method, which is used when dealing with the factory method pattern.

Question 413.
In System.out.println( ),what is System,out and println,pls explain?
Answer:
The system is a predefined final class, out is a PrintStream object acting as a field member and println is a built-in overloaded method in the out object.

Question 414.
What is meant by “Abstract Interface”?
Answer:
First, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods.

Question 415.
Can you make an instance of an abstract class? For example – java.util. A calendar is an abstract class with a method get instance( ) which returns an instance of the Calendar class.
Answer:
No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method that has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.

Question 416.
What is the output of x<y? a:b = p*q when x=l,y=2,p=3,q=4?
Answer:
When this kind of question has been asked, find the problems you think are necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x<y? a:(b=p*q); the return value would be variable a because the x is 1 and less than y = 2; the x < y statement return true and variable a is returned.

Question 417.
Why Java does not support pointers?
Answer:
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.

Question 418.
Why can’t I say just absO or sin() instead of Math.abs( ) and Math.sin( )?
Answer:
The import statement does not bring methods into your local namespace. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local namespace. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.

Question 418.
are there no global variables in Java?
Answer:
Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings- of the global variables), State variables lessen the cohesion of a program:

you need to know more to understand how something works. A major point of Object-Oriented programming is to break up the global states into more easily understood collections of local states, when you add one variable; you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.

Question 419.
What does it mean that a class or member is final?
Answer:
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations and makes thread safety a little easier to achieve. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too.

However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;

Question 420.
What does it mean that a method or class is abstract?
Answer:
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:

public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually 
implemented in the current class, it exists only to be overridden in subclasses, it has nobody. 
For example, public abstract float price( );

Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

Question 421.
Describe what happens when an object is created in Java?
Answer:
Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from the heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation- specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses.

This process continues until the constructor for java. lang.The object is called, as java.lang.The object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and the constructor for the most derived class completes last.

Question 422.
What is the difference between instanceof and instance?
Answer:
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstanceO Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

Question 423.
Why there are no global variables in Java?
Answer:
Global variables are globally accessible. Java does not support globally accessible variables due to the following reasons:

  • The global variables break the referential transparency
  • Global variables create collisions in the namespace.

Question 424.
What is a heap in Java?
Answer:
JAVA is a fully Object-oriented language. It has two phases first one is the Compilation phase and the second one is the interpretation phase. The Compilation phase converts the java file to a class file (byte code is the only readable format of JVM) then the Interpretation phase interoperate the class file fine by fine and gives the proper result.

Question 425.
How are memory leaks possible in Java?
Answer:
If any object variable is still pointing to some object which is of no use, then JVM will not garbage collect that object and object will remain in memory creating a memory leak

Question 426.
What would happen if you say this = null
Answer:
this will give a compilation error as follows cannot assign value to final variable this

Question 427.
How would you pass a java integer by reference to another function?
Answer:
Passing by reference is impossible in JAVA but Java supports the object reference so the object is the only way to pass the integer by reference.

Question 428.
Do multiple inheritances in Java
Answer:
It’s not possible directly. That means this feature is not provided by Java, but it can be achieved with the help of Interface. By implementing more than one interface.

Question 429.
What is data encapsulation? What does it buy you?
Answer:
The most common example I can think of is a JavaBean. Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class that is used to access the fields of the object. Typically the fields are made private while the get and set methods are public.
encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using JavaBeans in Struts, for instance).

Question 430.
Can we define a class inside the interface?
Answer:
Yes, of course! If we define a class inside the interface, the java compiler creates a static nested class. Let’s see how can we define a class within the interface:

interface M{ 
class A{ }
}

Question 431.
How can you free memory?
Answer:
With the help of finalize( ) method.
If a programmer really wants to explicitly request a garbage collection at some point, System.gc( ) or Runtime.gc( ) can be invoked, which will fire off a garbage collection at that time.

Question 432.
Does java do reference counting?
Answer:
It is more likely that the JVMs you encounter in the real world will use a tracing algorithm in their garbage-collected heaps.

Question 433.
What does a static inner class mean? How is it different from any other static member?
Answer:
A static inner class behaves like any “outer” class. It may contain methods and fields.
It is not necessarily the case that an instance of the outer class exists even when we . have created an instance of the inner class. Similarly, instantiating the outer class does not create any instances of the inner class.
The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access field x, but it cannot access field y.

Question 434.
How do you declare constant values in java?
Answer:
Using the Final keyword we can declare the constant values. The final member can be instantiated only at the time of declaration. Null.

Question 435.
Can we declare a static variable inside a method?
Answer:
No, static variables can’t be declared inside a method otherwise the class will not compile.

Question 436.
Tell us something about different types of casting?
Answer:
There are two types of casting:

a) Casting between primitive numeric types
b) Casting between object references.
♦ Casting between numeric types is used to convert larger values into smaller values. For e.g. double values to byte values.
♦ Casting between object references helps you refer to an object by a compatible class, interface, or array type reference.

Question 437.
What is Downcasting?
Answer:
Downcasting means casting from a general to a more specific type.

Question 438.
What do you mean by order of precedence and associativity?
Answer:

  • Order of precedence: It determines the order in which the operators in an expression should be evaluated.
  • Associativity: It determines whether an expression should be evaluated left-to-right or right-to-left.

Question 439.
If a class is declared without any access modifiers, where can the class be accessed?
Answer:

  • A class declared without any access modifiers is said to have package access.
  • Such a class can only be accessed by other classes and interfaces defined within the same package.

Question 440.
How do constructors use this( ) and super( )?
Answer:

  • this( ) is used to refer to another constructor in the same class with a different parameter list.
  • super( ) is used to invoke the superclass’s constructor.

Question 441.
Explain numeric promotion?
Answer:

  • conversion of a smaller numeric type to a larger numeric type is called numeric promotion.
  • This helps in carrying out integer and floating-point operations.
  • Byte, char, and short values are converted to int values in the numeric promotion.
  • int values are converted to long values if required.
  • The long and float values are converted to double values if required.

Question 442.
What is the final modifier?
Answer:
The final modifier keyword is that the programmer cannot change the value anymore.
Following is what happens when it is applied to classes, variables, or methods.

  • final Classes- A final class cannot have subclasses.
  • final Variables- Once initialized, a final variable cannot be changed.
  • final Methods- A final method cannot be overridden by subclasses.

Question 443.
What are the restrictions imposed on method overriding?
Answer:

  • Overridden methods must have the same name, argument list, and return type.
  • The overriding method cannot limit the access of the method overridden.
  • The overriding method cannot throw any exceptions that overridden method doesn’t throw.

Question 444.
What restrictions are placed on method overriding?
Answer:
The restriction on method overloading is the signature of the method.

  • The signature is the number, type, and order of the arguments passed to a method.
  • Overridden methods must have the same name, argument list, and return type.
  • Any method which has the same name cannot have the same signature.
  • They can have the same return types in the same scope.
  • The compiler uses the signature to detect which overloaded method to refer to when an overloaded method is called.
  • If two methods have the same name and signature the compiler will throw a runtime error.

Question 445.
Can I import the same package/class twice? Will the JVM load the package twice at runtime?
Answer:
One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. But the JVM will internally load the class only once no matter how many times you import the same class.

Question 446.
What is static import?
Answer:
By static import, we can access the static members of a class directly, there
is no to qualify it with the class name.
Static Import:
The static import feature of Java 5 facilitates the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.
Advantage of static import:
• Less coding is required if you have access to any static member of a class often.
The disadvantage of static import:
• If you overuse the static import feature, it makes the program unreadable and unmaintainable.
Simple Example of static import

import static java.lang.System.*;
class staticimportExample{
public static void main(String args[ ]){
           out.println(“Hello”);//Now no need of system.out
           out.println(“Java”);
    }
}

Output: Hello Java

Question 447.
What is the difference between import and static import?
Answer:
The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows accessing the static members of a class without the class qualification. The import provides accessibility to classes and interfaces whereas static import provides accessibility to static members of the class.

Question 448.
Name few Design Patterns used for designing Java applications?
Answer:
Singleton, Factory, Abstract Factory, Proxy, Command, Builder.

Question 449.
Explain the use of the “Native” keyword?
Answer:
Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language.

Question 450.
Difference between implicit and explicit typecasting?
Answer:
An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in the case of implicit type casting you need not provide the data type.

Question 451.
What is reflection?
Answer:
Reflection is the process of examining or modifying the runtime behavior of a class at runtime. lt is used in:

  • IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans.
  • Debugger
  • Test Tools etc.

Question 452.
Can you access the private method from outside the class?
Answer:
Yes, by changing the runtime behavior of a class if the class is not secured.

Question 453.
What will happen if the static modifier is removed from the signature of the main method?
Answer:
The program throws a “NoSuchMethodError” error at runtime.

Question 454.
Name Wrapper classes available for primitive types?
Answer:
boolean :      java.lang.Boolean
byte       :      java.lang.Byte
char       :      java.lang.Character
double   :     java.lang.Double
float       :     java.lang.Float
int          :     java.lang.Integer
long       :     java.lang.Long
short      :     java.lang.Short
void       :     java.lang.Void

Question 455.
Why do we need wrapper classes?
Answer:
It is sometimes easier to deal with primitives as objects. Moreover, most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these reasons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also, we can pass them around as method parameters where a method expects an object.

Question 456.
What is an immutable class?
Answer:
An immutable class is a class that once created; its contents cannot be changed. Immutable objects are objects whose state cannot be changed once constructed. E.g. String class.

Question 457.
How to create an immutable class?
Answer:
To create an immutable class following steps should be followed:
1. Create a final class.
2. Set the values of properties using the constructor only.
3. Make the properties of the class final and private
4. Do not provide any setters for these properties.
5. If the instance fields include references to mutable objects, don’t allow those objects to be changed:

1. Don’t provide methods that modify the mutable objects.
2. Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Ex:

public final class Finalpersonclass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
super( );
this.name = name;
this.age = age;
}
public int getAge( ) {
return age;
}
public String getName( ) {
return name;
}
}

Question 458.
Immutable objects are automatically thread-safe -true/false?
Answer:
True. Since the state of the immutable objects cannot be changed once they are created they are automatically synchronized/thread-safe.

Question 459.
Which classes in java are immutable?
Answer:
All wrapper classes in java. lang are immutable – String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, Biglnteger

Question 460.
What are the advantages of immutability?
Answer:
The advantages are:

  1. Immutable objects are automatically thread-safe; the over ad caused due to the use of synchronization is avoided.
  2. Once created the state of the immutable object cannot be changed so there is no possibility of them getting into an inconsistent state.
  3. The references to the immutable objects can be easily shared or cached without having to copy or clone them as their state cannot be changed ever after construction.
  4. The best use of immutable objects is as the keys of a map.

Question 461.
How does Java allocate stack and heap memory?
Answer:
Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack if they are local method variables and in the heap, if they are member variables (i.e. fields of a class).
In Java methods, local variables are pushed into the stack when a method is invoked and the stack pointer is decremented when a method call is completed.

In a multi-threaded application, each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is thread-safe (each thread will have its own stack) but the heap is not thread-safe unless guarded with synchronization through your code.