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.

J2EE & XML Interview Questions in Java

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

J2EE & XML Interview Questions in Java

Question 1.
What is J2EE?
Answer:
J2EE is a standard for building enterprise applications. It includes technologies for implementing business logic, database access, message exchange, transaction management, web requests processing, and many other features. The main approach of J2EE is separating presentation level from business logic (lightweight client applications) and business logic from data storage (application level of n-tier architecture).
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

Question 2.
Are J2EE applications portable and scalable?
Answer:
Nowadays industry requires portable and scalable information systems to stay in touch with the rapidly changing world. J2EE applications proved the right to be called portable, because of the platform independence of Java. J2EE applications can be developed at home and deployed to a multiprocessor server cluster. Object-oriented approach for application design makes applications scalable and easy to maintain.

Question 3.
What makes J2EE suitable for distributed multitiered Applications?
Answer:
The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:

  • Client-tier components run on the client machine.
  • Web-tier components run on the J2EE server.
  • Business-tier components run on the J2EE server.
  • Enterprise information system (ElS)-tier software runs on the EIS server.

Question 4.
What are the components of the J2EE application?
Answer:
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

  1. Application clients and applets are client components.
  2. Java Servlet and JavaServer Pages technology components are web components.
  3. Enterprise JavaBeans components (enterprise beans) are business components.
  4. Resource adapter components provided by EIS and tool vendors.

Question 5.
What do Enterprise JavaBeans components contain?
Answer:
Enterprise JavaBeans components contain Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All . the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.

Question 6.
Is the J2EE application only web-based?
Answer:
No, It depends on the type of application that client wants. A J2EE application can be web-based or non-web-based, if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as the J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When a user requests, it can open an HTTP connection to establish communication with a servlet running in the web tier.

Question 7.
Are JavaBeans J2EE components?
Answer:
No. JavaBeans, components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation but should conform to the naming and design conventions outlined in the JavaBeans component architecture.

Question 8.
Is an HTML page a web component?
Answer: No. Static HTML pages and applets are bundled with web components during application assembly but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.

Question 9.
What can be considered as a web component?
Answer:
J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.

Question 10.
What is the container?
Answer:
Containers are the interface between a component and the low-level platform-specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.

Question 11.
What are container services?
Answer:
A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.

Question 12.
What is the web container?
Answer:
Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of the JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.

Question 13.
What is Enterprise JavaBeans (EJB) container?
Answer:
It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server.

Question 14.
What is an Applet container?
Answer:
manages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.

Question 15.
How do we package J2EE components?
Answer:
J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean, Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules have their own deployment descriptor. A deployment descriptor is an XML document with a .xml extension that describes a component’s deployment settings.

Question 16.
What is the life cycle (J2EE component)?
Answer:
The framework events of a J2EE component’s existence. Each type of component has to define events that mark its transition into states in which it has varying availability for use. For example, a servlet is created and has its init method called by its container before the invocation of its service method by clients or other servlets that require its functionality. After the call of its init method, it has the data and readiness for its intended use. The servlet’s destroy method is called by its container before the ending of its existence so that processing associated with winding up can be done and resources can be released.

The init and destroy methods in this example are callback methods. Similar considerations apply to the life cycle of all J2EE component types: enterprise beans, Web components (servlets or JSP pages), applets, and application clients.

Question 17.
What is a thin client?
Answer:
A thin client is a lightweight interface to the application that does not have such operations as query databases, execute complex business rules, or connect to legacy applications.

Question 18.
What are the types of J2EE clients?
Answer:
Following are the types of J2EE clients:

  • Applets
  • Application clients
  • Java Web Start-enabled rich clients, powered by Java Web Start technology.
  • Wireless clients, based on Mobile Information Device Profile (MIDP) technology.

Question 19.
What is a deployment descriptor?
Answer:
A deployment descriptor is an Extensible Markup Language (XML) text-based file with a .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules have their own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At the run time; the J2EE server reads the deployment descriptor and acts upon the component accordingly.

Question 20.
What is the EAR file?
Answer:
An EAR file is a standard JAR file with a .ear extension, named from the Enterprise ARchive file. A J2EE application with all of its modules is delivered in an EAR file.

Question 21.
What are JTA and JTS?
Answer:
JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly.

Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high-level transaction interface that your application uses to control transactions, and JTS is a low-level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.

Question 22.
What is JAXP?
Answer:
JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulates access to it, discovers the operations available on it, and creates the appropriate JavaBeans component to perform those operations.

Question 23.
What is J2EE Connector?
Answer:
The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.

Question 24.
What is JAAP?
Answer:
The Java Authentication and Authorization Service (JAAS) provide a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.

Question 25.
What is Java Naming and Directory Service?
Answer:
The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS.

Question 26.
What is the J2EE application?
Answer:
Any deployable unit of J2EE functionality. This can be a single J2EE module or a group of modules packaged into an EAR file along with a J2EE application deployment descriptor. J2EE applications are typically engineered to be distributed across multiple computing tiers.

Question 27.
What is the J2EE component?
Answer:
A self-contained functional software unit supported by a container and configurable at deployment time. The J2EE specification defines the following J2EE components: Application clients and applets are components that run on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components that run on the server.

Enterprise JavaBeans (E JB) components (enterprise beans) are business components that run on the server. J2EE components are written in the Java programming language and are compiled in the same way as any program in the language. The difference between J2EE components and “standard” Java classes is that J2EE components are assembled into a J2EE application, verified to be well-formed and in compliance with the J2EE specification, and deployed to production, where they are run and managed by the J2EE server or client container.

Question 28.
What is the J2EE module?
Answer:
A software unit that consists of one or more J2EE components of the same container type and one deployment descriptor of that type. There are four types of modules: EJB, Web, application client, and resource adapter. Modules can be deployed as stand-alone units or can be assembled into a J2EE application.

Question 29.
What is the J2EE product?
Answer:
An implementation that conforms to the J2EE platform specification.

Question 30.
What is a J2EE product provider?
Answer:
A vendor that supplies a J2EE product.

Question 31.
What is the J2EE server?
Answer:
The runtime portion of a J2EE product. A J2EE server provides EJB or Web containers or both.
Question 32.
Explain J2EE architecture.
Answer:
The JEE platform provides the environment to develop enterprise applications/services using multitier architecture. The highly intensified technology made the need for scalable, efficient, faster solutions for information management. The JEE technology is rightly apt for meeting these requirements. JEE provides a programming development environment that improves the productivity of development, standards for hosting/deploying enterprise applications. The following are the tiers in JEE application
Client Tier: The client tier includes the web components such as Servlets, JSP, or standalone Java desktop applications. This tier provides dynamic interfaces to the middle tier.
• Middle Tier: This is also called the server tier. In the middle tier, enterprise beans and web services encapsulate distributable business logic for the applications which are reusable. The JEE application server contains the server-tier components which provide the platform for these web components for actions to be performed and data to be stored/persisted.
• Enterprise data tier: The enterprise-level data is stored/persisted preferably or typically in a relational database, in this tier.
The JEE applications comprise components, containers, and services. All the web components (Servlets, JSP) provide dynamic requests and responses from a web page. The EJB components contain the server-side business logic for enterprise applications.
Question 33.
J2EE is a container-centric architecture. Explain.
Answer:
A container acts as an interface between a platform-specific functionality and a component. The component must be assembled before a web or enterprise bean or application client component execution, into a JEE application and deployed into its container.
The settings of a container can be customized for underlying support provided by the JEE server. These include security, transaction management, and Java Naming and Directory Interface lookups.
The management of nonconfigurable services such as servlet life cycle, enterprise bean life cycle, database connection, data persistence, database connection pooling also can be done by the container.
Question 34.
Explain the four types of containers that the J2EE specification defines.
Answer:
A container is a runtime support of a system-level entity [Applet, Servlet/ JSP, EJB] The four types of containers that the J2EE specification defines are applet container, application-client container, web container, and EJB container.
Applet Container: An applet is a java program that can be embedded into a web page. Most of the web pages are authored in HTML. To use an applet in HTML document, the tags <APPLET> and </APPLET> are used. They are used to indicate to the browser that a java applet should be loaded. “These tags act as a container for the java applet definition. “ Applet container manages the execution of applet and contains the web browser.
Application-client Container: The Application Client Container (ACC) is a combination of Java classes, libraries, and other files. They are used to distribute along with Java client programs that execute on their own JVM. The execution of the application client components is managed by the application-client container. The ACC can take the responsibility to collect user name and password which is treated as authentication data.
Web Container: A web container is a part of the webserver. It provides the run time environment to execute a web application such as a servlet, JSP. A servlet container translates the URL requests into servlet requests. The JSP implicit objects such as request, response, out, page, pageContext, etc., are exposed by the JSP container.
EJB Container: The EJB container, like other containers, provides a run-time environment to execute EJB components such as enterprise beans. An EJB container manages transactions, state management details, multi-threading, connection pooling. The applications are provided with security using an EJB container. All database access required by the entity bean will be handled by the EJB container.
Question 35.
Explain the J2EE container architecture.
Answer:
J2EE Container Architecture:
The J2EE application components need support at runtime. This support is provided by J2EE containers. They use protocols, methods of the containers to access other application components. The containers of J2EE are 1) Web container 2) EJB container.
1) The web container is used to host web applications. It provides the run time environment to execute Servlet and JSP component types.
2) The business logic is dealt with by the server components called EJB components. Access to local and remote enterprise beans is provided by the EJB container. The operations of the three beans namely Entity Bean, Session Bean, and Message-driven bean are handled by the EJB Container.
Question 36.
Explain the technologies that the J2EE platform provides for developing components.
Answer:
1) Servlet Technology: It is considered the foundation of web technologies. It overcomes the limitations of CGI technology. It is a server-side component to serve the clients and generate dynamic content. Servlets interacts with web clients using the paradigm request-response. All client requests are sent through web servers to the servlet container. The servlet then processes the request and sends the response back to the client. Servlets are reliable, scalable, efficient, and reusable server-side components.
2) JSP Technology: It is the extension of servlet technology. It is easy to author JSP without much knowledge of the supporting API. JSP can be used to work with HTTP requests and HTTP responses, session management, and so on. It is easy to combine both static and dynamic content with JSP. The factor to develop JSP technology is to use regular HTML tags. The JSP author can place servlet or simple java code on the page by using specially designated tags. The entire JSP will be translated into Servlet and the servlet-related code is communicated to the container to run.
3) EJB Technology: EJB is a server-side web component. It depends on other Java technologies for proper functionality such as Remote Method Invocation. RMI is used as a protocol between 2 enterprise beans and between an enterprise bean and its client. EJB encapsulates the business logic. All EJBs are developed, deployed, and run only in an EJB container. This is similar to servlets and JSP run in a web container.
EJB applications are easy to develop because the applications developer can concentrate on business logic. The developer can utilize the services provided by the EJB container, like connection pooling and transactions.
Question 37.
Explain the J2EE APIs, i.e. RMI/IIOP, JNDI, JDBC, Java Mail, and JMS.
Answer:
RMI/IIOP: RMI stands for Remote Method Invocation. HOP stands for Inter Internet-ORB Protocol. ORB
RMI/IIOP API is used to write distributed objects using Java technology, which enables the communication between objects in the memory, across JVM and also physical devices.
RMI/IIOP yields the benefits of OOP such as inheritance, polymorphism, and encapsulation and is platform-independent. In RMI/IIOP, the code related to network is written by applying the interface but not the implementations. The operation can solely be on the interface of that object’s class.
RMI-IIOP relies on object serialization for passing parameters via remote method invocations.
JNDI (Java Naming and Directory Interface) API: To enable java programs to access the naming and directory services, the JNDI API is utilized. Naming services emphasize on the services that are to associate names with objects.
We are familiar with naming systems such as the file system which has a directory or path associated it. Surfing web is associated with a name that is the URL called Domain Naming System. EJB components of a J2EE application server, user profiles are associated in LDAP (Lightweight Directory Access Protocol) directory.
For example, JNDI is the best API to write a java application that is used for search utility over network-enabled desktop, class-browser, or an address book search utility.
JDBC (Java Database Connectivity) API: Many java applications use a database and database accessing and programming is a significant role in web application development. JDBC is an API that enables the accessibility to a database in order to manipulate the database.
The JDBC API supports both two-tier and three-tier models for database access. Two-tier model – a Java application interacts directly with the database. Three-tier model – introduces a middle-level server for execution of business logic: the middle tier to maintain control over data access.
The application that uses the JDBC implements the following sequence.
  1. Importing Packages
  2. Registering the JDBC Drivers
  3. Opening a Connection to a Database
  4. Creating a Statement Object
  5. Executing a query and Returning a Result Set Object
  6. Processing the Result Set
  7. Closing the Result Set and Statement Objects
  8. Closing the Connection.
Java Mail API: Mailing and Messaging applications can be modeled or developed using Java Mail. The e-mail messaging applications can be developed for both high-level implementation and low-level implementation. That is, a small company that is heading towards growth can develop solutions which ensure the accessing to their mail server in an efficient manner. A blue-chip company can focus on providing the access to industry-level access which is a wider reach and provides vast support. JMS: Java Message Services is an API that enables the components of an application, could it be JSE or JEE component to provide messaging services such as create, send, receive and read messages. Using loosely coupled, reliable and asynchronous communications are enabled by JMS.
The JMS application contains the following parts:
1. JMS Provider: It implements the JMS interface and provides the administration and control services for the messages. J2EE 1.3 includes the JMS Provider service.
2. JMS Clients: These are the java applications that produce or consume the messages.
3. Messages: These are the objects that communicate the messages between clients.
4. Administered Objects: They are the JMS objects created by the administrator that can be used by the clients. They are namely destinations and connection factories.
5. Native Clients: These are the applications that use the message client’s native client API instead of JMS API.
Question 38.
What are the 3 different Java platform editions? Explain them.
Answer:
Java 2 Platform, Standard Edition (J2SE)
Java 2 Platform, Enterprise Edition (J2EE)
Java 2 Platform, Micro Edition (J2ME)
Java 2 Platform, Standard Edition (JSE): J2SE is used to develop stand-alone/desktop portable java applications. J2SE consists of two components. Core component and desktop component. Core component provides back-end functionality. The desktop component provides GUI functionality. J2SE consists of Java Development Kit and Java Runtime Environment. JDK consists of a java compiler and other related tools to enable the users to create Java Applications. Java RuntimeJEnyironment consists of a java virtual machine, libraries, and all other components that are necessary to run a java application.
Java 2 Platform, Enterprise Edition (JEE): J2EE is a platform to develop multi¬tier enterprise applications. JEE includes Servlets API, Java Server Pages, and Enterprise Java Beans. It was built on J2SE technology.
Java 2 Platform, Micro Edition (JME): JME is the technology for microelectronic devices like PDAs, Mobile phones, etc. JME supports the flexibility for user interfaces, provides security, and uses the built-in network protocols for networked applications.JME applications can be ported across different devices.
Question 39.
What are the components of the J2EE application?
Answer:
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
Application clients and applets are client components. Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components. Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components. Resource adapter components provided by EIS and tool vendors.
Question 40.
What are the four types of J2EE modules?
Answer:
  1. Application client module
  2. Web module
  3. Enterprise JavaBeans module
  4. Resource adapter module
Question 41.
What does the application client module contain?
Answer:
The application client module contains:

• class files,
• an application client deployment descriptor.

Application client modules are packaged as JAR files with a .jar extension.
Question 42.
What does the web module contain?
Answer:
The web module contains:
  • JSP files,
  • class files for servlets,
  • GIF and HTML files, and
  • a Web deployment descriptor.

Web modules are packaged as JAR files with a .war (Web ARchive) extension.

Question 43.
What are the differences between Ear, Jar, and War files? Under what circumstances should we use each one?
Answer:
There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.

• Jar files (files with a .jar extension) are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
• War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context.
• Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications.
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.

Question 44
What is “application client”?
Answer:
A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.

Question 45.
What is an “application client container”?
Answer:
A container that supports application client components.

Question 46.
What is an “application client module”?
Answer:
A software unit that consists of one or more classes and an application client deployment descriptor.

Question 47.
What is an “application component provider”?
Answer:
A vendor that provides the Java classes that implement components’ methods, JSP page definitions, and any required deployment descriptors.

Question 48.
What is an “application configuration resource file”?
Answer:
An XML file is used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.

Question 49.
What is “archiving”?
Answer:
The process of saving the state of an object and restoring it.

Question 50.
What is “ascent”?
Answer:
A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed.

Question 51.
What is URI?
Answer:
Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (HTTP or https for Web applications) and the physical location of a resource (hostname and host-relative path). A URN is another type of URI.

Question 52.
What is a URL?
Answer:
Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this: protocol://host/ local info where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.

Question 53.
What is a URL path?
Answer:
The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path + servlet path + path info, where Context path is the path prefix associated with a servlet context of which the servlet is a part. If this context is the default context rooted at the base of the Web server’s URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path

Question 54.
What is URN?
Answer:
Uniform resource name. A unique identifier that identifies an entity but doesn’t tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.

Question 55.
What is Web application?
Answer:
An application is written for the Internet, including those built with Java technologies such as JavaServer Pages and servlets, as well as those built with non-Java technologies such as CGI and Perl.

Question 56.
What is a Web application, distributable?
Answer:
A Web application that uses J2EE technology written so that it can be deployed in a Web container distributed across multiple Java virtual machines running on the same host or different hosts. The deployment descriptor for such an application uses the distributable element.

Question 57.
What is Web component?
Answer:
A component that provides services in response to requests; either a servlet or a JSP page.

Question 58.
What is Web container?
Answer:
A container that implements the Web component contract of the J2EE architecture. This contract specifies a runtime environment for Web components that includes security, concurrency, life-cycle management, transaction, deployment, and other services. A Web container provides the same services as a JSP container as well as a federated view of the J2EE platform APIs. A Web container is provided by a Web or J2EE server.

Question 59.
What is a Web container, distributed?
Answer:
A Web container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

Question 60.
What is Web container provider?
Answer:
A vendor that supplies a Web container.

Question 61.
What is a Web module?
Answer:
A deployable unit that consists of one or more Web components, other resources, and a Web application deployment descriptor contained in a hierarchy of directories and files in a standard Web application format.

Question 62.
What is Web resource?
Answer:
A static or dynamic object contained in a Web application that can be referenced by a URL.

Question 63.
What is Web resource collection?
Answer:
A list of URL patterns and HTTP methods that describe a set of Web resources to be protected.

Question 64.
What is a Web server?
Answer:
Software that provides services to access the Internet, an intranet, or an extranet. A Web server hosts Web sites, provides support for HTTP and other protocols, and executes server-side programs (such as CGI scripts or servlets) that perform certain functions. In the J2EE architecture, a Web server provides services to a Web container. For example, a Web container typically relies on a Web server to provide HTTP message handling. The J2EE architecture assumes that a Web container is hosted by a Web server from the same vendor, so it does not specify the contract between these two entities. A Web server can host one or more Web containers.

Question 65.
What is Web server provider?
Answer:
A vendor that supplies a Web server.

Question 66.
What is the life cycle (J2EE component)?
Answer:
The framework events of a J2EE component’s existence. Each type of component has to define events that mark its transition into states in which it has varying availability for use. For example, a servlet is created and has its init method called by its container before invocation of its service method by clients or other servlets that require its functionality.

After the call of its init method, it has the data and readiness for its intended use. The servlet’s destroy method is called by its container before the ending of its existence so that processing associated with winding up can be done and resources can be released. The init and destroy methods in this example are callback methods. Similar considerations apply to the life cycle of all J2EE component types: enterprise beans, Web components (servlets or JSP pages), applets, and application clients.

Question 67.
What is life cycle (JavaServer Faces)?
Answer:
A set of phases during which a request for a page is received, a UI component tree representing the page is processed, and a response is produced. During the phases of the life cycle:

The local data of the components are updated with the values contained in the request parameters. Events generated by the components are processed. Validators and converters registered on the components are processed. The components’ local data is updated to back-end objects. The response is rendered to the client while the component state of the response is saved on the server for future requests.

Question 68.
What is Entity Bean and Session Bean?
Answer:
A session bean is a non-persistent object that implements some business logic running on the server. One way to think of a session object is as a logical extension of the client program that runs on the server. An entity bean is a component that represents an object-oriented view of some entities stored in persistent storage, such as a database, or entities that are implemented by an existing enterprise application.

Question 69.
What are the methods of Entity Bean?
Answer:
Here we will talk about the implementation of an Entity Bean, not about a home interface. An entity bean consists of 4 groups of methods:
1. create methods.Theylooklikethis: EntityBeanClassejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances according to the parameters specified and to some programmer- defined conditions. Implementation of creating ( ) methods of the home interface is necessary only in Entity Beans with Bean-Managed Persistence.

2. finder methods. Each finder method is used for finding Entity Beans (single objects or a collection of objects) within the home. There is a method used for finding objects by the unique identifier (a Primary Key) – findByPrimaryKey( PrimaryKeyClass). This method returns a single Entity Bean, whereas most other finder methods return a Collection of remote interfaces.

3. remove methods. These methods (you may have up to 2 remove methods, or don’t have them at all) allow the client to physically remove Entity Beans. You can remove these beans by specifying either Handle or a Primary Key for the Entity Bean.

4. home methods. These methods are designed and implemented by a developer, and EJB specification doesn’t have any requirements for them except the need to throw a RemoteException in each home method.

Question 70.
How does Stateful Session bean store its state?
Answer:
First of all, a Stateful Session bean is a Session Bean instance containing some conversational state (a result of data interchange or processing), which needs to be retained across methods and transactions.

A Stateful Session bean stores its state in the instance’s fields and objects referred to from these fields. These fields may contain some up-to-time information as open sockets or database connections.

Question 71.
Why does Stateless Session bean not store its state even though it has ejbActivate() and ejbPassivate()?
Answer:
To answer this question you need to remember what a Stateless Session bean is. It’s a Session Bean instance NOT containing any conversational state. Such beans are used mostly for performing some atomic operations, because NO data, is saved in the instance’s variables. The other point is that you never know which instance serves your application request at a given time. If your application requests; a Stateless Session bean once and another Stateless Session bean in some time, you
can never be sure that a Container gives you the same reference.

In conclusion, the Stateless Session beans have the ejbActivate( ) and ejbPassivate( ) methods, but there is no sense to rely on their persistence, because of the implementation of such beans.

Question 72.
What are the services provided by the container?
Answer:
A container provides a set of services listed below:

1. Enterprise Java Beans support. The support for EJBs is mandatory for each container. It must support all types of beans specified by SUN. (The latest specification is 2.0, though its final version is not yet released, most EJB containers already support it.)

2. JTS (Java Transaction Service). This service is intended to control transactions within an enterprise system.

3. JNDI (Java Naming and Directory Interface). Every EJB Container MUST provide a name space for accessing resources (including EJB instances), as well as a way to access them using JNDI.

4. JDBC (Java DataBase Connection). A Container must be able to provide EJBs with the ability to access existing database(s). In most cases, the XA and connection pooling are also supported, but it’s also a headache for a JDBC driver vendor.

5. JMS (Java Messaging Service). This service is new to EJB, and it was introduced j in EJB 2.0. This service allows interchange of asynchronous messages. EJB 2.0 also introduced the new type of beans – Message-driven Beans invoked by a Container only.

Question 73.
Types of transactions?
Answer:
EJBs may participate (and often do it) in database transactions. Just remember some database fundamentals:

1. Simple transactions. Transactions performing simple operations. This type of transaction is the most often used.

2. Nested transactions. Transactions can be nested, i.e. some method, which opens a transaction, may call another method, also opening a transaction. In such a case, a nested transaction appears. There is no need to make such transactions explicitly because most systems don’t require such complicated! logic. Nevertheless, modern database servers support nested transactions.
Note that if an inner transaction rolls back, the outer transaction automatically rolls back, and if an inner transaction fails, the outer transaction also fails.

3. Distributed transactions. This kind of transaction is used for performing operations on data located in different databases. If more than one database is involved in a transaction, such a transaction is called a distributed transaction.

Question 74.
What is a bean-managed transaction?
Answer:
If a developer doesn’t want a Container to manage transactions, it’s possible to implement all database operations manually by writing the appropriate JDBC code. This often leads to productivity increase, but it makes an Entity Bean incompatible with some databases and it enlarges the amount of code to be written. A developer explicitly performs all transaction management.

Question 75.
Why does E JB need two interfaces (Home and Remote Interface)?
Answer:
A client searches for a home interface to instantiate a remote interface. A remote interface is a client-side mapping to a server object performing business methods. Such schema was introduced purposely to demarcate the difference between server and client interfaces.

Question 76.
What are transaction attributes?
Answer:
The transaction attribute specifies how the Container must manage transactions for a method when a client invokes the method via the enterprise bean’s home or component interface or when the method is invoked as the result of the arrival of a JMS message. (Sun’s EJB Specification) Below is a list of transactional attributes:

1. NotSupported – transaction context is unspecified.

2. Required – bean’s method invocation is made within a transactional context. If a client is not associated with a transaction, a new transaction is invoked automatically.

3. Supports – if a transactional context exists, a Container acts like the transaction attribute is Required, else – like NotSupported.

4. RequiresNew – a method is invoked in a new transaction context.

5. Mandatory-if a transactional context exists, a Container acts like the transaction attribute is required, else it throws a javax.EJB.TransactionRequiredException.

6. Never – a method executes only if no transaction context is specified.

Question 77.
What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed (BMP) persistent entity bean?
Answer:
A CMP bean developer doesn’t need to worry about JDBC code and ^transactions, because the Container performs database calls and transaction management instead of the programmer. All table mapping is specified in the deployment descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database on his shoulders.

BMP beans are not 100% database-independent, because they may contain database-specific code, but CMP beans are unable to perform complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some new ways of querying databases (by using the EJB QL – query language).

Question 78.
How entity bean is created using the CMP entity bean?
Answer:
The container creates an entity bean automatically. Here, “automatically” means that a developer doesn’t need to write any SQL code for it. Certainly, this doesn’t exempt a programmer from implementing business methods.

Question 79.
What is the software architecture of EJB?
Answer:
Session and Entity EJBs consist of 4 or 5 parts: a remote interface (a client interacts with it), a home interface (used for creating objects and for declaring business methods) a bean object (an object, which actually performs business logic, and E JB-specific operations). The fourth part is a deployment descriptor (an XML file containing all information required for maintaining the EJB) or a set of deployment descriptors (if you are using some container-specific features). The fifth part – a Primary Key class – is only Entity bean specific.

Question 80.
Can Entity Beans have no created ( ) methods?
Answer:
Certainly. In some cases, the data is inserted NOT using Java application, so you may only need to retrieve the information, perform its processing, but not create your own information of this kind.

Question 81.
In which case, ejbLoad( ) doesn’t read data from the database?
Answer:
ejbLoad( ) reads data from the database in all cases except one: when the information stored in an Entity Bean has not been changed after creation or retrieving. In this case, ejbLoad( ) becomes a redundant operation.

Question 82.
What is an “eager loading of state”?
Answer:
An EJB container usually reads all data to construct the Entity Bean. This is opposite to “lazy loading” when data is read as pieces, not as a whole block. This increases speed in most cases but makes the application more complicated.

Question 83.
How would you implement a case when Entity Bean 1 calls Entity Bean 2, which calls Entity Bean 1?
Answer:
You need to mark Entity Bean 1 as a re-entrant.

Question 84.
How would you implement EJB subclassing?
Answer:
The following guidelines assume that we have EJB2, which subclasses EJB1. (Both EJBs are session ones.) The Remote interface of EJB2 implements the Remote interface of EJB1 The Bean class of EJB2 extends the Bean class of EJB1

Question 85.
What is the difference between Stateful and Stateless Session Bean?
Answer:
A Stateful Session Bean is a bean that is designed to service business processes that span multiple method requests or transactions. Stateful Session beans retain state on behalf of an individual client. Stateless Session Beans do not maintain a state.
EJB containers pool stateless session beans and reuse them to service many clients. Stateful session beans can be passivated and reused for other clients. But this involves I/O bottlenecks. Because a stateful session bean caches client conversation in memory, a bean failure may result in loosing the entire client conversation. Therefore, while writing a stateful session bean the bean developer has to keep the bean failure and client conversation loss in mind.

In the case of stateless session beans, client-specific data has to be pushed to the bean for each method invocation, which will result in an increase in the network traffic. This can be avoided in a number of ways like persisting the client-specific data in a database or in JNDI. But this also results in I/O performance bottlenecks.

If the business process spans multiple invocations thereby requiring a conversation then stateful session bean will be the ideal choice. On the other hand, if business process lasts only for a single method call, the stateless session bean model suits. Stateful session beans remember the previous request and responses. But stateless beans do not. stateful does not have a pooling concept, whereas the stateless bean instances are pooled

Question 86.
Difference between forward(request,response) and SendRedirect(url) in Servlet?
Answer:
With forwarding, request & response would be passed to the destination URL which should be relative (means that the destination URL should be within a servlet context). Also, after executing the forward method, the control will return back to the same method from where the forward method was called. All the opposite to the above points apply to sendRedirect.
(OR)The forward will redirect to the application server itself. It does not come to the client. Whereas Response.send redirect( ) will come to the client and go back …i.e. URL appending will happen.

Question 87.
What is enterprise bean?
Answer:
• Server-side reusable java component
• Offers services that are hard to implement by the programmer
• Sun: Enterprise Bean architecture is a component architecture for the deployment and development of component-based distributed business applications.

Applications written using enterprise java beans are scalable, transactional and multi-user secure. These applications may be written once and then deployed on any server platform that supports enterprise java beans specification.

• Enterprise beans are executed by the J2EE server. First version 1.0 contained session beans, entity beans were not included. Entity beans were added to version 1.1 which came out during year 1999. The current release is EJB version 1.2

Question 88.
Services of EJB?
Answer:
Database management

  • Database connection pooling
  • DataSource, offered by the J2EE server. Needed to access connection pool of the server.
  • Database access is configured to the J2EE server -> easy to change database/database driver
  • Transaction management
  • Distributed transactions
  • J2EE server offers a transaction monitor which can be accessed by the client.
  • Security management
  • Authentication
  • Authorization
  • encryption

Enterprise java beans can be distributed /replicated into separate machines distribution/replication offers

  • Load balancing, the load can be divided into separate servers.
  • Failover, if one server fails, others can keep on processing normally.
  • Performance, one server is not so heavily loaded. Also, for example, Weblogic has thread pools for improving performance in one server.

Question 89.
When to choose EJB?
Answer:
The server will be heavy loaded

  • The distribution of servers helps to achieve better performance.
  • The server should have a replica for the case of failure of one server.
  • Replication is invisible to the programmer
  • Distributed transactions are needed
  • J2EE server offers a transaction monitor that takes care of transaction management.
  • Distributed transactions are invisible to the programmer Other services vs. money
    Weblogic J2EE server ~ 80 000 MK and Jbuilder X Professional Edition ~ 5 OOOmk

Question 90.
Why not use free J2EE servers?
Answer:

  • no technical support
  • harder to use (no graphical user interface …)
  • no integration to development tools (for example, Jbuilder)
  • Bugs? Other problems during the project?

Question 91.
What J2EE server offers?
Answer:
DataSource.

  • An object that can be used to achieve database connection from the connection pool.
  • Can be accessed by the interface DataSource
  • Transaction monitor
  • Can be accessed by the interface UserTransaction.
    Java Naming and the Directory Service

Question 92.
Java Naming and the Directory Service
Answer:
Naming service is needed to locate beans home interfaces or other objects (DataSource, UserTransaction)

  • For example, jndi name of the DataSource A directory service is needed to store and retrieve properties by their name.
  • jndi name: java:comp/env/propertyName

Question 93.
XML – deployment descriptor
Answer:
ejb-jar.xml + server-specific xml- file Which is then Packed in a jar — file together with bean classes.
Beans are packaged into EJB JAR file, Manifest file is used to fist EJB’s and jar file holding Deployment descriptor.

Question 94.
Session Bean
Answer:
Developer programs three classes:

  • The home interface contains methods for creating (and locating for entity beans) bean instances.
  • The remote interface contains business methods the bean offers.
  • Bean class contains the business logic of the enterprise bean.

Question 95.
Entity Beans
Answer:
Represents one row in the database.

  • Easy way to access database
  • Business logic concept to manipulate data.
  • Container managed persistence vs. bean-managed persistence.

The programmer creates three or four classes:

  • Home interface for locating beans
  • The remote interface contains business methods for clients.
  • Bean class that implements bean’s behavior.
  • Primary key class – represents the primary key in the database. Used to locate beans.

Primary key class is not needed if the primary key is a single field that could be j

When to use which bean?

Entity beans are effective when an application wants to access one row at a time. If many rows need to be fetched, using session beans can be a better alternative java class (for example, Integer).
Entity beans are efficient when working with one row at a time

Cause a lot of network traffic.
Session Beans are efficient when the client wants to access the database directly.

  • fetching/updating multiple rows from the database

Question 96.
Explain J2EE Architecture?
Answer:
Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details.

The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components and the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand.

Containers and Services
Components are installed in their containers during deployment and are the interface between a component and the low-level platform-specific functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.

The assembly process involves specifying container settings for each component in the J2EE application and for the J2EE application itself. Container settings customize the underlying support provided by the J2EE Server, which include services such as security, transaction management, Java Naming and Directory Interface TM (JNDI) lookups, and remote connectivity.
Figure: J2EE Server and Containers
Container Types
The deployment process installs J2EE application components in the following types

Question 99.
What is the difference between BeanMangedPersistance and Container- MangedPersistance?
Answer:
CMP: Tx behavior in beans are defined in transaction attributes of the methods
BMP: Programmers have to write a code that implements Tx behavior to the bean class. Tuned CMP entity beans offer better performance than BMP entity beans. Moving towards the CMP-based approach provides database independence since it does not contain any database storage APIs within it. Since the container performs database operations on behalf of the CMP entity bean, they are harder to debug. BMP beans offer more control and flexibility than CMP beans.

Diff 1) In BMP you will take care of all the connections and you write the SQL code inside the bean whereas in CMP the container will take care of it Diff 2) The BMP is not portable across all DB’s.whereas the CMP is

Question 100.
How Servlet Maintain Session and EJB Maintain Session?
Answer:
Servlets maintain sessions in ServleContext and EJB’s in EJBContext.

Question 101.
What is “attribute”?
Answer:
A qualifier on an XML tag that provides additional information.

Question 102.
What is authentication?
Answer:
The process that verifies the identity of a user, device, or other entity in a computer system, usually a prerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication.

Question 103.
What is authorization?
Answer:
The process by which access to a method or resource is determined. Authorization depends on the determination of whether the principal associated with a request through authentication is in a given security role. A security role is a logical grouping of users defined by the person who assembles the application. A deployer maps security roles to security identities. Security identities may be principals or groups in the operational environment.

Question 104.
What is an authorization constraint?
Answer:
An authorization rule that determines who is permitted to access a Web resource collection.

Question 105.
What is B2B?
B2B stands for Business-to-business.

Question 106.
What is a backing bean?
Answer:
A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. The backing bean defines properties for the components on the page and methods that perform processing for the component. This processing includes event handling, validation, and processing associated with navigation.

Question 107.
What is basic authentication?
Answer:
An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application’s built-in authentication mechanism.

Question 103.
What is bean-managed persistence?
Answer:
The mechanism whereby data transfer between an entity bean’s variables and a resource manager is managed by the entity bean.

Question 109.
What is a bean-managed transaction?
Answer:
A transaction whose boundaries are defined by an enterprise bean.

Question 110.
What is binding (XML)?
Answer:
Generating the code needed to process a well-defined portion of XML data.

Question 111.
What is binding (JavaServer Faces technology)?
Answer:
Wiring UI components to back-end data sources such as backing bean properties.

Question 112.
What is a build file?
Answer:
The XML file contains one or more ascent targets. A target is a set of tasks you want to be executed. When starting ascent, you can select which targets you want to have executed. When no target is given, the project’s default target is executed.

Question 113.
What is business logic?
Answer:
The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, this logic is implemented by the methods of an enterprise bean.

Question 114.
What is the business method?
Answer:
A method of an enterprise bean that implements the business logic or rules of an application.

Question 115.
What are callback methods?
Answer:
Component methods are called by the container to notify the component of important events in its life cycle.

Question 116.
What is the caller?
Answer:
Same as caller principal.

Question 117.
What is caller principal?
Answer:
The principal that identifies the invoker of the enterprise bean method.

Question 118.
What is cascade delete?
Answer:
A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that has container-managed persistence.

Question 119.
What is CDATA?
Answer:
A predefined XML tag for character data means “don’t interpret these characters,” as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax.

Question 120.
What is a certificate authority?
Answer:
A trusted organization that issues public key certificates and provides identification to the bearer.

Question 121.
What is client-certificate authentication?
Answer:
An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure.

Question 122.
What is a comment?
Answer:
In an XML document, the text is ignored unless the parser is specifically told to recognize it.

Question 123.
What is commit?
Answer:
The point in a transaction is when all updates to any resources involved in the transaction are made permanent.

Question 124.
What is the component contract?
Answer:
The contract between a J2EE component and its container. The contract includes life-cycle management of the component, a context interface that the instance uses to obtain various information and services from its container, and a list of services that every container must provide for its components.

Question 125.
What is component-managed sign-on?
Answer:
A mechanism whereby security information needed for signing on to a resource is provided by an application component.

Question 126.
What is a connector?
Answer:
A standard extension mechanism for containers that provides connectivity to enterprise information systems. A connector is specific to an enterprise information system and consists of a resource adapter and application development tools for enterprise information system connectivity. The resource adapter is plugged into a container through its support for system-level contracts defined in the Connector architecture.

Question 127.
What is container-managed persistence?
Answer:
The mechanism whereby data transfer between an entity bean’s variables and a resource manager is managed by the entity bean’s container.

Question 128.
What is container-managed sign-on?
Answer:
The mechanism whereby security information needed for signing on to a resource is supplied by the container.

Question 129.
What is a container-managed transaction?
Answer:
A transaction whose boundaries are defined by an E JB container. An entity bean must use container-managed transactions.

Question 130.
What is content?
Answer:
In an XML document, the part that occurs after the prolog, including the root element and everything it contains.

Question 131.
What is a context attribute?
Answer:
An object bound into the context associated with a servlet.

Question 132.
What is context root?
Answer:
A name that gets mapped to the document root of a Web application.

Question 133.
What is the conversational state?
Answer:
The field values of a session bean plus the transitive closure of the objects reachable from the bean’s fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.

Question 134.
What is CORBA?
Answer:
Common Object Request Broker Architecture. A language-independent distributed object model specified by the OMG.

Question 135.
What is create method?
Answer:
A method defined in the Interview Questions – Home interface and invoked by a client to create an enterprise bean.

Question 136.
What are credentials?
Answer:
The information describing the security attributes of a principal.

Question 137.
What is CSS?
Answer:
Cascading style sheet. A style sheet is used with HTML and XML documents to add a style to all elements marked with a particular tag, for the direction of browsers or other presentation mechanisms.

Question 138.
What is CTS?
Answer:
Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification.

Question 139.
What is data?
Answer:
The contents of an element in an XML stream, generally used when the element does not contain any subelements. When it does, the term content is generally used. When the only text in an XML structure is contained in simple elements and when elements that have subelements have little or no data mixed in, then that structure is often thought of as XML data, as opposed to an XML document.

Question 140.
What is DDP?
Answer:
Document-driven programming. The use of XML to define applications.

Question 141.
What is a declaration?
Answer:
The very first thing in an XML document, which declares it as XML. The minimal declaration is. The declaration is part of the document prolog.

Question 142.
What is declarative security?
Answer:
Mechanisms used in an application are expressed in a declarative syntax in a deployment descriptor.

Question 143.
What is delegation?
Answer:
An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions.

Question 144.
What is a deployer?
Answer:
A person who installs J2EE modules and applications into an operational environment.

Question 145.
What is deployment?
Answer:
The process whereby software is installed into an operational environment.

Question 146.
What is a deployment descriptor?
Answer:
An XML file is provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.

Question 147.
What is destination?
Answer:
A JMS administered object that encapsulates the identity of a JMS queue or topic. See point-to-point messaging system, publish/subscribe messaging system.

Question 148.
What is digest authentication?
Answer:
An authentication mechanism in which a Web application authenticates itself to a Web server by sending the server a message digest along with its HTTP request message. The digest is computed by employing a one-way hash algorithm to a concatenation of the HTTP request message and the client’s password. The digest is typically much smaller than the HTTP request and doesn’t contain the password.

Question 149.
What has distributed application?
Answer:
An application is made up of distinct components running in separate runtime environments, usually on different platforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier (client-middleware- server), and multitier (client-multiple middleware-multiple servers).

Question 150.
What is a document?
Answer:
In general, an XML structure in which one or more elements contains text intermixed with subelements.

Question 151.
What is Document Object Model?
Answer:
An API for accessing and manipulating XML documents as tree structures. DOM provides platform-neutral, language-neutral interfaces that enable programs and scripts to dynamically access and modify content and structure in XML documents.

Question 152.
What is document root?
Answer:
The top-level directory of a WAR. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored.

Question 153.
What is DTD?
Answer:
Document type definition. An optional part of the XML document prolog, as specified by the XML standard. The DTD specifies constraints on the valid tags and tag sequences that can be in the document. The DTD has a number of shortcomings, however, and this has led to various schema proposals. For example, the DTD entry says that the XML element called username contains parsed character data-that is, text alone, with no other structural elements under it.

The DTD includes both the local subset, defined in the current file, and the external subset, which consists of the definitions contained in external DTD files that are referenced in the local subset using a parameter entity.

Question 154.
What is a durable subscription?
Answer:
In a JMS publish/subscribe messaging system, a subscription continues to exist whether or not there is a current active subscriber object. If there is no active subscriber, the JMS provider retains the subscription’s messages until they are received by the subscription or until they expire.

Question 155.
What is an EAR file?
Answer:
Enterprise Archive file. A JAR archive that contains a J2EE application.

Question 156.
What is ebXML?
Answer:
Electronic Business XML. A group of specifications designed to enable enterprises to conduct business through the exchange of XML-based messages. It is sponsored by OASIS and the United Nations Centre for the Facilitation of Procedures and Practices in Administration, Commerce, and Transport (U.N./CEFACT).

Question 157.
What is Java API for XML Processing (JAXP)?
Answer:
An API for processing XML documents. JAXP leverages the parser standards SAX and DOM so that you can choose to parse your data as a stream of events or to build a tree-structured representation of it. JAXP supports the XSLT standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP provides namespace support, allowing you to work with a schema that might otherwise have naming conflicts.

Question 158.
What is Java API for XML Registries (JAXR)?
Answer:
An API for accessing various kinds of XML registries.

Question 159.
What is Java API for XML-based RPC (JAX-RPC)?
Answer:
An API for building Web services and clients that use remote procedure calls and XML.

Question 160.
What is Java IDL?
Answer:
A technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operations on remote network services using the Object Management Group IDL and HOP.

Question 161.
What is Java Secure Socket Extension (JSSE)?
Answer:
A set of packages that enable secure Internet communications.

Question 162.
What is Java Transaction API (JTA)?
Answer:
An API that allows applications and J2EE servers to access transactions.

Question 163.
What is Java Transaction Service (JTS)?
Answer:
Specifies the implementation of a transaction manager that supports JTA and implements the Java mapping of the Object Management Group Object Transaction Service 1.1 specification at the level below the API.

Question 164.
What is the JavaBeans component?
Answer:
A Java class that can be manipulated by tools and composed into applications. A JavaBeans component must adhere to certain property and event interface conventions.

Question 165.
What is JavaMaii?
Answer:
An API for sending and receiving emails.

Question 166.
What is a local subset?
Answer:
That part of the DTD is defined within the current XML file.

Question 167.
What is a tag?
Answer:
In XML documents, a piece of text describes a unit of data or an element. The tag is distinguishable as markup, as opposed to data, because it is surrounded by angle brackets (< and >). To treat such markup syntax as data, you use an entity reference or a CDATA section.

Question 168.
What is a template?
Answer:
A set of formatting instructions that apply to the nodes selected by an XPath expression.

Question 169.
What is a tool provider?
Answer:
An organization or software vendor that provides tools used for the development, packaging, and deployment of J2EE applications.

Question 170.
What is a transaction attribute?
Answer:
A value specified in an enterprise bean’s deployment descriptor is used by the EJB container to control the transaction scope when the enterprise bean’s methods are invoked. A transaction attribute can have the following values: Required, RequiresNew, Supports, NotSupported, Mandatory, or Never.

Question 171.
What is a transaction?
Answer:
An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which are either complete or rollback. Transactions enable multiple users to access the same data concurrently.

Question 172.
What is the transaction isolation level?
Answer:
What is transaction isolation level The degree to which the intermediate state of the data being modified by a transaction is visible to other concurrent transactions and data being modified by other transactions is visible to it.

Question 173.
What is a transaction manager?
Answer:
Provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

Question 174.
What is Unicode?
Answer:
A standard defined by the Unicode Consortium uses a 16-bit code page that maps digits to characters in languages around the world. Because 16 bits cover 32,768 codes, Unicode is large enough to include all the world’s languages, with the exception of ideographic languages that have a different character for every concept, such as Chinese.

Question 175.
What is Universal Description, Discovery, and Integration (UDDI) project?
Answer:
An industry initiative to create a platform-independent, open framework for describing services, discovering businesses, and integrating business services using the Internet, as well as a registry. It is being developed by a vendor consortium.

Question 176.
What is Universal Standard Products and Services Classification (UNSPSC)?
Answer:
A schema that classifies and identifies commodities. It is used in sell-side and buy-side catalogs and as a standardized account code in analyzing expenditure.

Question 177.
What is an unparsed entity?
Answer:
A general entity that contains something other than XML. By its nature, an unparsed entity contains binary data.

Question 178.
What is a user data constraint?
Answer:
Indicates how data between a client and a Web container should be protected. The protection can be the prevention of tampering with the data or the prevention of eavesdropping on the data.

Question 179.
What is a user (security)?
Answer:
An individual (or application program) identity that has been authenticated. A user can have a set of roles associated with that identity, which entitles the user to access all resources protected by those roles.

Question 180.
What is validating parser?
Answer:
A parser that ensures that an XML document is valid in addition to being well formed. See also parser.

Question 181.
What is the value-binding expression?
Answer:
A JavaServer Faces EL expression that refers to a property of a backing bean. A component tag uses this expression to bind the associated component’s value or the component instance to the bean property. If the component tag refers to the property via its value attribute, then the component’s value is bound to the property. If the component tag refers to the property via its binding attribute then the component itself is bound to the property.

Question 182.
What is a virtual host?
Answer:
Multiple hosts plus domain names mapped to a single IP address.

Question 183.
What is W3C?
Answer:
World Wide Web Consortium. The international body that governs Internet standards. Its Web site is http://www.w3.org/.

Question 184.
What is a WAR file?
Answer:
Web application archive file. A JAR archive that contains a Web module.

Question 185.
What is the warning?
Answer:
A SAX parser warning is generated when the document’s DTD contains duplicate definitions and in similar situations that are not necessarily an error but which the document author might like to know about because they could be. See also fatal error, error.

Question 186.
What is Web service?
Answer:
An application that exists in a distributed environment, such as the Internet. A Web service accepts a request, performs its function based on the request, and returns a response. The request and the response can be part of the same operation, or they can occur separately, in which case the consumer does not need to wait for a response. Both the request and the response usually take the form of XML, a portable data-interchange format, and are delivered over a wire protocol, such as HTTP.

Question 187.
What is well-formed?
1 Answer:
An XML document that is syntactically correct. It does not have any angle brackets that are not part of tags, all tags have an ending tag or are themselves I am self-ending, and all tags are fully nested. Knowing that a document is well-formed makes it possible to process it. However, a well-formed document may not be valid. To determine that, you need a validating parser and a DTD.

Question 188.
What is Xalan?
Answer:
An interpreting version of XSLT.

Question 189.
What is XHTML?
Answer:
An XML look-alike for HTML defined by one of several XHTML DTDs. To use XHTML for everything would of course defeat the purpose of XML, because the idea of XML is to identify information content, and not just to tell how to display it. You can reference it in a DTD, which allows you to say, for example, that the text in an element can contain < em > and < b > tags rather than being limited to plain text.

Question 190.
What is XLink?
Answer:
The part of the XLL specification is concerned with specifying links between documents.

Question 191.
What is XLL?
Answer:
The XML Link Language specification, consisting of XLink and XPointer.

Question 192.
What is XML?
Answer:
Extensible Markup Language. A markup language that allows you to define the tags (markup) needed to identify the content, data, and text in XML documents. It differs from HTML, the markup language most often used to present information on the Internet. HTML has fixed tags that deal mainly with style or presentation. An XML document must undergo a transformation into a language with style tags under the control of a style sheet before it can be presented by a browser or other presentation mechanism. Two types of style sheets used with XML are CSS and XSL. Typically, XML is transformed into HTML for presentation.

Although tags can be defined as needed in the generation of an XML document, a document type definition (DTD) can be used to define the elements allowed in a particular type of document. A document can be compared by using the rules in the DTD to determine its validity and to locate particular elements in the document. A Web services application’s J2EE deployment descriptors are expressed in XML with schemas defining allowed elements. Programs for processing XML documents use SAX or DOM APIs.
I 336 I C, C++, JAVA & J2EE Interview Questions

Question 193.
What is an XML registry?
Answer:
An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

Question 194.
What is XML Schema?
Answer:
The W3C specification for defining the structure, content, and semantics of XML documents.

Question 195.
What is XPath?
Answer:
An addressing mechanism for identifying the parts of an XML document.

Question 196.
What is XPointer?
Answer:
The part of the XLL specification is concerned with identifying sections of documents so that they can be referenced in links or included in other documents.

Question 197.
What is XSL-FO?
Answer:
A subcomponent of XSL is used for describing font sizes, page layouts, and how information flows from one page to another.

Question 198.
What is Keystore?
Answer:
A file containing the keys and certificates used for authentication.

Question 199.
What is a local subset?
Answer:
That part of the DTD is defined within the current XML file.

Question 200.
What is managed bean creation facility?
Answer:
A mechanism for defining the characteristics of JavaBeans components used in a JavaServer Faces application.

Question 201.
What is a message?
Answer:
In the Java Message Service, an asynchronous request, report, or event is created, sent, and consumed by an enterprise application and not by a human. It contains vital information needed to coordinate enterprise applications, in the form of precisely formatted data that describes specific business actions.

Question 202.
What is a message consumer?
Answer:
An object created by a JMS session that is used for receiving messages sent to a destination.

Question 203.
What is a message-driven bean?
Answer:
An enterprise bean that is an asynchronous message consumer. A message-driven bean has no state for a specific client, but its instance variables can contain states across the handling of client messages, including an open database connection and an object reference to an EJB object. A client accesses a message-driven bean by sending messages to the destination for which the bean is a message listener.

Question 204.
What is a message producer?
Answer:
An object created by a JMS session that is used for sending messages to a destination.

Question 205.
What is the mixed-content model?
Answer:
A DTD specification defines an element as containing a mixture of text and one more another element. The specification must start with #PCDATA, followed by diverse elements, and must end with the “zero-or-more” asterisk symbol (*).

Question 206.
What is the method-binding expression?
Answer:
A JavaServer Faces EL expression that refers to a method of a backing bean. This method performs either event handling, validation, or navigation processing for the UI component whose tag uses the method-binding expression.

Question 207.
What is method permission?
Answer:
An authorization rule that determines who is permitted to execute one or more enterprise bean methods.

Question 208.
What is mutual authentication?
Answer:
An authentication mechanism is employed by two parties for the purpose of proving each other’s identity to one another.

Question 209.
What is namespace?
Answer:
A standard that lets you specify a unique label for the set of element names defined by a DTD. A document using that DTD can be included in any other document without having a conflict between element names. The elements defined in your DTD are then uniquely identified so that, for example, the parser can tell when an element <name> should be interpreted according to your DTD rather than using the definition for an element <name> in a different DTD.

Question 210.
What is naming context?
Answer:
A set of associations between unique, atomic, people-friendly identifiers and objects.

Question 211.
What is a naming environment?
Answer:
A mechanism that allows a component to be customized without the need to access or change the component’s source code. A container implements the component’s naming environment and provides it to the component as a JNDI naming context. Each component names and accesses its environment entries using the java: comp/env JNDI context. The environment entries are declaratively specified in the component’s deployment descriptor.

Question 212.
What is normalization?
Answer:
The process of removing redundancy by modularizing, as with subroutines, and of removing superfluous differences by reducing them to a common denominator. For example, line endings from different systems are normalized by reducing them to a single newline, and multiple whitespace characters are normalized to one space.

Question 213.
What is North American Industry Classification System (NAICS)?
Answer:
A system for classifying business establishments based on the processes they use to produce goods or services.

Question 214.
What is notation?
Answer:
A mechanism for defining a data format for a non-XML document referenced as an unparsed entity. This is a holdover from SGML. A newer standard is to use MIME data types and namespaces to prevent naming conflicts.

Question 215.
What is OASIS?
Answer:
Organization for the Advancement of Structured Information Standards. A consortium that drives the development, convergence, and adoption of e-business standards.

Question 216.
What is OMG?
Answer:
Object Management Group. A consortium that produces and maintains computer industry specifications for interoperable enterprise applications. Its Web site ishttp://www.omg.org/.

Question 217.
What is one-way messaging?
Answer:
A method of transmitting messages without having to block until a response is received.

Question 218.
What is ORB?
Answer:
Object request broker. A library that enables CORBA objects to locate and communicate with one another.

Question 219.
What is OS principal?
Answer:
A principal native to the operating system on which the J2EE platform is executing.

Question 220.
What is OTS?
Answer:
Object Transaction Service. A definition of the interfaces that permit CORBA objects to participate in transactions.

Question 221.
What is a parameter entity?
Answer:
An entity that consists of DTD specifications, as distinct from a general entity. A parameter entity defined in the DTD can then be referenced at other points, thereby eliminating the need to recode the definition at each location it is used.

Question 222.
What is parsed entity?
Answer:
A general entity that contains XML and therefore is parsed when inserted into the XML document, as opposed to an unparsed entity.

Question 223.
What is parser?
Answer:
A module that reads in XML data from an input source and breaks it into chunks so that your program knows when it is working with a tag, an attribute, or element data. A nonvalidating parser ensures that the XML data is well-formed but does not verify that it is valid. See also validating parser.

Question 224.
What is passivation?
Answer:
The process of transferring an enterprise bean from memory to secondary storage.

Question 225.
What is persistence?
Answer:
The protocol for transferring the state of an entity bean between its instance variables and an underlying database.

Question 226.
What is the persistent field?
Answer:
A virtual field of an entity bean that has container-managed persistence; it is stored in a database.

Question 227.
What is POA?
Answer:
Portable Object Adapter. A CORBA standard for building server-side applications that are portable across heterogeneous ORBs.

Question 228.
What is the point-to-point messaging system?
Answer:
A messaging system built on the concept of message queues. Each message is addressed to a specific queue; clients extract messages from the queues established to hold their messages.

Question 229.
What is primary key?
Answer:
An object that uniquely identifies an entity bean within a home.

Question 230.
What is principal?
Answer:
The identity is assigned to a user as a result of authentication.

Question 231.
What is privilege?
Answer:
A security attribute that does not have the property of uniqueness and that can be shared by many principals.

Question 232.
What is processing instruction?
Answer:
Information contained in an XML structure that is intended to be interpreted by a specific application.

Question 233.
What is programmatic security?
Answer:
Security decisions that are made by security-aware applications. Programmatic security is useful when declarative security alone is not sufficient to express the security model of an application.

Question 234.
What is a prolog?
Answer:
The part of an XML document that precedes the XML data. The prolog includes the declaration and an optional DTD.

Question 235.
What is a public-key certificate?
Answer:
Used in client-certificate authentication to enable the server, and optionally the client, to authenticate each other. The public key certificate is the digital equivalent of a passport. It is issued by a trusted organization, called a certificate authority, and provides identification for the bearer.

Question 236.
What is published/subscribe messaging system?
Answer:
A messaging system in which clients address messages to a specific node in a content hierarchy called a topic. Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a node’s multiple publishers to its multiple subscribers.

Question 237.
What is a query string?
Answer:
A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request.

Question 238.
What is a queue?
Answer:
See the point-to-point messaging system.

Question 239.
What is RAR?
Answer:
Resource Adapter Archive. A JAR archive that contains a resource adapter module.

Question 240.
What is RDF?
Answer:
Resource Description Framework. A standard for defining the kind of data that an XML file contains. Such information can help ensure semantic integrity-for example-by helping to make sure that a date is treated as a date rather than simply as text.

Question 241.
what is RDF schema?
Answer:
A standard for specifying consistency rules that apply to the specifications contained in an RDF.

Question 242.
what is realm?
Answer:
See security policy domain. Also, a string passed as part of an HTTP request during basic authentication defines a protection space. The protected resources on a server can be partitioned into a set of protection spaces, each with its own authentication scheme or authorization database, or both.

In the J2EE server authentication service, a realm is a complete database of roles, users, and groups that identify valid users of a Web application or a set of Web applications.

Question 243.
WTiat is a reentrant entity bean?
Answer:
An entity bean that can handle multiple simultaneous, interleaved, or nest invocations that will not interfere with each other.

Question 244.
what is a reference?
Answer:
See entity reference.

Question 245.
What is registry?
Answer:
An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

Question 246.
what is a registry provider?
Answer:
An implementation of a business registry that conforms to a specification for XML registries (for example, ebXML or UDDI).

Question 247.
What is the relationship field?
Answer:
A virtual field of an entity bean having container-managed persistence; it identifies a related entity bean.

Question 248.
What is the remote interface?
Answer:
One of two interfaces for an enterprise bean. The remote interface defines the business methods callable by a client.

Question 249.
What is the remove method?
Answer:
Method defined in the home interface and invoked by a client to destroy an enterprise bean.

Question 250.
What is a render kit?
Answer:
A set of Tenderers that render output to a particular client. The JavaServer Faces implementation provides a standard HTML render kit, which is composed of Tenderers that can render HMTL markup.

Question 251.
What is renderer?
Answer:
A Java class that can render the output for a set of JavaServer Faces UI components.

Question 252.
What is request-response messaging?
Answer:
A method of messaging that includes blocking until a response is received. What is a resource adapter A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs into a container.

The application components deployed on the container then use the client API (exposed by the adapter) or tool¬generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

Question 253.
What is the resource adapter module?
Answer:
A deployable unit that contains all Java interfaces, classes, and native libraries, implementing a resource adapter along with the resource adapter deployment descriptor.

Question 254.
What is resource manager?
Answer:
Provides access to a set of shared resources. A resource manager participates in transactions that are externally controlled and coordinated by a transaction manager. A resource manager typically is in a different address space or on a different machine from the clients that access it. Note: An enterprise information system is referred to as a resource manager when it is mentioned in the context of resource and transaction management.

Question 255.
What is a resource manager connection?
Answer:
An object that represents a session with a resource manager.

Question 256.
What is a resource manager connection factory?
Answer:
An object used for creating a resource manager connection.

Question 257.
What is RMI?
Answer:
Remote Method Invocation. A technology that allows an object running in one Java virtual machine to invoke methods on an object running in a different Java virtual machine.

Question 258.
What is RMI-IIOP?
Answer:
A version of RMI implemented to use the CORBA HOP protocol. RMI over HOP provides interoperability with CORBA objects implemented in any language if all the remote interfaces are originally defined as RMI interfaces.

Question 259.
What is role (development)?
Answer:
The function is performed by a party in the development and deployment phases of an application developed using J2EE technology. The roles are application component provider, application assembler, deployer, J2EE product provider, EJB container provider, EJB server provider, Web container provider, Web server provider, tool provider, and system administrator.

Question 260.
What is role mapping?
Answer:
The process of associating the groups or principals (or both), recognized by the container with security roles specified in the deployment descriptor. Security roles must be mapped by the deployer before a component is installed in the server.

Question 261.
What is the role (security)?
Answer:
An abstract logical grouping of users is defined by the application assembler. When an application is deployed, the roles are mapped to security identities, such as principals or groups, in the operational environment.
In the J2EE server authentication service, a role is an abstract name for permission to access a particular set of resources. A role can be compared to a key that can open a lock. Many people might have a copy of the key; the lock doesn’t care who you are, only that you have the right key.

Question 262.
What is rollback?
Answer:
The point in a transaction is when all updates to any resources involved in the transaction are reversed.
What is root?
Answer:
The outermost element in an XML document. The element that contains all other elements.

Question 263.
What is SAX?
Answer:
Abbreviation of Simple API for XML.

Question 264.
What is a Simple API for XML?
Answer:
An event-driven interface in which the parser invokes one of several methods supplied by the caller when a parsing event occurs. Events include recognizing an XML tag, finding an error, encountering a reference to an external entity, or processing a DTD specification.

Question 265.
What is schema?
Answer:
A database-inspired method for specifying constraints on XML documents using an XML-based language. Schemas address deficiencies in DTDs, such as the inability to put constraints on the kinds of data that can occur in a particular field. Because schemas are founded on XML, they are hierarchical. Thus it is easier to create an unambiguous specification, and it is possible to determine the scope over which comment is meant to apply.

Question 266.
What is a Secure Socket Layer (SSL)?
Answer:
A technology that allows Web browsers and Web servers to communicate over a secured connection.

What are security attributes?
Answer:
A set of properties associated with a principal. Security attributes can be associated with a principal by an authentication protocol or by a J2EE product provider or both.

Question 267.
What is a security constraint?
Answer:
A declarative way to annotate the intended protection of Web content. A security constraint consists of a Web resource collection, an authorization constraint, and a user data constraint.

Question 268.
What is security context?
Answer:
An object that encapsulates the shared state information regarding security between two entities.

Question 269.
What is security permission?
Answer:
A mechanism defined by J2SE and used by the J2EE platform to express the programming restrictions imposed on application component developers.

Question 270.
What is a security permission set?
Answer:
The minimum set of security permissions that a J2EE product provider must provide for the execution of each component type.

Question 271.
What is the security policy domain?
Answer:
A scope over which security policies are defined and enforced by a security administrator. A security policy domain has a collection of users (or principals), uses a well-defined authentication protocol or protocols for authenticating users (or principals), and may have groups to simplify the setting of security policies.

Question 272.
What is the security role?
Answer:
See role (security).

Question 273.
What is the security technology domain?
Answer:
A scope over which the same security mechanism is used to enforce a security policy. Multiple security policy domains can exist within a single technology domain.

Question 274.
What is a security view?
Answer:
The set of security roles is defined by the application assembler.

Question 275.
What is server certificate?
Answer:
Used with the HTTPS protocol to authenticate Web applications. The certificate can be self-signed or approved by a certificate authority (CA). The HTTPS service of the Sun Java System Application Server Platform Edition 8 will not run unless a server certificate has been installed.

Question 276.
What is server principal?
Answer:
The OS principal that the server is executing as.

Question 277.
What is service element?
Answer:
A representation of the combination of one or more Connector components that share a single-engine component for processing incoming requests.

Question 278.
What is the service endpoint interface?
Answer:
A Java interface that declares the methods that a client can invoke on a Web service.

Question 279.
What is a servlet?
Answer:
A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web applications using a request-response paradigm.

Question 280.
What is a servlet container?
Answer:
A container that provides the network services over which requests and responses are sent, decodes requests, and formats responses. All servlet containers must support HTTP as a protocol for requests and responses but can also support additional request-response protocols, such as HTTPS.

Question 281.
What is servlet container, distributed?
Answer:
A servlet container that can run a Web application that is tagged as distributable and that executes across multiple Java virtual machines running on the same host or on different hosts.

Question 282.
What is servlet context?
Answer:
An object that contains a servlet’s view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use

Question 283.
What is servlet mapping?
Answer:
Defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

Question 284.
What is a session?
Answer:
An object used by a servlet to track a user’s interaction with a Web application across multiple HTTP requests. What is session bean?
An enterprise bean that is created by a client and that usually exists only for the duration of a single client-server session. A session bean performs operations, such as calculations or database access, for the client. Although a session bean can be transactional, it is not recoverable should a system crash occur.

Session bean objects either can be stateless or can maintain a conversational state across methods and transactions. If a session bean maintains a state, then the EJB container manages this state if the object must be removed from memory. However, the session bean object itself must manage its own persistent data.

Question 285.
What is SGML?
Answer:
Standard Generalized Markup Language. The parent of both HTML and XML. Although HTML shares SGML’s propensity for embedding presentation information in the markup, XML is a standard that allows information content to be totally separated from the mechanisms for rendering that content.

Question 286.
What is SOAP?
Answer:
Simple Object Access Protocol. A lightweight protocol intended for exchanging structured information in a decentralized, distributed environment. It
defines, using XML technologies, an extensible messaging framework containing a message construct that can be exchanged over a variety of underlying protocols.

Question 287.
What is SOAP with Attachments API for Java (SAAJ)?
Answer:
The basic package for SOAP messaging, SAAJ contains the API for creating and populating a SOAP message.

Question 288.
What is SQL?
Answer:
Structured Query Language. The standardized relational database language for defining database objects and manipulating data.

Question 289.
What is SQL/J?
Answer:
A set of standards that includes specifications for embedding SQL statements in methods in the Java programming language and specifications for calling Java static methods as SQL stored procedures and user-defined functions. An SQL checker can detect errors in static SQL statements at program development time, rather than at execution time as with a JDBC driver.

Question 290.
What is SSL?
Answer:
Secure Socket Layer. A security protocol that provides privacy over the Internet. The protocol allows client-server applications to communicate in a way that cannot be eavesdropped upon or tampered with. Servers are always authenticated, and clients are optionally authenticated.

Question 291.
What is a template?
Answer:
A set of formatting instructions that apply to the nodes selected by an XPath expression.

Question 292.
What is a tool provider?
Answer:
An organization or software vendor that provides tools used for the development, packaging, and deployment of J2EE applications.

Question 293.
What is the topic?
Answer:
See publish-subscribe messaging system.

Question 294.
What is a transaction?
Answer:
An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which are either complete or rollback. Transactions enable multiple users to access the same data concurrently.

Question 295.
What is a transaction attribute?
Answer:
A value specified in an enterprise bean’s deployment descriptor is used by the EJB container to control the transaction scope when the enterprise bean’s methods are invoked. A transaction attribute can have the following values: Required, RequiresNew, Supports, NotSupported, Mandatory, or Never.

Question 296.
What is the transaction isolation level?
Answer:
The degree to which the intermediate state of the data being modified by a transaction is visible to other concurrent transactions and data being modified by other transactions is visible to it.

Question 297.
What is transaction manager?
Answer:
Provides the services and management functions required to support transaction demarcation, transactional resource management, synchronization, and transaction context propagation.

Question 298.
what is Unicode?
Answer:
A standard defined by the Unicode Consortium uses a 16-bit code page that maps digits to characters in languages around the world. Because 16 bits covers 32,768 codes, Unicode is large enough to include all the world’s languages, with the exception of ideographic languages that have a different character for every concept, such as Chinese.

Question 299.
What is Universal Description, Discovery, and Integration (UDDI) project?
Answer:
An industry initiative to create a platform-independent, open framework for describing services, discovering businesses, and integrating business services using the Internet, as well as a registry. It is being developed by a vendor consortium.

Question 300.
What is Universal Standard Products and Services Classification (UNSPSC)?
Answer:
A schema that classifies and identifies commodities. It is used in sell-side and buy-side catalogs and as a standardized account code in analyzing expenditure.

Question 301.
what is an unparsed entity?
Answer:
A general entity that contains something other than XML. By its nature, an unparsed entity contains binary data.

Question 302.
What is user data constraint?
Answer:
Indicates how data between a client and a Web container should be protected. The protection can be the prevention of tampering with the data or the prevention of eavesdropping on the data.

Question 303.
What is a user (security)?
Answer:
An individual (or application program) identity that has been authenticated. A user can have a set of roles associated with that identity, which entitles the user to access all resources protected by those roles.

Question 304.
What is valid?
Answer:
A valid XML document, in addition to being well formed, conforms to all the constraints imposed by a DTD. It does not contain any tags that are not permitted by the DTD, and the order of the tags conforms to the DTD’s specifications.

Question 305.
What is validating parser?
Answer:
A parser that ensures that an XML document is valid in addition to being well formed. See also parser.

Question 306.
What is value-binding expression?
Answer:
A JavaServer Faces EL expression that refers to a property of a backing bean. A component tag uses this expression to bind the associated component’s value or the component instance to the bean property. If the component tag refers to the property via its value attribute, then the component’s value is bound to the property. If the component tag refers to the property via its binding attribute then the component itself is bound to the property.

Question 307.
What is a virtual host?
Answer:
Multiple hosts plus domain names mapped to a single IP address.

Question 308.
What is Xalan?
Answer:
An interpreting version of XSLT.

Question 309.
What is XHTML?
Answer:
An XML look-alike for HTML defined by one of several XHTML DTDs. To use XHTML for everything would of course defeat the purpose of XML because the idea of XML is to identify information content, and not just to tell how to display it. You can reference it in a DTD, which allows you to say, for example, that the text in an element can contain <em> and <b> tags rather than being limited to plain text.

Question 310.
WhatisXLink?
Answer:
The part of the XLL specification is concerned with specifying links between documents.

Question 311.
What is XLL?
Answer:
The XML Link Language specification, consisting of XLink and XPointer.

Question 312.
What is XML?
Answer:
Extensible Markup Language. A markup language that allows you to define the tags (markup) needed to identify the content, data, and text in XML documents. It differs from HTML, the markup language most often used to present information on the Internet. HTML has fixed tags that deal mainly with style or presentation.

An XML document must undergo a transformation into a language with style tags under the control of a style sheet before it can be presented by a browser or other presentation mechanism. Two types of style sheets used with XML are CSS and XSL. Typically, XML is transformed into HTML for presentation. Although tags can be defined as needed in the generation of an XML document, a document type definition (DTD) can be used to define the elements allowed in a particular type of document. A document can be compared by using the rules in the DTD to determine its validity and to locate particular elements in the document. A Web services application’s J2EE deployment descriptors are expressed in XML with schemas defining allowed elements. Programs for processing XML documents use SAX or DOM APIs.

Question 313.
What is XML registry?
Answer:
See registry.

Question 314.
What is XML Schema?
Answer:
The W3C specification for defining the structure, content, and semantics of XML documents.

Question 315.
Explain DOM and SAX Parser?
Answer:
DOM parser is one which makes the entire XML passed as a tree Structure and will have it in memory. Any modification can be done to the XML.
SAX parser is one that triggers predefined events when the parser encounters the tags in XML, an Event-driven parser. Entire XML will not be stored in memory. Bit faster than DOM. NO modifications can be done to the XML.

Question 316.
What types of Servlets do you know?
Answer:
There are two types of Servlets – GenericServlet and HttpServlet.

Question 317.
What is the difference between HttpServlet and GenericServlet?
Answer:
GenericServlet has a service( ) method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet( ), doPost( ), doHead( ) methods (HTTP 1.0) plus doPut( ), doOptions( ), doDelete( ), doTrace( ) methods (HTTP 1.1). Both these classes are abstract.

Question 318.
What is the difference between doGet() and doPostO?
Answer:
doGet( ) method is limited with 2k of data to be sent, and the doPost( ) method doesn’t have this limitation. A request string for doGet( ) looks like the following: http://www.server.com/servlet7param l=valuel&param2=value2&…&paramN=valu eN
doPost(  ) method call doesn’t need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it’s impossible to guess the data transmitted to a servlet only looking at a request string.

Question 319.
What are the methods in HttpServlet?
Answer:
Methods of HttpServlet can be divided into 3 groups:

1. Initialization methods. These methods are inherited from GenericServlet interface. They include init (ServletConfig config) (allowing initializing a servlet with the prepared or existing config), ServletConfig getServletConfig( ) I (the opposite method), destroy( ) (removing a servlet), ServletContext getServletContext( ) (to obtain the context of a servlet), log methods (logging
| servlet operations).

2. Request processing methods. These are the methods listed in point 2 of this document plus get the last modified(HttpServletRequest request) method.

3. Programmer-defined methods. These methods are written by a programmer and are not regulated by Sun’s Servlet specification.

Question 320.

Why do you need to use session tracking?
Answer:

Session tracking becomes necessary when you are exchanging any information with the visitor and don’t want to lose this information. Session tracking j is the most convenient and easy way of unique client identification.

Question 321.
What are the types of session tracking?
Answer:
There are 4 types of session tracking: using cookies for identifying a client (reading a cookie each time a page is requested), using URL rewriting mechanism (appending the session id to each URL), using SSL built-in session tracking mechanisms, and hiding the session information in hidden fields of an HTML form (e.g. login name).

Question 322.
What are cookies? Why are cookies widely used?
Answer:
Cookies are little (up to 4k) pieces of text stored by the server on a client’s machine. Cookies are a standard way to store persistent session information (shopping cart, client’s preferences, etc.). Every Web server supports cookies, and more than 80% of clients keep cookies options turned on in their Internet browsers.

Question 323.
What will happen if my servlet attempts to write a cookie to the client’s machine, and his browser doesn’t accept cookies?
Answer:
Nothing will happen except you will be unable to read this cookie from a client.

Question 324.
Can I use JavaScript in servlets?
Answer:
You can include JavaScript code to the servlet response (i.e. to the generated page), but not to the servlet code itself.

Question 325.
What are the types of protocols used in HttpServlet?
Answer:
HttpServlet class was developed for usage with HTTP and HTTPS protocols.

C Interview Questions in Java

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

C Interview Questions in Java

Question 1. What is the C language?
Answer:

  • C language is a structure/procedure-oriented, middle-level programming language developed at Bell Laboratories in 1972 by Dennis Ritchie.
  • C language was invented for implementing UNIX operating system.
  • In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language”.
  • Also, C language is an ANSI/ISO standard and powerful programming language for developing real-time applications

Question 2.
Who developed the C language?
Answer:
C programming language was developed at Bell Laboratories in 1972 by Dennis Ritchie.

Question 3.
Where is the C programming language used or uses of the C language?
Answer:
C language is used to develop system applications that form the major portion of operating systems such as Windows, UNIX, and Linux. Operating systems, C compiler, and all UNIX application programs are written in C language. Below are some examples of uses of the C language.

  • Database systems
  • Graphics packages
  • Word processors
  • Spreadsheets
  • Operating system development
  • Compilers and Assemblers
  • Network drivers
  • Interpreters

Question 4.
What is the difference between C and C++?
Answer:
Even though C and C++ programming languages are belonging to middle
level languages, both are differed in below.

  • C is a structure/procedure-oriented programming language whereas C++ is an object-oriented programming language.
  • C language program design is a top-down approach whereas C++ is using a bottom-up approach.
  • Polymorphism, virtual function, inheritance, Operator overloading, namespace concepts are not available in the C programming language. Whereas C++ language supports all these concepts and features.
  • C language gives importance to functions rather than data. Whereas C++ gives importance to data rather than functions.
  • So, data and function mapping are difficult in C. But, data and function mapping are simple in C++ that can be done using objects.
  • C language does not support user define data types. Whereas C++ supports user define data types.
  • Exception handling is not present in the C programming language. Whereas exception handling is present in the C++ language.
  • C language allows data to freely flow around the functions. But, data and functions are bound together in C++ which does not allow data to freely flow around the functions.

Question 5.
What is the difference between the top-down approach and the bottom-up approach in programming languages?
Answer:
The top-down approach and bottom-up approach are involved in software
development. These approaches are not involved in program execution.

  • Structure/procedure-oriented programming languages like the C programming language follow a top-down approach. Whereas object-oriented programming languages like C++ and Java programming language follow a bottom-up approach.
  • The top-down approach begins with high-level design and ends with low-level design or development. Whereas, the bottom-up approach begins with low-level design or development and ends with high-level design.
  • In the top-down approach, the main( ) function is written first and all sub-functions are called from the main function. Then, sub-functions are written based on the requirement. Whereas, in the bottom-up approach, code is developed for modules and then these modules are integrated with the main( ) function.
  • Now-a-days, both approaches are combined together and followed in modern software design.

Question 6.
What is the difference between C and Java?
Answer:

  • C is a structure/procedure-oriented programming language whereas Java is an object-oriented programming language.
  • C language program design is a top-down approach whereas Java is using a bottom-up approach.
  • C language is a middle-level language whereas Java is a high-level language.
  • Exception handling is not present in the C programming language. Whereas exception handling is present in Java.
  • Polymorphism, virtual function, inheritance, Operator overloading, namespace concepts are not available in the C programming language. Whereas Java supports all these concepts and features.

Question 7.
C language has been developed in which language?
Answer:
C language has been developed using assembly-level language.

Question 8.
Which year C language is developed?
Answer:
C programming language was developed at Bell Laboratories in 1972 by Dennis Ritchie.

Question 9.
What is meant by programming language and give some examples?
Answer:

  • Programming language is nothing but a language designed to communicate to machines through instructions and commands.
  • Normally machines are computers. Programs are written using some programming languages to control the behavior of machines/computers and to make them perform required tasks.
  • Programming language example: Assembly language, C language, C++ language, Java, C#, .NET, Python, etc.,

Question 10.
Describe C standards.
Answer:

  • C89/C90 standard—First standardized specification for C language was developed by American National Standards Institute in 1989. C89 and C90 standards refer to the same programming language.
  • C99 standard – Next revision was published in 1999 that introduced new futures like advanced data types and other changes.
  • C11 standard adds new features to C and library like type generic macros, anonymous structures, improved Unicode support, atomic operations, multi¬threading, and bounds-checked functions. It also makes some portions of the existing C99 library optional and improves compatibility with C++.

Question 11.
What are the key features or characteristics of the C language?
Answer:

  • Reliability
  • Portability
  • Flexibility
  • Interactivity
  • Modularity
  • Efficiency and Effectiveness

Question 12.
What is embedded C?
Answer:

  • Embedded C is the extension of the C programming language.
  • Embedded C is used to develop microcontroller-based applications.
  • Embedded C includes features not available in normal C like fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.
  • Cell phones, MP3 players are some examples of embedded systems in which embedded C is used to program and control these devices.

Question 13.
Which level is the C language belonging to?
Answer:

  • C language is belonging to middle-level language. C language behaves as a bridge between machine-level (low-level) languages and high-level languages.
  • C language is more user-friendly than machine-level languages. And, C language does not support all the concepts that high-level languages offer. So, the C programming language is called middle-level language.

Question 14.
What do you mean by high level, middle level, and low-level languages, and give an example for each?
Answer:
High-level languages –

  • These level languages provide almost everything that the programmer might need to do as already build into the language.
  • Example: Java, Python

Middle-level languages –

  • These languages don’t provide all the built-in functions found in high-level languages but provide all the building blocks that we need to produce the result we want.
  • Example: C, C++

Low-level languages –

  • These languages provide nothing other than access to the machine’s basic instruction set.
  • Example: Assembly language

Question 15.
What is the difference between structured-oriented, object-oriented, and non-structure-oriented programming languages?
Answer:
Structured oriented programming language –

  • In this type of language, large programs are divided into small programs called functions.
  • The prime focus is on functions and procedures that operate on data
  • Data moves freely around the systems from one function to another
  • Program structure follows “Top-Down Approach”
  • Example: C, Pascal, ALGOL, and Modula-2

Object-oriented programming language –

  • In this type of language, programs are divided into objects
  • The prime focus is on the data that is being operated and not on the functions or procedures
  • Data is hidden and cannot be accessed by external functions
  • Program structure follows “Bottom UP Approach”
  • Example: C++, JAVA, and C# (C sharp)

Non-structure oriented programming language –

  • There is no specific structure for programming this language.
  • Example: BASIC, COBOL, FORTRAN
Question 16.
What is a compiler?
Answer:
The compiler is a program that converts human-readable code into machine-readable code. This process is called compilation.
Question 17.
What is the difference between assembler, compiler, and interpreter?
Answer:
  • Assembler is a program that converts assembly-level language (low-level language) into machine-level language.
  • The compiler compiles the entire C source code into machine code. Whereas interpreters convert source code into intermediate code and then this intermediate code is executed line by line.
Question 18.
What is printf( )?
Answer:
  • printf( ) is an inbuilt library function in C which is available in the C library by default. This function is declared and related macros are defined in “stdio.h” header file.
  • printf( ) function is used to print the “character, string, float, integer, octal, and hexadecimal values” onto the output screen.
Question 19.
What is scanf( )?
Answer:
  • scanf( ) function is an inbuilt library function in C that is available in the C library by default. This function is declared and related macros are defined in “stdio.h” header file.
  • scanf( ) function is used to read character, string, numeric data from the keyboard.
Question 20.
What is meant by protocol?
Answer:
The protocol is nothing but a set of rules to be followed by a programmer.
Question 21.
Execution of a C program starts from which function?
Answer:
Always, execution of a C program starts from the main( ) function.
Question 22.
What are all the sections that a C program may/must-have?
Answer:
There are many sections in a C program structure. They are,
  • Documentation section
  • Link Section
  • Definition Section
  • Global declaration section
  • Function prototype declaration section
  • Main function
  • User-defined function section
main( ) function section is the important section in a C program as program execution starts from main( ) function only in the C language. A-C program may not have all other sections except the main( ) function.
Question 23.
What is IDE?
Answer:
  • IDE is nothing but Integrated Development Environment. IDE is a tool that provides a user interface with compilers to create, compile and execute C programs.
  • Example: Turbo C++, Borland C++, and DevC++. These provide Integrated Development Environment with a compiler for both C and C++ programming languages.
Question 24.
List out some of C compilers.
Answer:
There are so many compilers available in the market for Windows operating system and UNIX. We are listing some of them here for your reference.
  • AMPC
  • CCS C Compiler
  • ch
  • clang
  • Cygwin
  • Digital mars
  • GCC compiler
  • MikroC Compiler
  • Portable C Compiler, Power C, QuickC, Ritchie C Compiler, Small-C
Question 25.
What is the header file in C language?
Answer:
  • The header file is a file that contains function declaration and macro definition for C in-built library functions.
  • All C standard library functions are declared in many header files which are saved as file_name.h.
  • We are including these header files in our C program using the “#include <file_name. h>” command to make use of the functions that are declared in the header files.
  • When we include header files in our C program using the “#include <filename.h>” command, all C codes of the header files are included in the C program. Then, this C program is compiled by the compiler and executed.
Question 26.
Is C language case sensitive?
Answer:
Yes. C language instructions/commands/functions and everything used in C programs is case-sensitive.
Question 27.
What is a data type in C?
Answer:
  • Data types in C language are defined as the data storage format that a variable that can store data to perform a specific operation.
  • Data types are used to define a variable before use in a program.
  • Size of variable, constant, and array are determined by data types.
Question 28.
What is the difference between int, char, float & double data types?
Answer:
  • The integer data type allows a variable to store numeric values. The storage size of int data type is 2 or 4 or 8 bytes. It varies depending upon the processor in the CPU.
  • Character data type allows a variable to store only one character. The storage size of the character data type is 1.
  • The float data type allows a variable to store decimal values. The storage size of float data type is 4. This also varies depending upon the processor in the CP.
  • The double data type is also the same as the float data type which allows up to 10 digits after the decimal.
Question 29.
What is the use of sizeof( ) function in C?
Answer:
sizeof( ) function is used to find the memory space allocated for each data type in C.
Question 30.
What is a modifier in C?
Answer:
  • The amount of memory space to be allocated for a variable is derived by modifiers.
  • Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage space allocated to a variable.
  • For example, storage space for the int data type is 4 bytes for the 32-bit processor. We can increase the range by using long int which is 8 bytes. We can decrease the range by using short int which is 2 bytes.
Question 31.
What are the different types of modifiers in C?
Answer:
There are 5 modifiers available in the C language. They are,
  • short
  • long
  • signed
  • unsigned
  • long long
Question 32.
What is enum in C?
Answer:
  • Enumeration is a data type that consists of named integer constants as a list.
  • It starts with 0 (zero) by default and the value is incremented by 1 for the sequential identifiers in the list.
Question 33.
What is void in C?
Answer:
Void is an empty data type that has no value.
  • We use void data type in functions when we don’t want to return any value to the calling function.
Example:
void sum (int a, int b); – This function won’t return any value to the calling function.
int sum (int a, int b); – This function will return value to the calling function.
  • We use void data type in pointer like “void *p”. It means pointer “p” is neither ‘ pointing to int data type nor char data type. It acts as a generic pointer. We are using a void pointer when we are not sure on the data type that this pointer will point to. We can use the void pointer to refer to either integer data or char data. But, this void pointer should not be dereferenced without explicit typecasting.
  • We use void in functions as “int function_name (void)”. Here void means, this function does not pass any argument.
Question 34.
What is token in C?
Answer:
  • C tokens are the basic buildings blocks in the C language which are constructed together to write a C program.
  • Each and every smallest individual unit in a C program are known as C tokens.
Question 35.
What are the types of C tokens?
Answer:
C tokens are of six types. They are,
  • keywords                (eg: int, while),
  • Identifiers               (eg: main, total),
  • Constants               (eg: 10, 20),
  • Special symbols     (eg: “total”, “hello”),
  • Special Symbols    (eg: 0, 0),
  • Operators              (eg: +, /,-,*)
Question 36.
What is the identifier in C?
Answer:
  • Each program element in a C program is given a name called identifiers.
  • Names given to identify Variables, functions and arrays are examples of identifiers.
  • Example: x is a name given to an integer variable in the above program
Question 37.
What is a keyword in C?
Answer:
  • Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific function in a C program.
  • Since keywords are referred names for compilers, they can’t be used as variable names.
Question 38.
List out some keywords available in the C language.
Answer:
  • Below are some of the keywords that C language offers.
  • auto, double, int, struct, break, else, long, switch, case, enum, register, typedef, char, extern, return, union, const, float, short, unsigned, continue, for, signed, void, default, goto, size, volatile, do, if, static, while
Question 39.
What is constant in C?
Answer:
  • Constants refer to fixed values. They are also called literals.
  • C Constants are also like normal variables. But, the only difference is, constant values can’t be modified by the program once they are defined. Constants may be belonging to any of the data types.
Question 40.
What are the types of constants in C?
Answer:
  • Integer constants
  • Real or Floating-point constants
  • Octal & Hexadecimal constants
  • Character constants
  • String constants
  • Backslash character constants
Question 41.
What is variable in C?
Answer:
  • C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
  • The value of the C variable may get change in the program.
  • C variable might be belonging to any of the data types like int, float, char, etc.
Question 42.
What is the difference between constant and variable in C?
Answer:
Constant values can’t be modified by the program once it is declared. But, variable values can be modified by the program.
Question 43.
Can variable names start with numbers?
Answer:
No. Variable names can’t start with numbers as per the variable naming rule.
Question 44.
What is the difference between variable declaration and variable definition in C?
Answer:
  • the variable declaration tells the compiler about the data type and size of the variable. Whereas, variable definition allocates memory to the variable
  • Variable can be declared many times in a program. But, the definition can happen only one time for a variable in a program.
  • Variable declaration is for the assignment of properties and identification to a variable. Whereas, a variable definition is for assignments of storage space to a variable
Question 45.
What are the different types of variables in C?
Answer:
  • Local variable
  • Global variable
  • Environment variable
Question 46.
What is the local variable in C?
Answer:
  • The variables which are having scope/life only within the function are called local variables.
  • These variables are declared within the function and can’t be accessed outside the function.
Question 47.
What is the global variable in C?
Answer:
  • The variables which are having scope/life throughout the program are called global variables.
  • A global variable is defined outside the main function. So, this variable is visible to the main function and all other sub-functions.
Question 48.
What is the environment variable in C?
Answer:
  • The environment variable is a variable that will be available for all C applications and C programs.
  • Once environment variables are exported, we can access them from anywhere in a C program without declaring and initializing them in an application or C program.
Question 49.
What is an operator in C?
Answer:
  • The symbols which are used to perform logical and mathematical operations in a C program are called C operators.
  • These C operators join individual constants and variables to form expressions. Operators, functions, constants, and variables are combined together to form expressions.
Question 50.
What are the different types of operators in C?
Answer:
C language offers many types of operators. They are,
  1. Arithmetic operators
  2. Assignment operators
  3. Relational operators
  4. Logical operators
  5. Bitwise operators
  6. Conditional operators (ternary operators)
  7. Increment/decrement operators
  8. Special operators
Question 51.
What is the syntax for the ternary operator in C?
Answer:
  • The ternary operator is the same as the if-else control statement in C.
  • Syntax : (Condition? true_value: false_value);
  • Example: (A > 100? 0: 1);
Question 52.
Answer:
  • C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, and modulus in C programs.
  • Arithmetic operators are +, -, *, /, %
Question 53.
Answer:
  • Assignment operators are used to assigning the values to the variables.
  • Assignment operators are =, +=, -=, /+, %= etc.
Question 54.
What is the relational operator in C?
Answer:
  • Relational operators are used to finding the relation between two variables, i.e. to compare the values of two variables in a C program.
  • Relational operators are >, <, >=, <=, ==, !=
Question 55.
What is the logical operator in C?
Answer:
  • Logical operators are used to performing logical operations on the given expressions.
  • There are 3 logical operators in the C language. They are,
1. logical AND (&&)
2. logical OR (||)
3. logical NOT (!)

Question 56.
What is a bitwise operator in C?
Answer:

  • Bitwise operators are used to performing bit operations. Decimal values are
    converted into binary values which are the sequence of bits and bit-wise operators work on these bits.
  • Bitwise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), A (XOR), << (left shift) and >> (right shift).

Question 57.
Differentiate between the expression “++a” and “a++”?
Answer:

  • With ++a, the increment happens first on variable a, and the resulting value is used. This is called prefix increment.
  • With a++, the current value of the variable will be used in an operation. This is called a postfix increment.

Question 58.
What are all decision control statements in C?
Answer:
There are 3 types of decision-making control statements in C language. They are,

  1. if statements
  2. if-else statements
  3. nested if statements

Question 59.
What are all loop control statements in C?
Answer:

  • Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once the condition becomes false.
  • There are 3 types of loop control statements in C language. They are,

1. for
2. while
3. do-while

Question 60.
What are the difference between while and do-while loops in C?
Answer:

  • While loop is executed only when a given condition is true.
  • Whereas, do-while loop is executed for the first time irrespective of the condition. After executing the while loop for the first time, the condition is checked.

Question 61.
What is the difference between single equal “=” and double equal “=” operators in C?
Answer:

  • Single equal is an assignment operator used to assign the values to the variables.
  • But, double equal is the relational operator used to compare two variable values whether they are equal are not.

Question 62.
What is the difference between the pre-increment operator and post-increment operator in C?
Answer:

  • The pre-increment operator is used to increment variable value by 1 before assigning the value to the variable.
  • The post-increment operator is used to increment variable value by 1 after assigning the value to the variable.

Question 63.
What is the difference between the pre decrement operator and the post decrement operator?
Answer:

  • Pre decrement operator is used to decrement the variable value by 1 before assigning the value to the variable.
  • Post decrement operator is used to decrement the variable value by 1 after assigning the value to the variable.

Question 64.
What are “&” and operators in C?
Answer:

  • The operator is used as a pointer to a variable. Example: * a where * is a pointer to the variable a.
  • & operator is used to getting the address of the variable. Example: &a will give the address of a.

Question 65.
What will happen if the break statement is not used in the switch case in C?
Answer:

  • Switch case statements are used to execute only specific case statements based on the switch expression.
  • If we do not use a break statement at the end of each case, the program will execute all consecutive case statements until it finds the next break statement or till the end of the switch case block.

Question 66.
Why is the default statement used in the switch case in C?
Answer:
Switch case statements are used to execute only specific case statements based on the switch expression. If the switch expression does not match with any case, default statements are executed by the program.

Question 67.
What is the use of the “goto” statement?
Answer:
the goto statement is used to transfer the normal flow of a program to the specified labl in the program. Below is the syntax for the goto statement in C.

{
..... .
goto label;
..... .
..... .
LABEL:
statements;
}

Question 68.
What value will be assigned to the variable X if a = 10, b = 20, c = 30, d = 40 in below expression?
Answer:
X = a/b+c*d-c;

  • The above arithmetic operation is performed based on the precedence of the operators.
  • In above mentioned expression, c*d will be performed first. Then, a/b, then (c*d)-c, then (a/b) + ((c*d)-c).
  • Please check the operator precedence table to know the priority and associativity of the C operators.
  • The output of the above expression is 1170.

Example program: 

#include <stdio.h>
#include <stdlib.h>
int main( )
{

int a = 10, b = 20, c = 30, d = 40, X ; 

x = a/b+c*d-c;.
printf(“ value of x = %d\n”, x); 
return 0;
}

Output: Value of X = 1170

Question 69.
What value is assigned to the below variables?
Answer:
int Xl = 13/3;
mt X2 = 13%3;

  • The value of XI is 4
  • The value of X2 is 1

Question 70.
What is the difference between auto variable and register variable in C?
Answer:
Storage class of all variables are auto by default unless we specify a variable is register or static or extern in C program.

  • Both auto variables and register variables are local variables. Register variables are stored in register memory. Whereas, auto variables are stored in main CPU memory.
  • Register variables will be accessed very faster than the normal/auto variables since they are stored in register memory rather than main memory.
  • But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)

Question 71.
What is the difference between auto variable and static variable in C?
Answer:

  • Both auto and static variables are local variables.
  • Static variables can retain the value of the variable between different function calls.
  • But, scope of auto variable is within the function only. It can’t retain the value of the variable between different function calls.

Question 72.
Where should type cast function not be used in C?
Answer:

  • Typecast function should not be used in const and volatile declaration.
  • Because constant values can’t be modified by the program once they are defined.
  • And, volatile variable values might keep on changing without any explicit assignment by the program as operating system will be modifying these values.

Question 73.
How will you print “Hello World” without semicolon?
Answer:

int main(void){
if (printf(“Hello world”)) ;
}

Question 74.
Why is C language being considered a middle level language?
Answer:
This is because C language is rich in features that make it behave like a high level language while at the same time can interact with hardware using low level methods. The use of a well structured approach to programming, coupled with English-like words used in functions, makes it act as a high level language. On the other hand, C can directly access memory structures similar to assembly language routines.

Question 75.
What are the different file extensions involved when programming in C?
Answer:
Source codes in C are saved with .C file extension. Header files or library files have the .H file extension. Every time a program source code is successfully compiled, it creates an .OBJ object file, and an executable .EXE file.

Question 76.
What are reserved words?
Answer:
Reserved words are words that are part of the standard C language library. This means that reserved words have special meaning and therefore cannot be used for purposes other than what it is originally intended for. Examples of reserved words are int, void, and return.

Question 77.
Why is c considered as a high level language and a low level language?
Answer:
C is a high-level language because it abstracts away a large part of the underlying machine; instead of dealing with registers and op codes, you are dealing with objects and expressions. Streams are abstractions of communications channels, pointers are abstractions of memory addresses, etc. However, Cs abstractions are fairly basic; you still have to be aware of limitations on memory, you have to be aware of how types and operations may be mapped onto the underlying hardware, and you have to be aware that some aspects of the language are left to the individual implementation (compiler or interpreter) to define.

C makes you *think* you are working at the hardware level, even though you aren’t in most cases. Compare this with languages like Haskell or Lisp, where there is no hint of an underlying hardware platform; types are not limited by what an individual platform can represent (as opposed to C), there are no obvious constraints on memory (until performance begins to suffer, anyway).

Question 78.
What is the difference between getch( ) and getche( )?
Answer:
Both getch( ) and getche( ) are used to read single character there is very little difference

  • Both functions accept a character input value from the user.
  • When getch( ) is used, the key that was pressed will not appear on the screen. It is automatically captured and assigned to a variable.
  • While when getche( ) is used,, the key that was pressed by the user appears on the screen and is assigned to a variable.

Question 79.
How do you construct an increment statement or decrement statement in C?
Answer:
There are actually two ways you can do this. One is to use the increment operator ++ and decrement operator For example, the statement “x++” means to increment the value of x b}- 1. Likewise; the statement “x -” means to decrement the value of x by 1. Another way of writing increment statements is to use the conventional + plus sign or – minus sign. In the case of “x++”, another way to write it is “x = x +1″.

Question 80.
Are comments included during the compilation stage and placed in the EXE file as well?
Answer:
No, comments that were encountered by the compiler are disregarded. Comments are mostly for the guidance of the programmer only and do not have any other significant use in the program functionality.

Question 81.
What is a sequential access file?
Answer:
When writing programs that will store and retrieve data in a file, it is possible to designate that file into different forms. A sequential access file is such that data are saved in sequential order: one data is placed into the file after another. To access a particular data within the sequential access file, data has to be read one data at a time, until the right one is reached.

Question 82.
What is variable initialization and why is it important?
Answer:
This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.

Question 83.
What is spaghetti programming?
Answer:
Spaghetti programming refers to codes that tend to get tangled and overlapped throughout the program. This unstructured approach to coding is usually attributed to lack of experience on the part of the programmer. Spaghetti programing makes a program complex and analyzing the codes difficult, and so must be avoided as much as possible.

Question 84.
Differentiate Source Codes.from Object Codes
Answer:
Source codes are codes that were written by the programmer. It is made up of the commands and other English-like keywords that are supposed to instruct the computer what to do. However, computers would not be able to understand source codes. Therefore, source codes are compiled using a compiler. The resulting outputs are object codes, which are in a format that can be understood by the computer processor. In C programming, source codes are saved with the file extension .C, while object codes are saved with the file extension .OBJ

Question 85.
In C programming, how do you insert quote characters (‘ and “) into the output screen?
Answer:
This is a common problem for beginners because quotes are normally part of a printf statement. To insert the quote character as part of the output, use the format specifiers V (for single quote), and \” (for double quote).
Question 86.
What is the use of a ‘\0’ character?
Answer:
It is referred, to as a terminating null character, and is used primarily to show the end of a string value.
Question 87.
What is the difference between the = symbol and = symbol?
Answer:
The = symbol is often used in mathematical operations. It is used to assign a value to a given variable. On the other hand, the == symbol, also known as “equal to” or “equivalent to”, is a relational operator that is used to compare two values.
Question 88.
What is the modulus operator?
Answer:
The modulus operator outputs the remainder of a division. It makes use of the percentage (%) symbol. For example: 10 % 3 = 1, meaning when you divide 10 by 3, the remainder is 1.
Question 89.
What is a nested loop?
Answer:
A nested loop is a loop that runs within another loop. Put it in another sense, you have an inner loop that is inside an outer loop. In this scenario, the inner loop is performed a number of times as specified by the outer loop. For each turn on the outer loop, the inner loop is first performed.
Question 90.
What is gets( ) function?
Answer:
The gets( ) function allows a full line data entry from the user. When the user presses the enter key to end the input, the entire line of characters is stored to a string variable. Note that the enter key is not included in the variable, but instead a null terminator \0 is placed after the last character.
Question 91.
The % symbol has a special use in a printf statement. How would you place this character as part of the output on the screen?
Answer:
You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.
Question 92.
Which of the following operators is incorrect and why? (>=, <=, o, =)
Answer:
<> is incorrect. While this operator is correctly interpreted as “not equal to” in writing conditional statements, it is not the proper operator to be used in C programming. Instead, the operator != must be used to indicate “not equal to” condition.
Question 93.
Compare and contrast compilers from interpreters.
Answer:
Compilers and interpreters often deal with how program codes are executed. Interpreters execute program codes one line at a time, while compilers take the program as a whole and convert it into object code, before executing it. The key difference here is that in the case of interpreters, a program may encounter syntax errors in the middle of execution, and will stop from there. On the other hand, compilers check the syntax of the entire program and will only proceed to execution when no syntax errors are found.
Question 94.
What are header files and what are its uses in C programming?
Answer:
Header files are also known as library files. They contain two essential things: the definitions and prototypes of functions being used in a program. Simply put, commands that you use in C programming are actually functions that are defined from within each header files. Each header file contains a set of functions. For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.
Question 95.
What is the use of a semicolon (;) at the end of every program statement?
Answer:
It has to do with the parsing process and compilation of the code. A semicolon acts as a delimiter, so that the compiler knows where each statement ends, and can proceed to divide the statement into smaller elements for syntax checking.
Question 96.
Finding a number which is a power of 2 in a single step
Answer:
int x=64;
if(x&&(x&(x-l))) printf(“ x is not the power of 2”); 
else printf(“x is power of 2”);
Question 97.
What is syntax error?
Answer:
Syntax errors are associated with mistakes in the use of a programming language. It maybe a command that was misspelled or a command that must was entered in lowercase mode but was instead entered with an upper case character. A misplaced symbol or lack of symbol, somewhere within a line of code can also lead to syntax error.
Question 98.
What is “Bus error”?
Answer:
A bus error indicates an attempt to access memory in an illegal way,perhaps due to an unaligned pointer. A ‘bus error’ is certain undefined behavior result type. The cause for such error on a system could not be specified by the C language. The memory accessibility which CPU could not address physically, ‘bus error’ occurs. Also, any fault detected by a device by the computer system can also be a ‘bus error. These errors caused by programs that generate undefined behavior which C language no longer specifies what can happen.
Question 99.
What are variables and it what way is it different from constants? c,
Answer:
Variables and constants may at first look similar in a sense that both are
identifiers made up of one character or more characters (letters, numbers and a few allowable symbols). Both will also hold a particular value. Values held by a variable can be altered throughout the program, and can be used in most operations and computations. Constants are given values at one time only, placed at the beginning of a program. This value is not altered in the program. For example, you can assigned a constant named PI and give it a value 3.1415. You can then use it as PI in the program, instead of having to write 3.1415 each time you need it.
Question 100.
How do you access the values within an array?
Answer:
Arrays contain a number of elements, depending on the size you gave it during variable declaration. Each element is assigned a number from 0 to number of elements-1. To assign or retrieve the value of a particular element, refer to the element number. For example: if you have a declaration that says “int scores[5];”, then you have 5 accessible elements, namely: scores[0], scores[l], scores[2], scores[3] and scores[4].
Question 101.
Can I use “int” data type to store the value 32768? Why?
Answer:
No. “int” data type is capable of storing values from -32768 to 32767. To store 32768, you can use “long int” instead. You can also use “unsigned int”, assuming you don’t intend to store negative values.
Question 102.
Can two or more operators such as \n and \t be combined in a single line of program code?
Answer:
Yes, it’s perfectly valid to combine operators, especially if the need arises. For example: you can have a code like ” printf (“Hello\n\n\’WorldY”) ” to output the text “Hello” on the first line and “World” enclosed in single quotes to appear on the next two lines.
Question 103.
Why is it that not all header files are declared in every C program?
Answer:
The choice of declaring a header file at the top of each C program would depend on what commands/functions you will be using in that program. Since each header file contains different function definitions and prototype, you would be using only those header files that would contain the functions you will need. Declaring all header files in every program would only increase the overall file size and load of the program, and is not considered a good programming style.
Question 104.
When is the “void” keyword used in a function?
Answer:

When declaring functions, you will decide whether that function would be returning a value or not. If that function will not return a value, such as when the purpose of a function is to display some outputs on the screen, then “void” is to be placed at the leftmost part of the function header. When a return value is expected after the function execution, the data type of the return value is placed instead of “void”.

Question 105.
What are compound statements?
Answer:
Compound statements are made up of two or more program statements that are executed together. This usually occurs while handling conditions wherein a series of statements are executed when a TRUE or FALSE is evaluated. Compound statements can also be executed within a loop. Curly brackets { } are placed before and after compound statements.

Question 106.
What is the significance of an algorithm to C programming?
Answer:
Before a program can be written, an algorithm has to be created first. An algorithm provides a step by step procedure on how a solution can be derived. It also acts as a blueprint on how a program will start and end, including what process and computations are involved.

Question 107.
What is the advantage of an array over individual variables?
Answer:
When storing multiple related data, it is a good idea to use arrays. This is because arrays are named using only 1 word followed by an element number. For example: to store the 10 test results of 1 student, one can use 10 different variable names (grade 1, grade2, grade3… grade 10). With arrays, only 1 name is used, the rest are accessible through the index name (grade[0], grade[1], grade[2]… grade[9]).

Question 108.
Can a variable be both const and volatile?
Answer:
Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. If a variable is both const and volatile, the two modifiers can appear in either order.

Question 109.
What is wrong in this statement? scanf(“%d”,whatnumber);
Answer:
An ampersand & symbol must be placed before the variable name whatnumber. Placing & means whatever integer value is entered by the user is stored at the “address” of the variable name. This is a common mistake for programmers, often leading to logical errors.

Question 110.
How do you generate random numbers in C?
Answer:
Random numbers are generated in C using the rand( ) command. For example: anyNum = randO will generate any integer number beginning from 0, assuming that anyNum is a variable of type integer.

Question 111.
What could possibly be the problem if a valid function name such as to lower( ) is being reported by the C compiler as undefined?
Answer:
The most probable reason behind this error is that the header file for that function was not indicated at the top of the program. Header files contain the definition and prototype for functions and commands used in a C program. In the case of “tolower( )”, the
code “#include <ctype.h>” must be present at the beginning of the program.

Question 112.
What are comments and how do you insert it in a C program?
Answer:
Comments are a great way to put some remarks or description in a program. It can serves as a reminder on what the program is all about, or a description on why a certain code or function was placed there in the first place. Comments begin with /* and ended by */ characters. Comments can be a single line, or can even span several fines. It can be placed anywhere in the program.

Question 113.
What is debugging?
Answer:
Debugging is the process of identifying errors within a program. During program compilation, errors that are found will stop the program from executing completely. At this state, the programmer would look into the possible portions where the error occurred. Debugging ensures the removal of errors, and plays an important role in ensuring that the expected program output is met.

Question 114.
What does the && operator do in a program code?
Answer:
The && is also referred to as AND operator. When using this operator, all conditions specified must be TRUE before the next action can be performed. If you have 10 conditions and all but 1 fails to evaluate as TRUE, the entire condition statement is already evaluated as FALSE.

Question 115.
What does the format %10.2 mean when included in a printf statement?
Answer:
This format is used for two things: to set the number of spaces allotted for the output number and to set the number of decimal places. The number before the decimal point is for the allotted space; in this case it would allot 10 spaces for the output number. If the number of space occupied by the output number is less than 10, addition space characters will be inserted before the actual output number. The number after the decimal point sets the number of decimal places, in this case, its 2 decimal spaces.

Question 116.
What are logical errors and how does it differ from syntax errors?
Answer:
Program that contains logical errors tend to pass the compilation process, but the resulting output may not be the expected one. This happens when a wrong formula was inserted into the code, or a wrong sequence of commands was performed. Syntax errors, on the other hand, deal with incorrect commands that are misspelled or not recognized by the compiler.

Question 117.
What are the different types of control structures in programming?
Answer:
There are 3 main control structures in programming: Sequence, Selection and Repetition. Sequential control follows a top to bottom flow in executing a program, such that step 1 is first perform, followed by step 2, all the way until the last step is performed. Selection deals with conditional statements, which mean codes are executed depending on the evaluation of conditions as being TRUE or FALSE. This also means that not all codes may be executed, and there are alternative flows within. Repetitions are also known as loop structures, and will repeat one or two program statements set by a counter.

Question 118.
What is || operator and how does it function in a program?
Answer:
The | | is also known as the OR operator in C programming. When using | | to evaluate logical conditions, any condition that evaluates to TRUE will render the entire condition statement as TRUE.

Question 119.
Not all reserved words are written in lowercase. TRUE or FALSE?
Answer:
FALSE. All reserved words must be written in lowercase; otherwise the C compiler would interpret this as unidentified and invalid.

Question 120.
What is the difference between the expression “++a” and “a++”?
Answer:
In the first expression, the increment would happen first on variable a, and the resulting value will be the one to be used. This is also known as a prefix increment. In the second expression, the current value of variable a would the one to be used in an operation, before the value of a itself is incremented. This is also known as postfix increment.

Question 121.
What would happen to X in this expression: X += 15; (assuming the value of X is 5)
Answer:
X +=15 is a short method of writing X = X + 15, so if the initial value of X is 5, then 5 + 15 = 20.

Question 122.
In C language, the variables NAME, name, and Name are all the same. TRUE or FALSE?
Answer:
FALSE. C language is a case sensitive language. Therefore, NAME, name and Name are three uniquely different variables.

Question 123.
What is an endless loop?
Answer:
An endless loop can mean two things. One is that it was designed to loop continuously until the condition within the loop is met, after which a break function would cause the program to step out of the loop. Another idea of an endless loop is when an incorrect loop condition was written, causing the loop to run erroneously forever. Endless loops are oftentimes referred to as infinite loops.

Question 124.
Can the “if’ function be used in comparing strings?
Answer:
No. “if’ command can only be used to compare numerical values and single character values. For comparing string values, there is another function called strcmp that deals specifically with strings.

Question 125.
What is a program flowchart and how does it help in writing a program?
Answer:
A flowchart provides a visual representation of the step by step procedure towards solving a given problem. Flowcharts are made of symbols, with each symbol in the form of different shapes. Each shape may represent a particular entity within the entire program structure, such as a process, a condition, or even an input/output phase.

Question 126.
What is wrong with this program statement? void = 10;
Answer:
The word void is a reserved word in C language. You cannot use reserved words as a user-defined variable.

Question 127.
Is this program statement valid? INT = 10.50;
Answer:
Assuming that INT is a variable of type float, this statement is valid. One may think that INT is a reserved word and must not be used for other purposes. However, recall that reserved words are express in lowercase, so the C compiler will not interpret this as a reserved word.

Question 128.
What is a newline escape sequence?
Answer:
A newline escape sequence is represented by the \n character. This is used to insert a new line when displaying data in the output screen. More spaces can be added by inserting more \n characters. For example, \n\n would insert two spaces. A newline escape sequence can be placed before the actual output expression or after.

Question 129.
Is it possible to initialize a variable at the time it was declared?
Answer:
Yes, you don’t have to write a separate assignment statement after the variable declaration, unless you plan to change it later on. For example: char planet[15] = “Earth”; does two things: it declares a string variable named planet, then initializes it with the value “Earth”.

Question 130.
What is output redirection?
Answer:
It is the process of transferring data to an alternative output source other than the display screen. Output redirection allows a program to have its output saved to a file. For example, if you have a program named COMPUTE, typing this on the command fine as COMPUTE >DATA can accept input from the user, perform certain computations, then have the output redirected to a file named DATA, instead of showing it on the screen.

Question 131.
What are run-time errors?
Answer:
These are errors that occur while the program is being executed. One common instance wherein run-time errors can happen is when you are trying to divide a number by zero. When run-time errors occur, program execution will pause, showing which program line caused the error.

Question 132.
What is the difference between functions abs( ) and fabs( )?
Answer:
These 2 functions basically perform the same action, which is to get the absolute value of the given value. AbsO is used for integer values, while fabs( ) is used for floating type numbers. Also, the prototype for abs( ) is under <stdlib.h>, while fabs( ) is under <math.h>.

Question 133.
What are control structures?
Answer:
Control structures take charge at which instructions are to be performed in a program. This means that program flow may not necessarily move from one statement to the next one, but rather some alternative portions may need to be pass into or bypassed from, depending on the outcome of the conditional statements.

Question 134.
When is a “switch” statement preferable over an “if’ statement?
Answer:
The switch statement is best used when dealing with selections based on a single variable or expression. However, switch statements can only evaluate integer and character data types.

Question 135.
What are global variables and how do you declare them?
Answer:
Global variables are variables that can be accessed and manipulated anywhere in the program. To make a variable global, place the variable declaration on the upper portion of the program, just after the preprocessor directives section.

Question 136.
What are enumerated types?
Answer:
Enumerated types allow the programmer to use more meaningful words as values to a variable. Each item in the enumerated type variable is actually associated with a numeric code. For example, one can create an enumerated type variable named DAYS whose values are Monday, Tuesday… Sunday.

Question 137.
What does the function toupper( ) do?
Answer:
It is used to convert any letter to its upper case mode. Toupper( ) function prototype is declared in <ctype.h>. Note that this function will only convert a single character, and not an entire string.

Question 138.
Is it possible to have a function as a parameter in another function?
Answer:
Yes, that is allowed in C programming. You just need to include the entire function prototype into the parameter field of the other function where it is to be used.

Question 139.
What are multidimensional arrays?
Answer:
Multidimensional arrays are capable of storing data in a two or more dimensional structure. For example, you can use a 2 dimensional array to store the current position of pieces in a chess game, or position of players in a tic-tac-toe program.

Question 140.
Which function in C can be used to append a string to another string?
Answer:
The strcat function. It takes two parameters, the source string and the string value to be appended to the source string.

Question 141.
What is the difference between functions getch( ) and getche( )?
Answer:
Both functions will accept a character input value from the user. When using getch( ), the key that was pressed will not appear on the screen, and is automatically captured and assigned to a variable. When using getche( ), the key that was pressed by the user will appear on the screen, while at the same time being assigned to a variable.

Question 142.
Do these two program statements perform the same output? 1) scanf(“%c”, &letter); 2) letter=getchar()
Answer:
Yes, they both do the exact same thing, which is to accept the next key pressed by the user and assign it to variable named letter.

Question 143.
What are structure types in C?
Answer:
Structure types are primarily used to store records. A record is made up of related fields. This makes it easier to organize a group of related data.

Question 144.
Is it possible to create your own header files?
Answer:
Yes, it is possible to create a customized header file. Just include in it the function prototypes that you want to use in your program, and use the #include directive followed by the name of your header file.

Question 145.
What is dynamic data structure?
Answer:
Dynamic data structure provides a means for storing data more efficiently into memory. Using dynamic memory allocation, your program will access memory spaces as needed. This is in contrast to static data structure, wherein the programmer has to indicate a fix number of memory space to be used in the program.

Question 146.
What are the different data types in C?
Answer:
The basic data types are int, char, and float. Int is used to declare variables that will be storing integer values. Float is used to store real numbers. Char can store individual character values.

Question 147.
What is the general form of a C program?
Answer:
A-C program begins with the preprocessor directives, in which the programmer would specify which header file and what constants (if any) to be used. This is followed by the main function heading. Within the main function lies the variable declaration and program statement.

Question 148.
What is the advantage of a random access file?
Answer:
If the amount of data stored in a file is fairly large, the use of random access will allow you to search through it quicker. If it had been a sequential access file, you would have to go through one record at a time until you reach the target data. A random-access file lets you jump directly to the target address where data is located.

Question 149.
In a switch statement, what will happen if a break statement is omitted?
Answer:
If a break statement was not placed at the end of a particular case portion? It will move on to the next case portion, possibly causing incorrect output.

Question 150.
Describe how arrays can be passed to a user-defined function
Answer:
One thing to note is that you cannot pass the entire array to a function. Instead, you pass to it a pointer that will point to the array first element in memory. To do this, you indicate the name of the array without the brackets.

Question 151.
What are different storage class specifiers in C?
Answer:
auto, register, static, extern

Question 152.
What is scope of a variable? How are variables scoped in C?
Answer:
Scope of a variable is the part of the program where the variable may directly be accessible. In C, all identifiers are lexically (or statically) scoped.

Question 153.
When should we use pointers in a C program?
Answer:

  1. To get address of a variable
  2. For achieving pass-by reference in C: Pointers allow different functions to share and modify their local variables.
  3. To pass large structures so that complete copy of the structure can be avoided.C
  4. To implement “linked” data structures like linked lists and binary trees.

Question 154.
What is NULL pointer?
Answer:
NULL is used to indicate that the pointer doesn’t point to a valid location. Ideally, we should initialize pointers as NULL if we don’t know their value at the time of declaration. Also, we should make a pointer NULL when memory pointed by it is deallocated in the middle of a program.

Question 155.
What is Dangling pointer?
Answer:
Dangling Pointer is a pointer that doesn’t point to a valid memory location. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. Following are examples.

// EXAMPLE 1

int *ptr = (int *)malloc(sizeof(int));
.......................
......................
free(ptr);
// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10; // or printf(“%d”, *ptr);

// EXAMPLE 2

int *ptr = NULL
{
int x =10;
 ptr = &x;
}
// x goes out of scope and memory allocated to x is free now. 
// So ptr is a dangling pointer now.

Question 156.
What is memory leak? Why it should be avoided
Answer:
Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.

/* Function with memory leak */ 
#include <stdlib.h> 
void f( ){
int *ptr = (int *) malloc(sizeof(int));
 /* Do some work */
return; /* Return without freeing ptr*/
}

Question 157.
What are pointers?
Answer:
Pointers point to specific areas in the memory. Pointers contain the address of a variable, which in turn may contain a value or even an address to another memory.

Question 158.
What is an lvalue?
Answer:
An lvalue is an expression to which a value can be assigned. The lvalue expression is located on the left side of an assignment statement, whereas an rvalue is located on the right side of an assignment statement. Each assignment statement must have an lvalue and an rvalue. The lvalue expression must reference a storable variable in memory. It cannot be a constant.

Question 159.
What is a pointer value and address?
Answer:
A pointer value is a data object that refers to a memory location. Each memory location is numbered in the memory. The number attached to a memory location is called the address of the location.

Question 160.
What is wild pointer?
Answer:
Wild pointers are also known as dangling pointers. Pointers that do not point to a valid object of the appropriate type, or to a distinguished null pointers value in language which support this.

Question 161.
What is the drawback of Pointer?
Answer:
Since the pointers point to a memory location issues of dangling pointers and wild pointers can occur. Dangling pointers are those pointers when the data at which they are pointed may have been modified or deleted. But still the pointer points to that location.
The pointers that are not initialized lead to wild pointers because they will be pointing to some arbitrary memory.
Also memory leaks occur, if a memory is not released.

Question 162.
What is pointer in C?
Answer:
Pointer is a variable that stores/points the address of another variable. Normal variable stores the value of the variable whereas pointer variable stores the address of the variable.
Syntax: data_type *var_name;
Where, * is used to denote that “p” is pointer variable and not a normal variable.

Question 163.
What is null pointer in C?
Answer:
Null pointer is a pointer which is pointing to nothing. Null pointer points to empty location in memory. Value of null pointer is 0. We can make a pointer to point to null as below,
int *p = NULL;
char *p = NULL;

Question 164.
What is NULL in C?
Answer:
NULLisamacrowhichisdefinedinCheaderfiles.ThevalueofNULLmacroisO. It is defined in C header files as below.
#define NULL (void *) 0;
NULL is used for pointers only as it is defined as (void *) 0. It should not be used other than pointers. If NULL is assigned to a pointer, then pointer is pointing to nothing.

Question 165.
What is void pointer in C?
Answer:

  • A void pointer is a generic pointer that can be used to point another variable of any data type.
  • A void pointer can store the address of a variable belonging to any of the data type. So, void pointer is also called a general-purpose pointer.

Note: int pointer can be used to point a variable of int data type and char pointer can be used to point a variable of char data type.

Question 166.
What is dangling pointer in C?
Answer:
When a pointer is pointing to non-existing memory location is called dangling pointer.

Question 167.
What is wild pointer in C?
Answer:
Uninitialized pointers are called as wild pointers in C which points to arbitrary (random) memory location. This wild pointer may lead a program to behave wrongly or to crash.

Question 168.
What is file pointer in C?
Answer:

  • File pointer is a pointer which is used to handle and keep track on the files being accessed. A new data type called “FILE” is used to declare file pointer. This data type is defined in stdio.h file. File pointer is declared as FILE *fp. Where, ‘fp’ is a file pointer.
  • fopen( ) function is used to open a file that returns a FILE pointer. Once file is opened, file pointer can be used to perform I/O operations on the file. fclose( ) function is used to close the file.

Question 169.
When can void pointer and null pointer be used in C?
Answer:
Void pointer is a generic pointer that can be used to point another variable of any data type. Null pointer is a pointer which is pointing to nothing.

Question 170.
What is const pointer in C?
Answer:
Const pointer is a pointer that can’t change the address of the variable that is pointing to. Once const pointer is made to point one variable, we can’t change this pointer to point to any other variable. This pointer is called const pointer.

Question 171.
Is pointer arithmetic a valid one? Which arithmetic operation is not valid in pointer? Why?
Answer:
Pointer arithmetic is not valid one. Pointer addition, multiplication and division are not allowed as these are not making any sense in pointer arithmetic. But, two pointers can be subtracted to know how many elements are available between these two pointers.

Question 172.
Is void pointer arithmetic a valid one? Why?
Answer:
Arithmetic operation on void pointer is not valid one. Void pointer is a generic pointer. It is not referring int, char or any other data type specifically. So, we need to cast void pointer to specific type before applying arithmetic operations. Note:

  • Pointer arithmetic itself is not valid one. Pointer addition, multiplication and division are not allowed as these are not making any sense in pointer arithmetic.
  • But, two pointers can be subtracted to know how many elements are available between these two pointers.

Question 173.
What is the difference between null and zero?
Answer:
NULLis a macro that is defined in C header files. The value ofNULLmacroisO. It is defined in C header files as below, define NULL (void *) 0;

  • NULL is used for pointers only as it is defined as (void *) 0. It should not be used other than pointers. If NULL is assigned to a pointer, then the pointer is pointing to nothing.
  • 0 (zero) is a value.

Question 174.
What is the difference between null pointer and uninitialized pointer in C?
Answer:
Null pointer is a pointer which is pointing to nothing. Null pointer points to empty location in memory. Value of null pointer is 0. We can make a pointer to point to null as below,

int *p = NULL;
char *p = NULL;

Uninitialized pointers are called as wild pointers in C which points to arbitrary (random) memory location. This wild pointer may lead a program to behave wrongly or to crash.

Question 175.
Can array size be declared at run time?
Answer:
Array size can’t be declared at run time. Size of array must be known during compilation time. So, array size should be declared before compilation.

  • Correct example: char array [10];
  • Wrong example: char array[i];
  • Always, the Array subscript should be positive and it should not be either negative or any variable name.
  • If we really don’t know the size of an array, we can use dynamic memory allocation concepts in C which uses malloc( ), calloc( ) functions to allocate memory during execution time.

Question 176.
What are local static variables? What is their use?
Answer:
A local static variable is a variable whose life doesn’t end with a function call where it is declared. It extends for the lifetime of a complete program. All calls to the function share the same copy of local static variables. Static variables can be used to count the number of times a function is called. Also, static variables get the default value is 0. For example, the following program prints “0 1″

#include <stdio.h>
void fun( ){
// static variables get the default value as 0.


static int x;
printf(“%d x);
x = x + 1;
}
int main( ){
fun( );
fun( );
return 0;
}

// Output: 0 1

Question 177.
What are static functions? What is their use?
Answer:
In C, functions are global by default. The “static” keyword before a function name makes it static. Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.

Question 178.
Reallocating memory
Answer:
When reallocating memory if any other pointers point into same piece of memory do you have to readjust these pointers or do they get readjusted automatically?

Question 179.
What is the difference between Call by Value and Call by Reference?
Answer:
When using Call by Value, you are sending the value of a variable as parameter to a function, whereas Call by Reference sends the address of the variable. Also, under Call by Value, the value in the parameter is not affected by whatever operation that takes place, while in the case of Call by Reference, values can be affected by the process within the function.

Question 180.
What are the actual arguments?
Answer:
When you create and use functions that need to perform an action on some given values, you need to pass these given values to that function. The values that are being passed into the called function are referred to as actual arguments.

Question 181.
What are formal parameters?
Answer:
In using functions in a C program, formal parameters contain the values that were passed by the calling function. The values are substituted in these formal parameters and used in whatever operations as indicated within the main body of the called function. .

Question 182.
Can you pass an entire structure to functions?
Answer:
Yes, it is possible to pass an entire structure to a function in a call by method style. However, some programmers prefer declaring the structure globally, and then pass a variable of that structure type to a function. This method helps maintain consistency and uniformity in terms of argument type.

Question 183.
Is there a built-in function in C that can be used for sorting data?
Answer:
Yes, use the qsort( ) function. It is also possible to create user-defined functions for sorting, such as those based on the balloon sort and bubble sort algorithm.

Question 184.
How do you convert strings to numbers in C?
Answer:
You can write you own functions to do string to number conversions, or instead use C’s built-in functions. You can use atof to convert to a floating-point value, atoi to convert to an integer value, and atol to convert to a long integer value.

Question 185.
How many arguments can be passed to a function in C?
Answer:

  • Any number of arguments can be passed to a function. There is no limit on this. Function arguments are stored in stack memory rather than heap memory. Stack memory allocation is depending on the operating system.
  • So, any number of arguments can be passed to a function as much as stack has enough memory. Program may crash when stack overflows.

Question 186.
What is a static function in C?
Answer:
All functions are global by default in a C program/file. But, static keyword makes a function as a local function which can be accessed only by the program/ file where it is declared and defined. Other programs/files can’t access these static functions.

Question 187.
What is the difference between memcpy( ) & strcpy( ) functions in C?
Answer:
• memcpy( ) function is used to copy a specified number of bytes from one memory to another. Whereas, strcpy( ) function is used to copy the contents of one string into another string.
• memcpy( ) function acts on memory rather than value. Whereas, strcpy( ) function acts on value rather than memory.

Question 188.
What is the difference between memcpy( ) & memmove( ) functions in C?
Answer:

  • memcpy( ) function is used to copy a specified number of bytes from one memory to another.
  • memmove( ) function is used to copy a specified number of bytes from one memory to another or to overlap on the same memory.
  • Difference between memmove( ) and memcpy( ) is, overlap can happen on memmove( ). Whereas, memory overlap won’t happen in memcpy( ) and it should be done in non-destructive way.

Question 189.
Is there any inbuilt library function in C to remove leading and trailing spaces from a string? How will you remove them in C?
Answer:

• There is no inbuilt function to remove leading and trailing spaces from a string in C. We need to write our own function to remove them.
• We need to check the first non-space character in a given string. Then, we can copy that string from where the nonspace character is found. Then, we can check whether any spaces are available in copied string from the end of the string. If space is found, we can copy ‘\0’ in that space until any character is found. Because ‘indicates the end of the string. Now, we have removed leading and trailing spaces in a given string.

Question 190.
What is the difference between strcpy( ) & strncpy( ) functions in C?
Answer:

  • strcpy( ) function copies the whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string.
  • If the destination string length is less than the source string, the entire/specified source string value won’t be copied into the destination string in both cases.

Question 191.
If you want to execute C program even after main function is terminated, which function can be used?
Answer:

  • “atexit( )” function can be used if we want to execute any function after program is terminated normally.
  • Syntax: int atexit (void ( func)(void));
  • The function “func” will be called automatically without any arguments once the program is terminated normally.

Question 192.
What is exit() function in C?
Answer:

  • exit( ) function terminates the program/process normally and returns the status code to the parent program/process.
  • Syntax: void exit(int status)

Question 195.
What is the use of “#define” in C?
Answer:
#define is a pre-processor directive that is used to define constant value. This constant can be any of the basic data types.

Question 193.
Is it possible to call exit( ) function more than once in a C program?
Answer:
Yes. We can call atexit( ) function more than once. But, they will be executed in reverse order as a stack.

Example program:

#include <stdio.h>
#inc1ude <std1ib.h>
void Exitl (void){
printf (“Exitl function is called\n”);
}
void Exit2 (void){
printf (“Exit2 function is called \n”);
}
int main (void){
atexit (Exitl);
atexit (Exit2);
printf (“This is the end of this program.\n”);
return 0;
}

Question 194.
What is the difference between exit( ) and return( ) in C?
Answer:

  • exit( ) is a system call that terminates the current process. exit( ) is not an instruction of C language.
  • Whereas return( ) is a C language instruction/statement and it returns from the current function (i.e. provides exit status to calling function and provides control back to the calling function).

Question 195.
What is the use of “#define” in C?
Answer:
#define is a preprocessor directive that is used to define constant value. This constant can be any of the basic data types.

Question 196.
What is the syntax for comments in C?
Answer:
Below is the syntax for comments in C. The characters or words or anything which are given between “/*” and won’t be considered by C compiler for compilation process. These will be ignored by the C compiler during compilation.
Syntax: /* your comments here */

Question 197.
What is a stack?
Answer:
A stack is one form of a data structure. Data is stored in stacks using the FILO (First In Last Out) approach. At any particular instance, only the top of the stack is accessible, which means that in order to retrieve data that is stored inside the stack, those on the upper part should be extracted first. Storing data in a stack is also referred to as a PUSH, while data retrieval is referred to as a POP.

Question 198.
What is a linked list?
Answer:
A linked list is composed of nodes that are connected with one another. In C programming, linked lists are created using pointers. Using linked lists is one efficient way of utilizing memory for storage.

Question 199.
What is FIFO?
Answer:
In C programming, there is a data structure known as queue. In this structure, data is stored and accessed using FIFO format, or First-In-First-Out. A queue represents a fine wherein the first data that was stored will be the first one that is accessible as well.

Question 200.
What are binary trees?
Answer:
Binary trees are actually an extension of the concept of linked lists. A binary tree has two pointers, a left one and a right one. Each side can further branch to form additional nodes, which each node having two pointers as well.

Question 201.
What are the advantages and disadvantages of a heap?
Answer:
Storing data on the heap is slower than it would take when using the stack. However, the main advantage of using the heap is its flexibility. That’s because the memory in this structure can be allocated and remove in any particular order. Slowness in the heap can be compensated if an algorithm was well designed and implemented.

Question 202.
What are static memory allocation and dynamic memory allocation?
Answer:
• Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of the operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variable has static memory, this way of assigning pointer value to a pointer variable is known as static memory allocation. Memory is assigned during compilation time.

• Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assigned to pointer variables, such assignments are known as dynamic memory allocation. Memory is assigned during run time.

Question 203.
What is the difference between “calloc” and “malloc”?
Answer:
calloc and malloc are used for dynamic memory allocation. Calloc initializes the memory locations to zero by default but malloc memory contains garbage values.

Question 204.
Where is the function declared as static stored in memory?
Answer:
The usage of static with a function or variable restricts their scope. Is this behavior memory related?
Yes static keyword would not affect where the function gets stored, even if it is static a function will always be stored in stack! But it hides the function from being used in other files other than in which it is declared.

Question 205.
What is pointer linking with the operating system?
Answer:
When we declare a null pointer it addresses the 0 address which is the address of the operating system so we cannot use that address this is what the pointer is linked to OS.

Question 206.
Difference between program memory, data memory, stack memory, and heap memory?
Answer:
When the program is compiled and linked different parts of the program is organized in separate segments. That is our code will be in one segment code means the instructions to be executed this is called as code segment or program memory this is usually read-only. Then there are data which on which the code operates, these data get stored in a segment called data segment. Stack memory is a part of programs memory which will be used as stack in case of function calls to store the IP and parameters variables of the current function.

The three types of memory specified above are owned by the corresponding process or program the linker will give info about where to store which data to the loader, based on these infos loader will load the corresponding image i.e. executable in the memory. Heap memory is the memory that is not owned by the process. OS has set of pages of memory which can be allocated to the process when a process requests for extra memory, these requests are done by the malloc and calloc function calls.

This memory is allocated when the program is running and according to the current condition of the process i.e. allocated dynamically that’s why this is called as dynamic allocation.
I have used words program and process invariably. Because a program needs physical primary memory when it gets executed and a program under execution is a process, Hope this explanation is clear.

Question 207.
C is a structural or high-level or middle-level language which one is the correct answer
Answer:
C is a middle-level language.
Because this language contains both the features of both high-level language and low-level languages. Also can be called a structured programming language.

Question 208.
What do the characters “r” and “w” mean when writing programs that will make use of files?
Answer:
“r” means “read” and will open a file as input wherein data is to be retrieved, “w” means “write”, and will open a file for output. Previous data that was stored on that file will be erased.

Question 209.
What is the difference between text files and binary files?
Answer:
Text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain Is and Os that only computers can interpret.

Question 210.
How do you search data in a data file using a random access method?
Answer:
Use the fseek( ) function to perform random access input/output on a file. After the file was opened by the fopen( ) function, the fseek would require three parameters to work: a file pointer to the file, the number of bytes to search, and the point of origin in the file.

Question 211.
Difference between “printf” and “sprintf”.
Answer:
printf will write to the console, sprintf will write to the buffer

Question 212.
Difference between printf and cprintf
Answer:
printf outputs to the standard output stream (stdout) fprintf goes to a file handle (FILE*) sprintf goes to a buffer you allocated, (char*)

Question 213.
Garbage Value
Answer:
In C if a variable is not assigned a value then why does it take garbage value? •

Question 214.
What are preprocessor directives?
Answer:
Preprocessor directives are placed at the beginning of every C program. This is where library files are specified, which would depend on what functions are to be used in the program. Another use of preprocessor directives is the declaration of constants. Preprocessor directives begin with the # symbol.

Question 215.
What is Macro? Why do we use a macro?
Answer:

  • Macro is a name that is given to a value or to a piece of code/block in a program. Instead of using the value, we can use a macro that will replace the value in a program.
  • The reason for using a macro is, consider the below example.
  • You are using a person’s age as 50 in many places in your program. If you use direct value in all the places in your program, it is very difficult to change the age value in the future if you want to change it to 60. If you use a macro in your program, it is very simple to replace the value and we can change in only one place which will change the value in all places in your program.
    Syntax: #define <MACR0 _NAME> VALUE
    Example: Original declaration — #define AGE 50
    Modified declaration – #define AGE 60

Question 216.
What is the “##” operator in C?
Answer:
## is a pre-processor macro in C. It is used to concatenate 2 tokens into one token.
Example program:

#include<stdio.h>
#define concatination(a,b) a ## b 
int main ( ){
int ab = 1000;
printf(“The concatenated value is:%d \n”,concatination(a,b)); 
return 0;
}

Output: The concatenated value is: 1000

Question 217.
How will you override an existing macro in C?
Answer:
To override an existing macro, we need to undefine the existing macro using “#undef’. Then, we need to define the same macro again with the new value.

Question 218.
What is pragma in C? Or how will you execute functions before and after main function in C program?
Answer:
#pragma is a. pre-processor macro in C. It is used to call a function before and after main function in a C program.
Example program:

#include <stdio.h>
void functionlC );
void function2( );
#pragma startup function1
#pragma exit function2
int main( ){
printf C “\n Now we are in main function” ) ;
return 0;
}
void functionl( ){
printf(“\nFunctionl is called before main function call”);

}
void function2( ){
printf C “\nFunction2 is called just before end of “ \
«main function” )
}

Output:
Function1 is called before the main function call
Now we are in the main function
Function2 is called just before the end of the main function

Question 219.
How to check whether the macro is defined or not in a C program?
Answer:
“#ifdef ’ pre-processor directive checks whether a particular macro is defined or not in a C program.

Question 220.
What is the difference between typedef & Macros?
Answer:
Typedef is used to create a new name to an already existing data type. Redefine the name that creates conflict with the previous declaration,
eg: typedef unsigned int UINT32
Macros [#define] is a direct substitution of the text before completing the whole code. In the given example, it’s just a textual substitution. Where there is a possibility of redefining the macro

eg: #define pointer char *
under chpointer
#define chPointer int *

Question 221.
What are pre-processor directives?
Answer:

  • Pre-processor directives are placed at the beginning of a C program. They begin with the # symbol.
  • This is the place, where library files are specified depending on the functions to be used in the program.
  • Pre-processor directives are also used for the declaration of constants.

Question 222.
What is the difference between structure & union?
Answer:
Differences are:

  1. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total i memory required by the members.
  2. In a union, one block is used by all the members of the union but in the case of structure, each member has their own memory space
  3. union is best in the environment where memory is less as it shares the memory allocated. But structure cannot implement in shared memory.
  4. As memory is shared, ambiguity is more in the union, but less in structure.
  5. The self-referential union cannot be implemented in any data structure, but the self referential structure can be implemented.

Question 223.
What is wrong with this statement? myName = “Robin”;
Answer:
You cannot use the = sign to assign values to a string variable. Instead, use the strcpy function. The correct statement would be: strcpy(myName, “Robin”);

Question 224.
How do you determine the length of a string value that was stored in a variable?
Answer:
To get the length of a string value, use the function strlen( ) For example, if you have a variable named FullName, you can get the length of the stored string value by using this statement: I = strlen(FullName); the variable I will now have the
i character length of the string value.

Question 225.
How do you declare a variable that will hold string values?
Answer:
The char keyword can only hold 1 character value at a time. By creating an array of characters, you can store string values in it. Example: “char MyName[50]; ” declares a string variable named MyName that can hold a maximum of 50 characters.

Question 226.
Can array subscripts have a negative value in C?
Answer:
No. Array subscripts should not have a negative value. Always, it should be positive.

Question 227.
What is the difference between array and string in C?
Answer:

  • The array can hold any of the data types. But, the string can hold only char data type.
  • Array size must be a constant value. So, array size can’t be changed once declared. But, string size can be modified using a char pointer.
  • The array is not ended with a null character by default. But, the string is ended with a null (‘\0’) character by default.

Question 228.
What is meant by core dump in C?
Answer:

  • Core dump or core is a file, generated when a program is crashed or terminated abnormally because of segmentation fault or some other reason. Information of the memory used by a process is dumped in a file called core. This file is used for debugging purposes. Core dump has file names like “core.<process_id>”
  • The core dump file is created in the current working directory when a process terminates abnormally. A core dump is a typical error that occurs because of illegal memory access.
  • A core dump is also called a memory dump, storage dump, or dump.

Question 229.
What is the purpose of the “register” keyword?
Answer:
It is used to make the computation faster.
The register keyword tells the compiler to store the variable onto the CPU register if space on the register is available. However, this is a very old technique. Today’s processors are smart enough to assign the registers themselves and hence using the register keyword can actually slow down the operations if the usage is incorrect.

Question 230.
What is the purpose of the “register” keyword?
Answer:
The keyword ‘register’ instructs the compiler to persist the variable that is being declared, in a CPU register.
Ex: register int number;
The persistence of register variables in the CPU register is to optimize the access. Even the optimization is turned off; the register variables are forced to store in the CPU register.

Question 231.
Explain the use of the “auto” keyword.
Answer:
When a certain variable is declared with the keyword ‘auto’ and initialized to a certain value, then within the scope of the variable, it is reinitialized upon being called repeatedly.

Question 232.
Explain the use of the “auto” keyword.
Answer:
The keyword ‘auto’ is used extremely rarely. A variable is set by default to auto. The declarations:
auto int number; and int number;
has the same meaning. The variables of type static, extern and register need to be explicitly declared, as their need is very specific. The variables other than the above three are implied to be auto variables. For better readability, auto keywords can be used.

C++ Interview Questions in Java

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

C++ Interview Questions in Java

Question 1.
What is C++?
Answer:
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language while simplifying memory management and adding several features – including a new data type known as a class (you will learn more about these later) – to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.

Question 2.
What Is Object-Oriented Programming?
Answer:
Object-Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects talking to each other. An object is a collection of data and methods that operate on its data.

Question 3.
Why OOP?
Answer:
The main advantage of OOP is better manageable code that covers the following.

  1. The overall understanding of the software is increased as the distance between the language spoken by developers and that spoken by users.
  2. Object orientation eases maintenance by the use of encapsulation. One can easily change the underlying representation by keeping the methods the same. OOP paradigm is mainly useful for relatively big software. See this for a complete example that shows the advantages of OOP over procedural programming.

Question 4.
What are the main features of OOP?
Answer:

  • Encapsulation
  • Polymorphism
  • Inheritance

Question 5.
What is encapsulation?
Answer:
Encapsulation is referred to one of the following two notions.

  1. Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in C++.
  2. Bundling of data and methods together: Data and methods that operate on that data are bundled together.

Question 6.
What is Polymorphism? How is it supported by C++?
Answer:
Polymorphism means that some code or operations or objects behave differently in different contexts. In C++, the following features support polymorphism.
• Compile Time Polymorphism: Compile time polymorphism means the compiler knows which function should be called when a polymorphic call is made. C++ supports compiler time polymorphism by supporting features like templates, function overloading, and default arguments.

• Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea is virtual functions are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime.

Question 7.
What is Abstraction?
Answer:
The first thing with which one is confronted when writing programs is the problem. Typically we are confronted with “real-life” problems and we want to make life easier by providing a program for the problem. However, real-life problems are nebulous and the first thing we have to do is to try to understand the problem to separate necessary from unnecessary details: We try to obtain our own abstract view, or model, of the problem. This process of modeling is called abstraction

Question 8.
What is the difference between realloc( ) and free()?
Answer:
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

Question 9.
What is function overloading and operator overloading?
Answer:
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types, and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn’t add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

Question 10.
What is the difference between declaration and definition?
Answer:
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.

E.g.: void stars ( ) //function declaration 
The definition contains the actual implementation.
E.g.: void stars ( ) // declaratory
{
for(int j=10; j > =0; j - - ) //function body 
cout << *; 
cout << end1; }

Question 11.
What are the differences between references and pointers?
Answer:
Bothreferencesandpointerscanbeusedtochangelocalvariablesofonefunction inside another function. Bothofthemcanalsobeusedtosavecopyingofbig objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.
References are less powerful than pointers

  1. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  2. References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
  3. A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java are the main reason Java doesn’t need pointers. References are safer and easier to use:

  1. Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location.
  2. Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. the operator is needed only at the time of declaration. Also, members of an object reference can be accessed with a dot operator, unlike pointers where an arrow operator (->) is needed to access members.

Question 12.
Explain Copy Constructor.
Answer:
It is a constructor which initializes its object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it.

Question 13.
When do you call copy constructors?
Answer:
Copy constructors are called in these situations:

  • when the compiler generates a temporary object
  • when a function returns an object of that class by value
  • when the object of that class is passed by value as an argument to a function
  • when you construct an object based on another object of the same class

Question 14.
Differentiate between late binding and early binding. What are the advantages of early binding?
Answer:

  • Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time.
  • Late binding occurs through virtual functions while early binding takes place when all the information needed to call a function is known at the time of compiling. Early binding increases the efficiency. Some of the examples of early binding are normal function calls, overloaded function calls, and overloaded operators, etc.

Question 15.
What are the advantages of inheritance?
Answer:
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 16.
What do you mean by inline function?
Answer:
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application’s performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Question 17.
What is public, protected, private?
Answer:
Public, protected, and private are three access specifiers in C++. Public data members and member functions are accessible outside the class. Protected data members and member functions are only available to derived classes. Private data members and member functions can’t be accessed outside the class. However, there is an exception that can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.

void swap(int* a, int*b) { 
int t; 
t = *a;
*a = *b;
*b = t;
}

Question 18.
What are virtual constructors/destructors?
Answer:
Answer 1 Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.

There is a simple solution to this problem that declares a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.
Answer 2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Question 19.
Explain storage qualifiers in C++.
Answer:

  1. Const – This variable means that if the memory is initialized once, it should not be altered by a program.
  2. Volatile – This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
  3. Mutable – This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

Question 20.
What is the type of “this” pointer? When does it get created?
Answer:
It is a constant pointer type. It gets created when a non-static member function of a class is called.

Question 21.
How would you differentiate between pre and post-increment operators while overloading?
Answer:
Mentioning the keyword int as the second parameter in the post-increment form of the operator++0 helps distinguish between the two forms.

Question 22.
What are the advantages of inheritance?
Answer:

  • It permits code reusability.
  • Reusability saves time in program development.
  • It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 23.
What is a template?
Answer:
Templates allow the creation of generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until a certain point, they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template <class indetifier> function_declaration; 
template type name indetifier> function_declaration;

The only difference between both prototypes is the use of keyword class or type name, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Question 24.
Define a constructor – What it is and how it might be called (2 methods).
Answer:
Answer 1
Constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized. Ways of calling constructor:

  1. Implicitly: automatically by complier when an object is created.
  2. Calling the constructors explicitly is possible, but it makes the code unverifiable.

Answer 2

class Point2D{ 
int x; int y;
public Point2DO : x(0) , y(0) {} //default (no argument) constructor
};
main( ){
Point2D MyPoint; // implicit Constructor call, in order to allocate 
memory on stack, the default constructor is implicitly called.
Point2D * pPoint = new Point2D(); // Explicit constructor call, 
In order to allocate memory on HEAP we call the default constructor.
we have two pairs: new( ) and delete( ) and another pair : alloc( ) and free( ).

Question 25.
Explain differences between eg. new() and malloc()
Answer:
Answer 1:

  1. “new and delete” are preprocessors while “malloc( ) and ffee( )” are functions, [we dont use brackets will calling new or delete],
  2. no need of allocate the memory while using “new” but in “malloc( )” we have to use “sizeof( )”.
  3. “new” will initlize. the new rnemoiy to 0 but “malloc( )” gives random value in the new alloted memory location [better to use calloc( )]

Answer 2:
new( ) allocates continous space for the object instace mallocO allocates distributed space.
new( ) is castless, meaning that allocates memory for this specific type, mallocO, callocO allocate space for void * that is cated to the specific class type pointer.

Question 26.
What is the difference between class and structure?
Answer:
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

Question 27.
WhatisRTTI?
Answer:
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many Interview Questions – Homegrown versions with a solid, consistent approach.

Question 28.
W/hat is encapsulation?
Answer:
Packaging an object’s variables within its methods is called encapsulation.

Question 29.
W/hat is an object?
Answer:
Object is a software bundle of variables and related methods. Objects have state and behavior.

Question 30.
W/hat do you mean by inheritance?
Answer:
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Question 31.
Wffiat is namespace?
Answer:
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:

namespace identifier { namespace-body }

Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example: namespace general {int a, b;} In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:

general::a general::b

The functionality of namespaces is especially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

Question 32.
What is virtual class and friend class?
Answer:
Friend classes are used when two or more classes are designed to work .together and need access to each other’s implementation in ways that the rest of the world shouldn’t be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than mainO has.

Question 33.
WTiat is the difference between an object and a class?
Answer:
Classes and objects are separate but related concepts. Every object belongs
to a class and every class contains one or more related objects.

  • A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don’t change.
  • The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
  • An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Question 34.
What is a class?
Answer:
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

Question 35.
WTiat is friend function?
Answer:
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Question 36.
WTiich recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Answer:
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time.

Question 37.
What is abstraction?
Answer:
Abstraction is of the process of hiding unwanted details from the user.

Question 38.
What are virtual functions?
Answer:
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don’t know about the derived class.

Question 39.
What is a scope resolution operator?
Answer:
A scope resolution operator (::), can be used to define the member functions of a class outside the class.

Question 40.
What do you mean by pure virtual functions?
Answer:
Pure virtual function in object oriented programming is called as virtual method that acts as a function allowing its behavior to be overridden by the class that is inheriting the pure virtual function with the same signature. This is used in case of polymorphism. It is used when a base class is being driven by the derived class and an object of the derived class referred as base or derived class type. When a derived class overrides the base class method then the output or the behavior will be called as ambiguous. To use the virtual function a virtual keyword is used. This allows the function to be defined in every derived class and use the functionality of it.

Question 40.
What is polymorphism? Explain with an example?
Answer:
“Poly” means“many” and“morph” means“form”. Polymorphismisthe ability of anobject(orreference)toassume(bereplacedby)orbecomemanydifferentformsofobject. Example: function overloading, function overriding, virtual functions. Another example can be a plus “+’ sign, used for adding two integers or for using it to concatenate two strings.

Question 41.
What is a conversion constructor?
Answer:
A constructor that accepts one argument of a different type.

Question 42.
What is the difference between a copy constructor and an overloaded assignment operator?
Answer:
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Question 43.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
Answer:
A specialized class “is” a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee “has” a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Question 44.
What is the Standard Template Library (STL)?
Answer:
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Question 45.
In C++, what is the difference between method overloading and method overriding?
Answer:
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

Question 46.
What is a modifier?
Answer:
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’.

Question 47.
What is an accessor?
Answer:
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

Question 48.
Differentiate between a template class and class template.
Answer:
Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

Question 49.
Explain Stack & Heap Objects
Answer:
The memory a program uses is divided into four areas:

  • The code area – this is where the compiled program sits in memory.
  • The global area – the place where global variables are stored.
  • The heap – the place where dynamically allocated variables are allocated from.
  • The stack -the place where parameters and local variables are allocated from.

Question 50.
Explain deep copy and a shallow copy
Answer:

  • Deep copy – It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining object.
  • Shallow copy -It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable. This happens because of the straight copying of references and pointers.

Question 51.
Explain virtual class and friend class
Answer:
a. Virtual Base Class:
It is used in context of multiple inheritances in C++.
If you want to derive two classes from a class, and further derive one class from the two classes in the second level, you need to declare the uppermost base class as ‘virtual’ in the inherited classes. This prevents multiple copies of the uppermost base class data members when an object of the class at the third level of hierarchy is created.

b. Friend class:
When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods.
Friendship is not necessarily bi-directional. If A declares B as its friend it does not imply that A can access private data of B. It only means that B can access all data of A.
Explain the of scope resolution operator A scope resolution operator (::) is used to define the member functions of a class outside the class.
Mostly, a scope resolution operator is required when a data member is redefined by a derived class or an overridden method of the derived class wants to call the base class version of the same method.

Question 52.
What are virtual functions?
Answer:
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual. Following things are necessary to write a C++ program with runtime polymorphism use of virtual functions)

  1. A base class and a derived class.
  2. A function with same name in base class and derived class.
  3. A pointer or reference of base class type pointing or referring to an object of derived class.

Question 53.
What are the features that are provided to make a program modular?
Answer:
To create a program requires self sufficient resources, the way to make a piece of code modular so that it can be handled properly. This shows the relationship between different objects or in between the same objects. Different functions have to be used to keep the code different from the data provided. Object oriented programming allows creating a modular approach to make it more abstract and create the interactions between them. The features that are being provided in object oriented programming are:

• Encapsulation: it deals with the grouping of data and functions together at one place or it can be said in an object that defines the interface of their interaction and the relationship between them.
• Inheritance: it deals with the relationship that exists between the parent and child classes. A child can inherit the properties of the parent and it remains helpful in creating a hierarchy in the system to keep things more modular.
• Polymorphism: is a feature that deals with different values that can be used by only one function. It doesn’t have to re-create the same function again and again for different values but, it uses the same function to call different data types.

Remote Method Invocation (RMI) Interview Questions in Java

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

Remote Method Invocation (RMI) Interview Questions in Java

Question 1.
What are RMI and the steps involved in developing an RMI object?
Answer:
Remote Method Invocation (RMI) allows java objects that execute on one machine and invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are:

  • Define the interfaces.
  • Implementing these interfaces
  • Compile the interfaces and their implementations with the java compiler
  • Compile the server implementation with the RMI compiler
  • Run the RMI registry
  • Run the application

Question 2.
What is RMI architecture?
Answer:
RMI architecture consists of four layers and each layer performs specific functions:

a) Application layer                ——-     contains the actual object definition
b) Proxy layer                         ——-     consists of stub and skeleton
c) Remote Reference layer     ——-     gets the stream of bytes from the transport layer and sends it to the proxy layer
d) Transportation layer          ——-     responsible for handling the actual machine-to-machine communication

Question 3.
What is UnicastRemoteObject?
Answer:
All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

Question 4.
Explain the methods, rebind( ) and lookup( ) in Naming class?
Answer:
rebind( ) of the Naming class(found in java.rmi) is used to update the RMI registry on the server machine.
Naming. rebind(“AddSever”, AddServerlmpl);
lookup( ) of the Naming class accepts one argument, the rmi URL, and returns a reference to an object of type AddServerlmpl.

 

Java Networking Interview Questions in Java

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

Java Networking Interview Questions in Java

Question 1.
What are Datagrams and Sockets?
Answer:
A socket represents a connection point into a TCP/IP network between two computers; one of which is the server and the other is the client. Sockets are used to access the Web server. These sockets are available in the Java Socket class. Sockets act as virtual passageways for communication through which the data travels from one host to another. Sockets are of two types, connection-oriented or connectionless. The connection-oriented socket operates similarly to a telephone where the connection is established prior to the transmission of data. The second type of socket is the connectionless socket. This type of socket is called a Datagram. This socket operates similarly to the mail. A characteristic of the Datagram is that it allows only one message to be sent at a time. The delivery of data is not guaranteed because Datagrams use the UDP protocol.

Question 2.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances of InetAddress.

Question 3.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 4.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 5.
What are the seven layers of the OSI model?
Answer:
Application
Presentation
Session
Transport
Network
DataLink
Physical Layer.

Question 6.
What Transport Layer does?
Answer:
It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent.

Question 7.
What is DHCP?
Answer:
Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.

Question 8.
What is SMTP?
Answer:
Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails. SMTP exchanges mail between servers; contrast this with POP, which transmits mail between a server and a client.

Question 9.
In OSI N/W architecture, the dialogue control and token management are responsibilities of which layer?
Answer:
b) Session Layer.

Question 10.
In OSI N/W Architecture, the routing is performed by which layer?
Answer:
Network Layer.

Question 11.
What is the difference between URL instances and URLConnection instances?
Answer:
A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

Question 12.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.

Question 13.
What Is a Socket?
Answer:
A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes-Socket and ServerSocket–which implement the client-side of the connection and the server-side of the connection, respectively.

Question 14.
What information is needed to create a TCP Socket?
Answer:
The Local System’s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

Question 15.
what are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in Socket class.

Question 16.
When MalformedURLException and UnknownHostException throws?
Answer:
When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unable to resolve the hostname they throw an UnknownHostException.

Question 17.
Define Network Programming?
Answer:
It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Question 18.
What is a Socket?
Answer:
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

Question 19.
Advantages of Java Sockets?
Answer: Sockets are flexible and sufficient. Efficient socket-based programming can be easily implemented for general communications. It causes low network traffic.

Question 20.
Disadvantages of Java Sockets?
Answer:
Socket-based communications allow only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Question 21.
Which class is used by server applications to obtain a port and listen for client requests?
Answer:
java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests.

Question 22.
Which class represents the socket that both the client and server use to communicate with each other?
Answer:
java.net.Socket class represents the socket that both the client and server use to communicate with each other.

Question 23.
How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
Answer:
By InetAddress.getByName(“192.18.97.39”).getHostName( ) where 192.18.97.39 is the IP address.

Question 24.
How do I get the IP address of a machine from its hostname?
Answer:
The InetAddress class is able to resolve IP addresses for you. Obtain an instance of InetAddress for the machine, and call the get host address( ) method, which returns a string in the xxx.xxx.xxx.xxx address form.

InetAddress inet = InetAddress.getByNameC“www.davidreilly.com”); 
System.out.println (“IP: “ + inet.getHostAddress( )) ;

Question 25.
How do I perform a hostname lookup for an IP address?
Answer:
The InetAddress class contains a method that can return the domain name of an IP address. You need to obtain an InetAddress class and then call its get hostname( ) method. This will return the hostname for that IP address. Depending on the platform, a partial or a fully qualified hostname may be returned.

InetAddress inet = InetAddress.getByName(“209.204.220.121”); 
system. out.println (“Host: “ + inet.get hostname( ));

Question 26.
How can I find out who is accessing my server?
If you’re using a DatagramSocket, every packet that you receive will contain the address and port from which it was sent.

DatagramPacket packet = null;
// Receive next packet 
myDatagramsocket.receive (packet);
// Print address + port
system.out.println (“Packet From: “ + packet.getAddress( ). 
getHostAddress( ) + ' : ’ + packet. getPort( ));

If you’re using a ServerSocket, then every socket connection you accept will contain similar information. The Socket class has a getlnetAddress( ) and getPort( ) method which will allow you to find the same information.

socket mysock = myServersocket.accept( );
// Print address + port
System.out.println (“connection From: “ + mySock.getlnetAddress( ). 
getHostAddress( ) + ‘:’ + mysock. getPort( ));

27. How can I find out the current IP address for my machine?
Answer:
The InetAddress has a static method called get localhost( ) which will return the current address of the local machine. You can then use the getHostAddressO method to get the IP address.

InetAddress local = InetAddress.getLocalHost( );
// print address
System.out.println (“Local IP: “ + local .getHostAddress( ));

Question 28.
Why can’t my applet connect via sockets, or bind to a local port?
Applets are subject to heavy security constraints when executing under the control of a browser. Applets are unable to access the local file system, bind to local ports, or connect to a computer via sockets other than the computer from which the applet is loaded. While it may seem to be an annoyance for developers, there are many good reasons why such tight constraints are placed on applets. Applets could bind to well-known ports, and service network clients without authorization or consent. Applets executing within firewalls could obtain privileged information, and then send it across the network.

Applets could even be infected by viruses, such as the Java StrangeBrew strain. Applets might become infected without an applet author’s knowledge and then send information back that might leave hosts vulnerable to attack.

Signed applets may be allowed greater freedom by browsers than unsigned applets, which could be an option. In cases where an applet must be capable of network communication, HTTP can be used as a communication mechanism. An applet could communicate via java.net.URLConnection with a CGI script or a Java servlet. This has an added advantage – applets that use the URLConnection will be able to communicate through a firewall.

Question 29.
What are socket options, and why should I use them?
Socket options give developers greater control over how sockets behave. Most socket behavior is controlled by the operating system, not Java itself, but as of JDKl.l, you can control several socket options, including SOJTIMEOUT, SO_LINGER, TCP_ NODELAY, SO.RCVBUF and SO_SNDBUF.
These are advanced options, and many programmers may want to ignore them. That’s OK, but be aware of their existence for the future. You might like to specify a timeout for reading operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle’s algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.

Question 30.
How do I display more than one page from an applet?
The show document method of the AppletContext interface is overloaded – meaning that it can accept more than one parameter. It can accept a second parameter, which represents the name of the browser window that should display a page.
For example,
myAppletContext.show document (myurl, “frame 1”) will display the document in frame 1. If there exists no window named frame 1, then a brand new window will be created.

Question 31.
How do I use a proxy server for HTTP requests?
When a Java applet under the control of a browser (such as Netscape or Internet Explorer) fetches content via an URLConnection, it will automatically and transparently use the proxy settings of the browser.
If you’re writing an application, however, you’ll have to manually specify the proxy server settings. You can do this when running a Java application or you can write code that will specify proxy settings automatically for the user (providing you allow the users to customize the settings to suit their proxy servers).
To specify proxy settings when running an application, use the -D parameter:

jre -DproxySet=true -DproxyHost=myhost -DproxyPort=myport MyApp

Alternately, your application can maintain a configuration file, and specify proxy settings before using an URLConnection:

// Modify system properties
Properties sysProperties = System.getProperties( );
 // Specify proxy settings
sysProperties.put(“proxyHost”, “myhost”);
 sysProperties.put(“proxyPort”, “myport”); 
sysProperties.put(“proxySet”, “true”);

Question 32.
What is a malformed URL, and why is it exceptional?
When you create an instance of the java.net.URL class, its constructor can throw a MalformedURLException. This occurs when the URL is invalid. When it is thrown, it isn’t because the host machine is down, or the URL path points to a missing file; a malformed URL exception is thrown when the URL cannot be correctly parsed. Common mistakes include:-

  • leaving out a protocol (eg “www.microsoft.com” instead of “http://www.microsoft. com/”)
  • specifying an invalid protocol (eg “www://netscape.com”)
  • leaving out the character (eg http//www.micrsoft.com/)

MalformedURLException will not be thrown if:-

  • the hostname is invalid (eg “www.microsoft-rules-the-world.com”)
  • the path is invalid (eg “http://www.microsoft.com/company_secrets.htm”)

Question 33.
Why is a security exception thrown when using java.net.URL or java.net. URLConnection from an applet?
Answer:
Web browsers impose security restrictions on applets, which prevent applets from establishing network connections to servers other than that from which they were loaded. Like socket connections, HTTP connections will cause security exceptions to be thrown. If you absolutely, positively, have to access other hosts (and replacing your applet with a Java servlet is impractical), consider using a digitally signed applet.

Question 34.
How do I prevent caching of HTTP requests?
Answer:
By default, caching will be enabled. You must use a URLConnection, rather than the URL.openStreamO method, and explicitly specify that you do not want to cache the requests. This is achieved by calling the URLConnection.setup caches (boolean) method with a value of false.

Question 35.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be . used to create instances of InetAddress.

Question 36.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 37.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 38.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke open Connection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.
E.g.

URL url;
URLConnection connection; 
try{ url = new URL(“...”); 
conection = url.openConnection( );
} catch (MaiFormedURLException e) {  }

Question 39.
When MalformedURLException and UnknownHostException throw?
Answer:
When the specified URL is not connected then the URL throw Malforme- dURLExceptiop and If InetAddress’ methods
getByName( ) and getLocalHost( ) are unable to resolve the host name they throw an UnknownHostException.

Question 40.
What are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in the Socket class.

Java Applet Interview Questions in Java

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

Java Applet Interview Questions in Java

Question 1.
What is the difference between applications and applets?
Answer:

a) Application must be run on a local machine whereas the applet needs no explicit installation on the local machine.
b) Application must be run explicitly within a Java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
d) Application starts execution with its main method whereas applet starts execution with its init method.
e) Application can run with or without the graphical user interface whereas applet must run within a graphical user interface.

Question 2.
How does the applet recognize the height and width?
Answer:
Using getParameters( ) method.

Question 3.
When do you use codebase in the applet?
Answer:
When the applet class file is not in the same directory, the codebase is used.

Question 4.
What is the lifecycle of an applet?
Answer:
init( ) method – Can be called when an applet is first loaded
start( ) method – Can be called each time an applet is started
paint( ) method – Can be called when the applet is minimized or maximized
stop( ) method – Can be used when the browser moves off the applet’s page
destroy( ) method – Can be called when the browser is finished with the applet

Question 5.
How do you set security in applets?
Answer:
using setSecurityManager( ) method

Question 6.
How will you initialize an Applet?
Answer:
By including the initialization code in the init( ) method.

Question 7.
What is the order of method invocation in an Applet?
Answer:
init( ), start( ), paint( ), stop( ), destroy( ),

Question 8.
When is the update method called?
Answer:
Whenever we minimize, maximize, restart the applet, and explicitly calling the repaint( ) method in the code. Repaint( ) method will implicitly call the update!) method.

Question 9.
How will you communicate between two Applets?
Answer:
By creating URL object, URLConnection object and getting InputStream , OutputStream Using getlnputStream( ), getOutputStream( )

Question 10.
What is an applet?
Answer: Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

Question 11.
How does the applet recognize the height and width?
Answer.
’Using getParameters( ) method.

Question 12.
When do you use codebase in the applet?
Answer:
When the applet class file is not in the same directory, the codebase is used.

Question 13.
How do you set security in applets?
Answer:
using setSecurityManager( ) method

Question 14.
The definition of an applet named MyApplet would begin with the line

class MyApplet extends Applet {

What is going on here? What is “Applet”? What is the word “extends” doing there?
Answer:
The applet is the name of a class that is a standard part of Java. Here, MyApplet is a new class that is being defined as a subclass of Applet. The word “extends” is used to create subclasses in this way. The class MyApplet inherits everything that is in the class Applet. The rest of the definition of MyApplet will consist of additions and modifications to the stuff that is inherited from Applet.
(Note: The Applet class is actually defined in the package java. applet, so the above line has to be preceded by “import java.applet.*” or “import java.applet.Applet;” to make the applet class available.)

Question 15.
An applet can define a method
public boolean keyDown(Event evt, int key)
What is the purpose of such a method? What is the key parameter for? Why is this method “public”?
Answer:
This keyDown method will be called by the “system” when the user presses a key on the keyboard (assuming that the applet has the input focus at that time). You would write such a method to react to the user’s keystrokes. The key parameter tells which key the user pressed. This method has to be public since it is called by the system, from outside the class that contains the method.

Question 16.
Is it possible to access the network resources through an Applet on the browser?
Answer:
There is no way that an applet can access network resources. You have to implement a Java Query Server that will be running on the same machine from where you are receiving your applet (that is Internet Server). Your applet will communicate with that server which will fulfill all the requirements of the applet. You can communicate between applet and Java query server using sockets RMI (preferred, as this will return the whole object).

Question 17.
Java applets can be downloaded from anywhere and run on a client’s system. What are the restrictions imposed on Java applets that prevent them from causing system damage or security breaches?
Answer:
The restrictions that are there for Java applets are: –

  • Applets cannot read or write to the local file system where it is being executed.
  • Applets can only communicate back to the server from where it was downloaded by the browser.
  • Applets cannot execute any local program on the client’s system.

Question 18.
What is the sequence of interpretation, compilation of a java applet?
Answer:
A java program is first compiled to bytecode 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 19.
Is it possible to access the network resources through an Applet on the browser?
Answer:
There is no way that an applet can access network resources. You have to implement a Java Query Server that will be running on the same machine from where you are receiving your applet (that is Internet Server). Your applet will communicate with that server which will fulfill all the requirements of the applet. You can communicate between applet and Java query server using sockets RMI (preferred, as this will return the whole object).

Question 20.
When we give the resize function within an applet then it does not reflect the changes when we see the applet in the IE. Why does this happen?
Answer:
Applets are resized only in applet viewer, not in browsers. Change the applet height/width attributes in the HTML file and refresh IE.

Question 21.
What is the relationship between clipping and repainting?
Answer:
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

Question 22.
How do I load a serialized applet?
Answer:
Instead of specifying the CODE attribute of a <APPLET> tag, you use the OBJECT attribute, as in:

<APPLET 
OBJ ECT=TheApp1et.ser
WIDTH=300 
HEIGHT=300 
>
</APPLET>

This allows you to pre-initialize your applet to some saved state, instead of having to reinitialize your applet each time it is loaded.

Question 23.
“Why does it take so much time to access an Applet having Swing Components the first time?
Answer:
Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.

Question 24.
Which method is called by the Applet class to load an image?
Answer:
getImage(URL object, filename) is used for this purpose.

 

Java Swing Interview Questions in Java

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

Java Swing Interview Questions in Java

Question 1.
Why swing is not thread-safe?
Answer:
The Swing API was designed to be powerful, flexible, and easy to use. In particular, we wanted to make it easy for programmers to build new Swing components, whether from scratch or by extending the components that we provide. For this reason, we do not require Swing components to support access from multiple threads. Instead, we make it easy to send requests to a component so that the requests run on a single thread.

Question 2.
Which package has lightweight components?
Answer:
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame, and JWindow are lightweight components.

Question 3.
What are peerless components?
Answer:
The peerless components are called lightweight components.

Question 4.
What is the difference between the Font and FontMetrics classes?
Answer:
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

Question 5.
What is the difference between Swing and AWT components?
Answer:
AWT components are heavy-weight, whereas Swing components are lightweight. Hence Swing works faster than AWT. Heavyweight components depend on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component. Pluggable look and feel possible using java Swing. Also, we can switch from one look and feel to another at runtime in swing which is not possible in AWT.

Question 6.
Name the containers which use Border Layout as their default layout?
Answer:
window, Frame, and Dialog classes.

Question 7.
Name Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 8.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 9.
What is the difference between the paint() and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 10.
Which package has lightweight components?
Answer:
javax.The swing package contains lightweight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

Question 11.
What are peerless components?
Answer:
The peerless components are called lightweight components.

Question 12.
What is a Container in a GUI?
Answer:
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

Question 13.
How are the elements of a GridBagLayout organized?
Or
What is a layout manager and what are the different types of layout managers available in java Swing?
Or
How are the elements of different layouts organized?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using

the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 14.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

Question 15.
What method is used to specify a container’s layout?
Answer:
The setLayout( ) method is used to specify a container’s layout. For example, setLayout(new FlowLayout( )); will be set the layout as FlowLayout.

Question 16.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 17.
Name Component subclasses that support painting.
Answer:
The Canvas, Frame, Panel, and Applet classes support painting.

Question 18.
What is the purpose of the enableEvents() method?
Answer:
The enableEvents( ) method is used to enable an event for a particular component. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

Question 19.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

Question 20.
What do heavy-weight components mean?
Answer:
Heavyweight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt .The button is a heavy-weight component.

Question 21.
What is the difference between a Scrollbar and a ScrollPane?
Answer:
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Question 22.
What is the preferred size of a component?
Answer:
The preferred size of a component is the minimum component size that will allow the component to display normally.

Question 23.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and Applet classes use the FlowLayout as their default layout.

Question 24.
What is Event-Driven-Thread (EDT) in Swing?
Answer:
Event-Driven-Thread or EDT is a special thread in Swing and AWT. Event-Driven Thread is used to draw graphics and listen for events in Swing. You will get a bonus point if you are able to highlight that time-consuming operation like connecting to the database, opening a file, or connecting to the network should not be done on the EDT thread because it could lead to freezing GUI because of blocking and time-consuming nature of these operations instead of the,’ should be done on a separate thread and EDT can just be used to spawn those thread on a button click or mouse click.

Question 25.
Does Swing is thread-safe? What do you mean by swing is not thread-safe?
Answer:
Since Swing components are not thread-safe it means you cannot update these components in any thread other than Event-Driven-Thread. If you do so you will get unexpected behavior. Some time interviewer will also ask what are thread-safe methods in swing which can be safely called from any thread only a few like repaint( ) and revalidate( )

Question 26.
What are the differences between Swing and AWT?
Answer:
There is a couple of differences between swing and AWT:

  1. AWT components are considered to be heavyweight while Swing components are lightweights
  2. Swing has a pluggable look and feel.
  3. AWT is platform depended same GUI will look different on the different platforms while Swing is developed in Java and is platform-dependent.

Question 27.
Why Swing components are called lightweight components?
Answer:
AWT components are associated with native screen resources and called heavyweight components while Swing components use the screen resource of an ancestor instead of having their own and that’s why called lightweight or lighter components.

Question 28.
What is the difference between invokeAndWait and invokeLater?
Answer:
Sometimes the question is how do you update the swing component from a thread other than EDT, for such kind of scenario we use SwingUtilities. invokeAndWait(Runnable r) and SwingUtilities.invoke setter(Runnable r) though there are quite a few differences between these two, the major one is invokeAndWait is a blocking call and wait until GUI updates while invokeLater is a nonblocking asynchronous call. In my opinion, these question has its own value and every swing developer should be familiar with these questions or concept not just for interview point of view but on application perspective, you can read more on my post How InvokeAndWait and InvokeLater works in Swing

Question 29.
Write code for JTable with custom cell editor and custom cell Tenderer?
Answer:
JTable is one of the favorite topics of all Swing interviews and the most popular questions on swing interviews are from JTable why? Because here interviewer will directly ask you to write code another reason is JTable heavily used in all Electronic TRADINGS GUI. GUI used for online stock TRADINGS uses JTable to show data in tabular format so an in-depth knowledge of JTable is required to work on ONLINE TRADING GUI developed in Swing. While this question is just an example questions around JTable are mostly centered around updating the table, how do you handle a large volume of data in the table, using customize cell Tenderer and editor, sorting table data based on any column, etc. so just make sure you have done quite a few handsome exercises on JTable before appearing for any java swing interview in IB.

Question 30.
Write code to print following layout (mainly focused on GridBag layout)?
Answer:
GridBagLayout in the swing is the most powerful but at the same time, most complex layout and a clear-cut experience and expertise around GridBagLayout is desired for developing Swing GUI for trading systems. No matter whether you are developing GUI for equities trading, futures, or OPTIONS TRADING or forex trading you always required GridBagLayout. Swing interview question on GridBagLayout will be mostly on writing code for a particular layout just like an example shown here. In which six buttons A, B, C, D, E, and F are organized in a certain fashion.

Question 31.
How do you handle the opening of a database, file, or network connection with a click of a button?
Answer:
You should not do this operation in the EDT thread instead spawn a new thread from the actionListener or button and disable the button until the operation gets completed to avoid resubmitting the request. The only condition is that your GUI should always be responsive no matter what happens on a network connection or database connection because these operations usually take time.

Event Handling Interview Questions in Java

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

Event Handling Interview Questions in Java

Question 1.
What are the advantages of the model over the event-inheritance model?
Answer:
The event-delegation model has two advantages over the event-inheritance model. They are:

a) It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.

b) It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events as is the case of the event inheritance.

Question 2.
What are source and listener?
Answer:
Source: A source is an object that generates an event. This occurs when the internal state of that object changes in some way.
Listener: A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications.

Question 3.
What is adapter class?
Answer:
An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( )and mouseMoved( ).

The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged( ).

Question 4.
What is an event and what are the models available for event handling?
Answer:
An event is an event object that describes a state of change in a source. In other words, an event occurs when an action is generated, like pressing a button, clicking the mouse, selecting a fist, etc.
There are two types of models for handling events and they are:

a) event-inheritance model and
b) event-delegation model

Question 5.
What are the advantages of the model over the event-inheritance model?
Answer:
The event-delegation model has two advantages over the event-inheritance model. They are:

a) It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.

b) It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events as is the case of the event inheritance.

Question 6.
what is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?
Answer:
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

Question 7.
What is the highest-level event class of the event-delegation model?
Answer:
The java. util.EventObject class is the highest-level class in the event- delegation class hierarchy.

Question 8.
What event results from the clicking of a button?
Answer:
The ActionEvent event is generated as the result of the clicking of a button.

Question 9.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 10.
What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?
Answer:
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

Question 11.
What is the purpose of the enableEvents( ) method?
Answer:
The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

Question 12.
What interface is extended by AW^T event listeners?
Answer:
All AWT event listeners extend the java. util.EventListener interface.

Question 13.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 14.
What is the purpose of the enableEvents( ) method?
Answer:
The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

String Handling Interview Questions in Java

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

String Handling Interview Questions in Java

Question 1.
What is String in Java? The string is a data type?
Answer:
The string is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. The String class represents character strings. The string is used in almost all Java applications and there are some interesting facts we should know about String. The string is immutable and final in Java and JVM uses String Pool to store all the String objects. Some other interesting thing about String is the way we can instantiate a String object using double quotes and overloading the “+” operator for concatenation.

Question 2.
What are different ways to create String Object?
Answer:
We can create a String object using a new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in the String class to get String from a char array, byte array, StringBuffer, and StringBuilder.

String str = new String(“abc”); 
String str1 = “abc”;

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with the same value. If found, it just returns the reference to that String object else it creates a new String object with a given value and stores it in the String pool.

When we use a new operator, JVM creates the String object but doesn’t store it in the String Pool. We can use the intern( ) method to store the String object into the String pool or return the reference if there is already a String with equal value present in the pool.

Question 3.
Write a method to check if the input String is Palindrome?
Answer:
A String is said to be Palindrome if its value is the same when reversed. For example “aba” is a Palindrome String.
String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder class have a reverse method that we can use to check if String is palindrome or not.

private static boolean is palindrome(string str) {
if (str == null)
     return false;
     StringBuilder strBuilder = new stringBuilder(str);
     strBuilder. reverse( );
     return strBuilder.tostring( ).equals(str);
}

Sometimes interviewer asks not to use any other class to check this, in that case we can compare characters in the String from both ends to find out if it’s palindrome or not.

private static boolean isPalindromestring(String str) {
if (str == null)
      return false;
      int length = str.length( );
      System.out.println(length / 2);
for (int i = 0; i < length / 2; i++) {

      if (str.charAt(i) != str.charAt(length - i - 1))
      return false;
  }
  return true;
}

Question 4.
Write a method that will remove the given character from the String?
Answer:
We can use the replaceAll method to replace all the occurrences of a String with another String. The important point to note is that it accepts String as an argument, so we will use Character class to create String and use it to replace all the characters with empty String.

private static String remove char(string str, char c) {
   if (str == null)
           return null;
       return str.replaceAll(Character.toString(c) "");
}

Question 5.
How can we make String upper case or lower case?
Answer:
We can use String class toUpperCase and toLowerCase methods to get the String in all upper case or lower case. These methods have a variant that accepts the Locale argument and uses that locale rules to convert String to upper or lower case.

Question 6.
What is the String subSequence method?
Answer:
Java 1.4 introduced the CharSequence interface and String implements this interface, this is the only reason for the implementation of the subSequence method in the String class. Internally it invokes the String substring method.

Question 7.
How to compare two Strings in a java program?
Answer:
Java String implements a Comparable interface and it has two variants of compareTo( ) methods.

compareTo(String another string) method compares the String object with the String argument passed lexicographically. If the String object precedes the argument passed, it returns a negative integer and if the String object follows the argument String passed, it returns a positive integer. It returns zero when both the String have the same value, in this case, the equals(String str) method will also return true.

compareToIgnoreCase(String str): This method is similar to the first one, except that it ignores the case. It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison. If the value is zero thenequalsIgnoreCase(String str) will also return true.

Question 8.
How to convert String to char and vice versa?
Answer:
This is a tricky question because String is a sequence of characters, so we can’t convert it to a single character. We can use the charAt method to get the character at the given index or we can use the toCharArrayOmethod to convert String to a character array. Check this post for a sample program on converting String to character array to String.

Question 9.
How to convert String to byte array and vice versa?
Answer:
We can use the String get bytes( ) method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.

Question 10.
Can we use String in the switch case?
Answer:
This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier java versions don’t support this. If you are implementing conditional flow for Strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions.

Question 11.
Write a program to print all permutations of String?
Answer:
This is a tricky question and we need to use recursion to find all the permutations of a String, for example, “AAB” permutations will be “AAB”, “ABA”, and “BAA”. We also need to use Set to make sure there are no duplicate values.

Question 12.
Write a function to find out the longest palindrome in a given string?
Answer:
A String can contain palindrome strings in it and to find the longest palindrome in a given String is a programming question.

Question 13.
Difference between String, StringBuffer, and StringBuilder?
Answer:
The string is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource-consuming, so java provides two utility classes for String manipulations — StringBuffer and StringBuilder.

StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on the same String, we should use StringBuffer but in a single-threaded environment, we should use StringBuilder.

StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.

Question 14.
Why String is immutable or final in Java
Answer:
There are several benefits of String because it’s immutable and final.

  • String Pool is possible because String is immutable in java.
  • It increases security because any hacker can’t change its value and it’s used for storing sensitive information such as database username, password, etc.
  • Since String is immutable, it’s safe to use in multi-threading and we don’t need any synchronization.
  • Strings are used in java classloader and immutability provides security that the correct class is getting loaded by Classloader.

Question 15.
How to Split String in java?
Answer:
We can use split(String regex) to split the String into String array based on the provided regular expression.

Question 16.
Why Char array is preferred over String for storing passwords?
Answer:
The string is immutable in java and stored in the String pool. Once it’s created it stays in the pool until unless garbage is collected, so even though we are done with the password it’s available in memory for a longer duration and there is no way to avoid it. It’s a security risk because anyone having access to a memory dump can find the password as clear text.

If we use a char array to store passwords, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Question 17.
How do you check if two Strings are equal in Java?
Answer:
There are two ways to check if two Strings are equal or not — using the “==” operator or using the equals method. When we use the “==” operator, it checks for the value of the String as well as reference but in our programming, most of the time we are checking the equality of String for value only. So we should use the equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore the case.
String s1 = “abc”;
String s2 = “abc”;
String s3= new String(“abc”);
System.out.println(“s1 == s2 ? “+(s1==s2)); //true
System.out.println(“s1== s3 ? “+(s1=s3)); //false
System.out.println(“sl equals s3 ? “+(sl.equals(s3))); //true

Question 18.
What is String Pool?
Answer:
As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.

Question 19.
What does the String intern( ) method do?
Answer:
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool, and a reference to this String object is returned.
This method always returns a String that has the same contents as this string but is guaranteed to be from a pool of unique strings.

Question 20.
Does String is thread-safe in Java?
Answer:
Strings are immutable, so we can’t change their value in the program. Hence it’s thread-safe and can be safely used in a multi-threaded environment.

Question 21.
Why String is a popular HashMap key in Java?
Answer:
Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for a key in a Map and its processing are fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

Question 22.
What is the Contract between hashcode and equal method?
Answer:
The Java superclass java. lang. The object has two very important methods defined.

public boolean equals(Object obj) 
public int hashcode( )

It is very important to understand the contract between equals and hashcode. The general contract of hashCode is:
Whenever the hashCode method is invoked on the same object more than once during the execution of the application, the hashCode method consistently returns the same integer value.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java. lang. Object)method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Question 23.
What is a Hash Code collision?
Answer:
The idea of hashing is to store an element into the array at a position index computed as below.

  • obtain element_hash_code of the element by processing the element’s data and generating an integer value.
  • use a simple mod operation to map into the array’s range: index = hash(element) = abs(element_hash_code % array_capacity)

The hashcode collision occurs when the index calculated by hash function results same for two or more elements.

Question 24.
Why StringBuffer is called mutable?
Answer:
The String class is considered immutable; so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to the Strings of characters then StringBuffer should be used.

Question 25.
What is the difference between StringBuffer and StringBuilder class?
Answer:
Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

Question 26.
Define immutable object?
Answer:
An immutable object can’t be changed once it is created.

Question 27.
Explain the scenarios to choose between String, StringBuilder, and StringBuffer?
Answer:

  • If the Object value will not change in a scenario use String Class because a String object is immutable.
  • If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized (means faster).
  • If the Object value may change and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread-safe (synchronized).

Question 28.
Difference between String, StringBuffer, and StringBuilder?
Answer:

String StringBuffer StringBuilder
The string is an immutable class StringBuffer is a mutable class StringBuilder is a mutable class
The new object is created every time when modified No new object is created, modification is done in the existing one No new object is created, modification is done in the existing one
Syntax-string s1=”hello”; Syntax – StringBuffer sf=new StringBuffer(“hello”); Syntax – StringBuilder sb=new StringBuilder(“hello”);
StringBuffer methods are synchronized. StringBuilder methods are non-synchronized and added in JDK 5.
Use String if you require immutability Use StringBuffer in java if you need mutable + thread – safety. Use string builder in java if you require mutable + without thread safety.