Scope of local and global variables in C

What is the scope of local and global variables in C.

Scope of local variables

  • Local variables can only be accessed by other statements or expressions in same scope.
  • Local variables are not known outside of their function of declaration or block of code.

Scope of global variables

  • Global variables can be accessed form anywhere in a program. The scope of the global variables are global throughout the program.
  • Any function can access and modify value of global variables.
  • Global variables retains their value throughout the execution of entire program.

What are the uses of main function in C.

  • Execution of any C program starts from main function.
  • The main function is compulsory for any C program.
  • C program terminates when execution of main function ends.

OOPS Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on OOPS

Note: We have come out with a exclusive book on ‘OOP’s with real project scenarios’. In this book 
          we have tried to understand OOP’s fundamentals and also tried to apply them on projects by 
          simulating project scenarios.

Question 1.
What Is Object-Oriented Programming?
Answer:
OOP is a software designing technique where we think in terms of real-world objects.

Question 2.
What are a class and object?
Answer:
Class is a blueprint/template. Objects are instances of classes, in other words, they bring life in class. To use a class we need to ideate an object.

Question 3.
What are different properties provided by object-oriented systems?
Answer:
Following are characteristics of an object-oriented system:

Abstraction: Abstraction means show only what is necessary. Example color is abstracted to RGB (Red, Green Blue). By just making the combination of these three colors we can achieve any color in the world. So rather than remembering each and every color we just use RGB.

Encapsulation: It is a process of hiding all the complex processing from the outside world and makes your objects simple.

Inheritance: This concept helps to define the parent-child relationship between classes.

Polymorphism: It is a property of an object to act differently under different conditions. For instance, a simple user object depending on conditions can act as an admin or as a data entry object.
Remember the word APIE (Abstraction, Polymorphism, Inheritance, and Encapsulation).

Question 4.
How can we implement encapsulation in .NET?
Answer:
Encapsulation can be achieved by using the below five access modifiers.

  • Private: Only members of the class have access to the variables.
  • Protected: All members in the current class and in derived classes can access the variables.
  • Friend (internal in C#): Only members in the current project have access to the elements.
  • Protected friend (protected internal in C#): All members in the current project and all members in the derived class can access the variables.
  • Public: All members have access to all classes and projects.
Note: This question can also be tweaked by asking what are the different access modifiers in .NET

Question 5.
What’s the difference between abstraction and encapsulation?
Answer:

Note:  This question is a bit confusing question. Abstraction says show only what is necessary 
         and encapsulation says hide complexity. Does it look like talking the same things with different faces?

Abstraction and encapsulation complement each other. Encapsulation implements abstraction. Abstraction is the design process while encapsulation happens during the coding phase which is achieved by using access modifiers. Abstraction is done in the design phase while encapsulation is implemented in the execution phase using access modifiers.

Question 6.
How is inheritance implemented in .NET?
Inheritance is implemented by using the “:” symbol.
Below is a simple code snippet where we have the “Customer” class which is the parent class. We have then created a child class called “CustomerDiscount” which inherits all the properties and adds a “Discount” property.

class Customer
{
       public string customer name;
       public string customer code;
}
class CustomerDiscount: Customer
{
       public double Discount;
}

Question 7.
What are the two different types of polymorphism?
Answer:
There are two kinds of polymorphism static and dynamic. Many people also call them runtime or compile-time polymorphism.

Question 8.
How can we implement static polymorphism?
Answer:
Static polymorphism is implemented by using method overloading. In compile-time itself, we come to know if there are mismatches. The below code snippet shows how method overloading is implemented. The add method can take either 2 inputs or 3 inputs.
Depending on the number of inputs the addition logic is executed.

// add method with 2 inputs,
objmaths.add(1, 2);
// add method with 3 inputs,
objmaths.add(1, 2, 3);

Question 9.
How can we implement dynamic polymorphism?
Answer:
Dynamic polymorphism is implemented by using override and virtual keywords.
Below is a simple code snippet that has three classes, Customer class is the parent class.
CustomerDiscountlOPercent and CustomerDiscount2OPercent are child classes.
Customer parent class has a discount function which returns zero discounts. This function is defined as virtual and then overridden by both the child classes with 10% and 20% discounts.

class Customer
{
      public string customerName;
      public string customerCode;
      public virtual int Discount( )
      {
            return 0;
      }
}
class CustomerDiscountlOPercent: Customer
{
      public override int Dis.count( )
      {
          return 10;
      }
}
class CustomerDiscount20Percent: Customer
{
      public override int Discount()
      {
          return 20;
      }
}

Now on the client-side on the fly, your parent object can point to any child classes and invoke the child implementation accordingly. This is called dynamic polymorphism; the parent object can point to any of the child objects and invoke the child function dynamically.

Customer obj;
obj = new CustomerDiscountlOPercent();
obj = new CustomerDiscount2OPercent();

Question 10.
What are downcasting and upcasting?
Answer:
“Upcasting” means moving subclass objects to the parent class object. “Downcasting” is opposite to “Upcasting” moving the parent object to the child object.

OOP Interview Questions in . NET chapter 3 img 1

“Upcasting” is perfectly valid but “Downcasting” is not allowed in .NET as shown in Figure 3.1. For instance below is a simple “Customer” parent class which is further inherited by a child class “GoldCustomer”.

class Customer
{
}
class GoldCustomer: Customer
{
}

Below is an “upcasting” code where the child-parent class GoldCustomer is pushed to the Customer class.

Customer obj=new GoldCustomer( );

Below is a sample of “downcasting” code where a parent class object is tried to move to a child class object, this is not allowed in .NET.

GoldCustomer obj = new Customer( ); //not allowed illegal

Question 11.
What is the difference between overriding and overloading?
Answer:

Note:  I am not sure why this question is asked frequently. It’s like comparing apples with mangoes. 
          Probably it’s just the common word “over” which confuses developers.

Overloading is a concept where we can have the same method names with different input signatures. In overriding, we have a parent class with virtual functions which are overridden in the child classes.

Question 12.
What is operator overloading?
Answer:
Operator overloading is a concept of polymorphism where you can redefine operators like +, *, etc.,
with additional functionalities.

For instance, we can redefine the + functionalities to add objects like obj l + obj 2. Below is the simple code snippet which redefines the + operator.

class SomeClass
{
      private int someValue;
      public SomeClass(int val)
      {
            someValue = val;
      }
      public static SomeClass operator +(SomeClass argl, SomeClass arg2)
      {
            return new SomeClass(arg1.someValue + arg2.someValue);
      }
}

You can now use the + operator to add objects of type some class as shown in the below code snippet.

Obj = obj1 + obj2;

Question 13.
What are abstract classes?
Answer:
An abstract class is a half-defined parent class. The full implementation of abstract class is defined by the child classes.
For example below code, snippet shows a simple abstract class/half-defined class called “DatabaseCommon” and later the concrete classes, i.e., “SQLServer” and “Oracle” inherit and define a complete implementation for the same. To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public class SQLServer: DatabaseCommon
{
}
public class Oracle: DatabaseCommon
{
}

Question 14.
What are abstract methods?
Answer:
Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw an error.

Question 15.
What is an Interface?
Answer:
An interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only an empty definition of methods, functions, events, and indexers.

Interfaces provide the forced implementation. For instance, in the below code snippet we have created a simple interface called ” id compulsory”. The below classes who implement interface “id compulsory” have to provide an implementation for “ExecSgi”.

interface IDbCompulsory
{
       void ExecSql();
}
public class SQLServer: IDbCompulsory
{
       public void ExecSql( )
{
// Here code for firing SQL Server SQL statements
// are written
}
}
public class Oracle: IDbCompulsory
{
      public void ExecSql()
      {
          // Here code for firing Oracle SQL statements
         // are written
      }
}

Question 14.
Does the interface have an accessibility modifier?
Answer:
All elements in the Interface should be public. So no accessibility modifier is required.

Question 15.
Can we create an object of the abstract class or an interface?
Answer:
No.

Question 16.
What is the difference between abstract classes and interfaces?
Answer:

Abstract class Interface
Implementation Some methods in abstract classes can have implementation. All methods, functions, properties in interfaces have to empty compulsorily.
Scenario Abstract classes are used when we want to share a common functionality in the parent-child relationships. Interfaces are used to define contracts, enforce standardization, decoupling, and dynamic polymorphism.
Variable declaration We can declare variables. In interface, we cannot declare variables.
Ingeritance VS Implementation Abstract classes are inherited. Interfaces are implemented.

Question 17.
An abstract with only an abstract method, how is it different from interfaces?
Answer:
If you define all methods, functions, properties as abstract in abstract class it inhibits the same behavior as an interface.

Question 18.
If we want to update the interface with new methods, what is the best practice?
Answer:
The biggest use of the interface is to ensure that strict contract is followed between clients and components. So that when changes happen on the components clients do not have to change too much. In real-world contracts between two parties do not change which implies that interfaces should also not change.

So if you want to add new methods or change methods in interfaces the best practice is to create new interfaces by inheriting. With this approach, your older client who is using the interface stays happy and the new clients who want those new or changed methods get the benefits of the new functionality.

Let’s consider you have a simple interface called ” view” which helps you to view data. Below is the code for the same. Let’s consider that this interface is consumed by many clients.

interface IView
{
public void View( );
}

Over a period of time some users demand “Edit” functionality as well but the rest of the users are happy with the ‘View” functionality and they do not want them to get affected by these changes. Now if you go and change this interface (“IView”) as shown in Figure 3.2 you will be disturbing everyone.

So the best option would be to add a new interface, i.e., “lEdit” which inherits from “IView”. So the “lEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is not changed at all.

OOP Interview Questions in . NET chapter 3 img 2

interface IEdit: IView
{
public void Edit();
}

So putting this whole story in one single sentence for the interviewer.

Interface once fixed should not be changed. If we ever have to add new functions, new interfaces 
should be created so that we do not break compatibility with old clients.

Question 19.
What is a delegate?
Answer:
Delegate is an abstract pointer to a function or method. In other words, you can create a pointer that points to a method or function and then pass that pointer wherever you wish and invoke the function/ method.

Question 20.
How can we create a delegate?
Answer:
Creating a delegate is a four-step process:
  • Declare a delegate
  • Create an object reference
  • Point the reference to the method
  • Invoke the method via the delegate
Below is the code snippet for the same.
// Declare a delegate
public delegate int PointToAdd(int i, int y) ;
// Create a reference pointer
PointToAdd objpointer = null;
// Point to the method
objpointer = Add;
// Invoke the function/method
objpointer.Invoke(10, 20);
Question 21.
What is a multicast delegate?
Answer:
Normally when you create a delegate, your delegate points to only one function or method. In case you want to point to multiple functions and invoke them sequentially, you need to use the multicast delegate.
To point to multiple functions using delegate pointers we need to use the “+=” sign as shown in the below code snippet.
ptrcall += Method1;

ptrcall += Method2;
Question 22.
What are Events?
Answer:
Events are a higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. The event provides a publisher/subscriber mechanism model.
So subscribers subscribe to the event and the publisher then pushes messages to all the subscribers. Below is a simple code snippet for the same:
Create a delegate and declare the event for the same.
public delegate void CallEveryone( );

public event CallEveryone MyEvent;
Raise the event.
MyEvent( );
Attached client methods to the event are fired/notified.
obj. MyEvent += Function 1;
Question 23.
What is the difference between delegates and events?
Answer:
They(l) What is the difference between delegate and events? can not be compared because one derives from the other.
  • Actually, events use delegates at the bottom. But they add an extra layer of security on the delegates, thus forming the publisher and subscriber model.
  • As delegates function as pointers, they can move across any client. So any of the clients can add or remove events, which can be confusing. But events give the extra protection/encapsulation by adding the layer and making it a publisher and subscriber model. Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.
Question 24.
Do events have a return type?
Answer:
No, events do not have a return type.
Question 25.
Can events have access modifiers?
Answer:
Yes.
Question 26.
Can we have shared events?
Answer:
Yes, you can have shared events, do note only shared methods can raise shared events.
Question 27.
Explain Action, Func, Anonymous methods, and Lambda expressions.
Answer:
Left to the readers.
Question 28.
What is shadowing?
Answer:
Shadowing replaces the complete element of the parent class. For instance, you can see in the below sample code where the cisParent has a variable int “i”, which is replaced by the child class child by a method “i”. In other words when you refer to the parent object “i” it is a variable and when you refer to the child object” i” it is a method.
class clsParent
{
      public int i=0;
}
class cisChild: cisParent
{
     public new void i()
     {
          Console.WriteLine("Hey i became a method");
     }
}

Question 29.
What is the difference between shadowing and overriding?
Answer:
Overriding redefines only the implementation while shadowing redefines the whole element.

Question 30.
If we inherit a class do the private variables also get inherited?
Answer:
Yes, the variables are inherited.
Question 31.
How can we stop the class from further inheriting?
Answer:
We can stop the class from further inheriting by using the “sealed” keyword. For instance below is a sample code where we have a class called “Human” which is further inherited to create a “Male” or “Female” class.
Now the below code is great but we do not have anyone to further inherit from the “Male” or “Female” class. In simple words, “Male” and “Female” are the last legs in this inheritance hierarchy. This can be done by using the “sealed” keyword.
public class Human
{ }
public sealed class Male: Human
{ }
public sealed class Female: Human
{ }

If anyone tries to inherit the sealed classes an error appears” cannot derive from sealed type”.

Question 32.
What is the use of the “Must Inherit” keyword in VB.NET?
Answer:
If you want to create an abstract class in VB.NET it is done by using the “Must Inherit” keyword. You cannot create an object of a class, which is marked as “Must Inherit”. When you define the “Must Inherit” keyword for a class, you can only use the class by inheriting it.
Question 33.
What are the similarities between class and structure?
Answer:
Following are the similarities between classes and structures:
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Structures and classes can implement the interface.
  • Both of them can have constructors with and without parameters.
  • Both can have delegates and events.
Question 34.
What is the difference between class and structure?
Answer:
Following are the key differences between them:
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage Collector (GC). Structures are not destroyed using GC.
Question 35.
When to use structures and when to use classes?
Answer:
You will use structures when:
Point 1: If you want to represent a custom value type. This custom value type is derived from primitive data types (int, double). Some of the examples of custom types are coordinates (which have X, Y), complex numbers (which have real and imaginary components). You can also term these things as value objects or technical objects. Technical objects do not represent real-world objects like customers, suppliers, invoices, etc.
Point 2: If you want to have a low memory footprint. For instance, let’s say you want to plot a graph. To plot a graph you need to have 100’s of objects created so that you can represent coordinates. Now if you create a class and generate those 10Q’s of objects you end up putting a lot of load on your garbage collector. If you create a “struct”, it is a value type as shown in Figure 3.3. So they get created and destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
OOP Interview Questions in . NET chapter 3 img 3
Question 36.
What does virtual keyword mean?
Answer:
The signifies that method and property can be overridden by the child classes.
Question 37.
What are shared (VB.NET)/Static(C#) variables?
Answer:
When you define a variable as static or shared only one instance of the object or variable is created.
Question 38.
What is an enum and what are the benefits of using it?
Answer:
enum helps to define, manage and assign constants in an effective way. Now the below sample code is good but the level values are not readable.
if (level == 0)(Console.WriteLine(“Below quality”);}
else if (level == 1)(Console.WriteLine(“Moderate quality”);}
else if(level == 2)(Console.WriteLine(“High quality”);}
Now by declaring a simple enum called Quality as shown below.
enum Quality
{
Low = 0,
Moderate = 1,
High = 2
};

Our code would look more readable as shown below. The other big benefit is if we change the numeric values of quality we do not have to change throughout the project. So we can go a change the Low quality to 1 and no change in code is required.

if (level == Quality.Low)(Console.WriteLine(“Below quality”);}
else if (level == Quality.Moderate)(Console.WriteLine(“Moderate quality”);}
else if(level == Quality.High)(Console.WriteLine(“High quality”);}
So summarizing enum has two big benefits:
  • Code becomes more readable.
  • Easy to change constants without affecting the project. Easy maintenance.
Question 39.
What is the use of Flags in the enum?
Answer:
“Flags” is an enum attribute. If you want to set multiple values to an enum we need to use Flags.
[Flags]
enum MyColors
{
Green = 0,
Red = 1,
Blue = 2
} ;

In the below code we are setting “MyColors” enum to “Blue” and “Green” valuess.

MyColors color = MyColors.Blue | MyColors.Green;


if ((color & MyColors.Blue) == MyColors.Blue)
{
Console.WriteLine(" Blue");
}
if ((color & MyColors.Green) == MyColors.Green)
{
Console.WriteLine(" Green");
}

Question 40.

How can we loop through Enum values?
Answer:
We can use the “Get values ( )” method of the “Enum” class which returns an array of Enum values.
varx = Enum. GetValues(typeot(MyColors));

Question 41.
What is the use of the “Enum. parse” method?
Answer:
Interviewers can also put this question differently on how to convert a string to an Enum value.

OOP Interview Questions in . NET chapter 3 img 4

Many times we would like to convert a string into Enum objects. For example, let’s say you have a color Enum and you would like to pass string “Red” and get Enum object “color. Red”.

“Enum. parse” method parses the string to an Enum value. Like in the below code we pass the “Red” string value and it gets typecasted to enum which has green Enum as a constant.

MyColors EnumColors = (MyColors)Enum.Parse(typeof(MyCo!ors), “Red”);

Question 42.
What are nested classes?
Answer:
Nested classes are classes within classes.
If you create the child class object which constructor will fire first?

public class class1
{
public class1( ){ }
}
public class class2: class1
{
public class2( ){ }
}

Parent class constructor will fire first.

Question 43.
In what instances you will declare a constructor to be private?
Answer:
When we create a private constructor, we cannot create an object of the class. Private constructors are used when we want only a single instance of the class to be created and externally no one can use the ‘ new’ keyword to create the object.

Question 45.
Can we have different access modifiers on getting/set methods of a property?
Answer:
Yes, we can have different access modifiers. The below code will compile perfectly well.

public string CustName
{
get
{
return _Custname;
}
protected set
{
Custname = value;
}
}

Question 46.
How can you define a property read-only for the external world and writable in the same assembly?
Answer:

This question is a variation to the previous question. So it's possible that the interviewer 
  can ask the previous question in this format.

Let’s first try to understand this question. Let’s say if you have a class called “Customer” with a property “CustomerCode”. Now you want that anyone can read from the “CustomerCode” property but this property can only be set from within the assembly.
In other words, anyone can run the below code.

Customer obj = new Customer();
string x = obj.CustomerCode;

But the setting of the value can be only done from within assembly. The below code will run only if it is within the assembly and it will throw an error if it is external to the assembly.

Customer obj = new Customer( );
obj. CustomerCode - “c001”;

This can be achieved by having different access modifiers for “set” and “get” properties on the “CustomerCode” property.

So for the “get”, we will have public access modifiers and for “set” we will apply internal access modifiers. Now because “get” is public this property can be read anywhere and because the “set” is internal it can only be accessed from within assembly. Below is the code for the same.

class Customer
{
      private string _CustomerCode = " ";
      public string CustomerCode
      {
           get { return _CustomerCode; }
           internal set { _CustomerCode = value; }
      }
}

Question 47.
Will the final run in this code?
Answer:
In the below code in the try statement we have a return statement, will the finally block still run.

public static void Main()
{
    try
   {
        // Some code
        return;
  }
  finally
 {
        //Will this run
  }
}

Yes, the final code will run even though there is a return statement in the trial. The final block will run irrespective of what happens in the try block. That’s the reason why finally block is a good place to put clean up code.

Question 48.
What is an Indexer?
Answer:
Many times classes have contained (aggregated or composed) collections. For example, in the below code you can see we have a customer class that has an Address collection.

public class Customer
{
private List<Address> Addresses = new List<Address>( );
}

Now let’s say we would like to fetch the addresses collected by “Pincode” and “PhoneNumber”. So the logical step would be that you would go and create two overloaded functions one which fetches by using “PhoneNumber” and the other by “PinCode”. You can see in the below code we have two functions defined.

public Address getAddress(int PinCode)
{
       for each (Address o in Addresses)
       {
              if (o.Pincode == PinCode)
              {
                   return o;
              }
       }
       return null;
}
public Address getAddress(string PhoneNumber)
{
      for each (Address o in Addresses)
      {
            if (o.MobileNumber == PhoneNumber)
            {
                   return o;
            }
      }
      return null;
}

Now on the client-side, your code would look something as shown below.

Customer Customers = new Customerf);
Customers.getAddress(1001);
Customers.getAddress(“9 090”) ;

Now the above code is great but how about simplifying things further. How about something more simple as shown in the below code. In other words, the class itself is to be indexed.

Customer Customers = new Customer();
Address o = Customers[10001]; o = Customers[“4320948”];

You can see in the Figure 3.5 where we can have two overloaded indexers “Pincode” and “PhoneNumber”.

 

OOP Interview Questions in . NET chapter 3 img 5

This can be achieved by using an indexer. There are two things we need to remember about indexers:

  • “Indexer” is defined by using the ” this” keyword.
  • “Indexer” is a property so we need to define set and get for the same.

Below is the code implementation for the indexer. You can see we have used the “this” keyword with two overloaded functions one which will fetch us address by using the “PhoneNumber” and the other by using “PinCode”.

public class Customer
{
       private List<Address> Addresses = new List<Address>( );
       public Address this[int PinCode]
       {
           get
           {
                  for each (Address o in Addresses)
                  {
                         if (o.Pincode == PinCode)
                         {
                              return o;
                         }
                 }
                 return null;
            }
}
public Address this[string PhoneNumber]
{
      get
      { 
            for each (Address o in Addresses)
            {
                  if (o.MobileNumber == PhoneNumber)
                  { 
                           return o;
                  }
          }
          return null;
         }
     }
}

Once you put the above “indexer” code you should be able to access the address collection from the Customer object using an indexer ” [ ]” as shown in Figure 3.5.

Summarizing in one sentence: Indexers help to access contained collection within a class using a simplified interface. It is syntactic sugar.

Question 49.
Can we have a static indexer in C#?
Answer:
NO.

What do you mean by prototype of a function

What do you mean by prototype of a function.

function declaration or prototype in C tells the compiler about function name, function parameters and return value of a function. The actual body of the function can be defined separately.
Here is the syntax of function declaration:

return_type function_name(type arg1, type arg2 .....);

Like variable in C, we have to declare functions before their first use in program.

Important points about function declaration.

  • Function declaration in C always ends with a semicolon.
  • By default the return type of a function is integer(int) data type.
  • Function declaration is also known as function prototype.
  • Name of parameters are not compulsory in function declaration only their type is required. Hence following declaration is also valid.
    int getSum(int, int);
  • If function definition is written before main function then function declaration is not required whereas, If function definition is written after main function then we must write function declaration before main function.

What is difference between Call by value and Call by reference in C.

Call by Value

In call by value method a copy of actual arguments is passed into formal arguments in the function definition. Any change in the formal parameters of the function have no effect on the value of actual argument. Call by value is the default method of passing parameters in C. Different memories are allocated for the formal and actual parameters.
Here is an example of call by Value

 
void getDoubleValue(int F){
   F = F*2;
   printf("F(Formal Parameter) = %d\n", F);
}

Call by Reference

In call by reference method the address of the variable is passed to the formal arguments of a function. Any change in the formal parameters of the function will effect the value of actual argument. Same memory location is accessed by the formal and actual parameters.
Here is an example of call by reference

void getDoubleValue(int *F){
   *F = *F + 2;
   printf("F(Formal Parameter) = %d\n", *F);
}

MYSQL Interview Questions for Freshers

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

MYSQL Interview Questions for Freshers

Question 1.
What is c#?
Answer:
C# is an object-oriented, type-safe, and managed language that is compiled by the .Net framework to generate Microsoft Intermediate Language.

Question 2.
Explain types of comments in C# with examples
Answer:

Single line 


Example:


//This is a single line comment


ii. Multiple line (/* */)


Example:


/*This is a multiple line comment


We are in line 2


Last line of comment*/


iii. XML Comments (///).


Eg: 


/// summary;


/// Set error message for multilingual language.


/// summary

Question 3.
Can multiple catch blocks be executed?
Answer:
No, Multiple catch blocks can’t be executed. Once the proper catch code is executed, the control is transferred to the final block, and then the code that follows the final block gets executed.

Question 4.
What is the difference between public, static, and void?
Answer:
Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. Static members are by default not globally accessible it depends upon the type of access modified used. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value.

Question 5.
What is an object?
Answer:
An object is an instance of a class through which we access the methods of that class. The “New” keyword is used to create an object. A class that creates an object in memory will contain information about the methods, variables, and behavior of that class.

Question 6.
What is a Class?
Answer:
A Class is an encapsulation of properties and methods that are used to represent a real¬time entity. It is a data structure that brings all the instances together in a single unit.

Question 7.
Define Constructors.
Answer:
A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

Question 8.
What is the difference between ref & out parameters?
Answer:
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not be initialized before passing to a method.

Question 9.
What is the use of the ‘using’ statement in C#?
Answer:
The ‘using’ block is used to obtain a resource and process it is then automatically disposed of when the execution of the block is completed.

Question 10.
Can we use the “this” command within a static method?
Answer:
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

Question 11.
What is the difference between constants and read-only?
Answer:
Constant variables are declared and initialized at compile time. The value can’t be changed afterward. Read-only is used only when we want to assign the value at run time.

Question 12.
What is an interface class? Give one example of it
Answer:
An Interface is an abstract class that has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace DemoApplication 
{
interface Guru99lnterface
{
void SetTutorial(int pID, string pName);
String GetTutorial( );
}
class Guru99Tutorial: Guru99lnterface
{
protected int TutoriallD;
protected string TutorialName;

public void SetTutorial(int pID, string pName)
{
TutoriallD = pID;
TutorialName = pName;
}

public String GetTutorial( )
{
return TutorialName;
}
static void Main(string[ ] args)
{
Guru99Tutorial pTutor = new Guru99Tutorial( );

pTutor.SetTutorial(l,".Net by Guru99");

Console. WriteLine(pTutor.GetTutorial());

Console.ReadKey( );
}
}
}

Question 13.
The basis of comparison Between C# Interface vs Abstract Class C# Interface
Answer:
Access Specifier: In C#, Interface cannot have an access specifier for functions. It is public by default.
Implementation: In C#, an interface can only have a signature, not the implementation.
Speed: Interface is comparatively slow.
Instantiate: Interface is absolutely abstract and cannot be instantiated.
Fields: Interface cannot have fields.
Methods: Methods

C# Abstract Class

Access Specifier: In C#, an abstract class can have an access specifier for functions.
Implementation: An abstract class can provide a complete implementation.
Speed: An abstract class is fast.
Instantiate: An abstract class cannot be instantiated.
Fields: An abstract class can have defined fields and constants Methods: An abstract class can have non-abstract methods.
Basic Difference: Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

Question 14.
What are value types and reference types?
Answer:
A value type holds a data value within its own memory space. Example

int a = 30;

Reference type stores the address of the object where the value is being stored. It is a pointer to another memory location.

string b = “Hello Guru99!l”;

Question 15.
What are Custom Control and User Control?
Answer:
Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to the toolbox. Developers can drag and drop controls to their web forms. Attributes can, at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll to the bin directory of the web application and then add references and can use them.

User Controls are very much similar to ASP include files, and are easy to create. User controls can’t be placed in the toolbox and dragged – dropped from it. They have their design and code behind them. The file extension for user controls is ascx.

Question 16.
What are sealed classes in C#?
Answer:
We create sealed classes when we want to restrict the class to be inherited. The sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as a base class, then a compile-time error occurs.

Question 17.
What is method overloading?
Answer:
Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoked.

Question 18.
What is an Array? Give the syntax for a single and multi-dimensional array?
Answer:
An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

For Example:

double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single-dimensional array is a linear array where the variables are stored in a single row. The above example is a single-dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example. int[,] numbers = new int[3,2] {{1,2} ,{2,3},{3,4}};

Question 19.
Name some properties of Array.
Answer:

Properties of an Array include:

  • Length – Gets the total number of elements in an array.
  • IsFixedSize – Tells whether the array is fixed in size or not.
  • IsReadOnly – Tells whether the array is read-only or not.

Question 20.
What is an Array Class?
Answer:
An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace System.

Question 21.
What is the difference between Array and Arraylist?
Answer:
In an array, we can have items of the same type only. The size of the array is fixed when compared. An ArrayList is similar to an array, but it doesn’t have a fixed size.

Question 22.
What are Jagged Arrays?
Answer:
The Array which has elements of type array is called a jagged array. The elements can be of different dimensions and sizes. We can also call a jagged Array an Array of arrays.

Question 23.
Can a private virtual method be overridden?
Answer:
No, because they are not accessible outside the class.

Question 24.
Describe the accessibility modifier “protected internal”.
Answer:
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.

Question 25.
What are the differences between System. String and System.Text.StringBuilder classes?
Answer:
System. The string is immutable. When we modify the value of a string variable, then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string where a variety of operations can be performed without allocating separate memory locations for the modified string.

Question 26.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Answer:
Using Clone() method, we create a new array object containing all the elements in the original Array and using the CopyToQ method. All the elements of the existing array copy into another existing array. Both methods perform a shallow copy.

Question 27.
How can we sort the elements of the Array in descending order?
Answer:
Using Sort( ) methods followed by reverse( )  method.

Question 28.
Write down the C# syntax to catch an exception ‘
Answer:
To catch an exception, we use try-catch blocks. Catch block can have a parameter of system. Exception type.

Eg:
try {
GetAllData( );
}
catch (Exception ex) {
}

In the above example, we can omit the parameter from the catch statement.

Question 29.
What is the difference between Finalize!) and Dispose!) methods?
Answer:
Dispose( ) is called when we want an object to release any unmanaged resources with them. On the other hand, Finalize!) is used for the same purpose, but it doesn’t assure the garbage collection of an object.

Dispose

It is used to free unmanaged resources at any time.
It is called by user code and the class which is implementing dispose method must have to implement an IDisposable interface.
It is implemented by implementing the IDisposable interface Dispose ( ) method.
There are no performance costs associated with Dispose method.

Finalize

It can be used to free unmanaged resources held by an object before that object is destroyed.
It is called by Garbage Collector and cannot be called by user code.
It is implemented with the help of Destructors
There are performance costs associated with Finalize method since it doesn’t clean the memory immediately and is called by GC automatically.

Question 30.
What are circular references?
Answer:
A circular reference is a situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

Question 31.
What are generics in C#.NET?
Answer:
Generics are used to make reusable code classes to decrease code redundancy, increase type safety, and performance. Using generics, we can create collection classes. To create a generic collection, System.Collections.The generic namespace should be used instead of classes such as ArrayList in the System. Collections namespace. Generics promotes the usage of parameterized types.

Question 32.
What is an object pool in .NET?
Answer:
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, the total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

Question 33.
List down the commonly used types of exceptions in .net
Answer:
ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException, IndexOutOfRangeException ,lnvalidCastException JnvalidOperationException, lOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.

Question 34. What are Custom Exceptions?
Answer:
Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them and are used as defined exceptions.

Question 35.
What is a Delegate? Explain.
Answer:
A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System. Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created of the delegate using the new keyword.
AddNumbers aril = new AddNumbers(number);
The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

1 public delegate int myDel(int number);
2 public class Program
3 {
4 public int AddNumbers(int a)
5{ 
6 int Sum = a + 10;
7 return Sum;
8}
9 public void Start( )
10 {
11 myDel DelgateExample = AddNumbers;
12}
13}

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers( ).

If there is another method called Start( ) that creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.

Question 36.
What are Events?
Answer:
Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress, and so on.

Programmatically, a class that raises an event is called a publisher and a class that responds/receives the event is called a subscriber. An event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

Public delegate void PrintNumbers( );

Event PrintNumbers myEvent;

Question 37.
How to use Delegates with Events?
Answer:
Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

Let us see an example:

Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from the patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and the other two classes should receive the event.

1 namespace ConsoleApp2
2{
3 public class Patient
4{
5 public delegate void deathlnfo( );//Declaring a Delegate//
public event deathlnfo deathDate;//Declaring the
6
event//
7 public void Death( )
8{
9 deathDate();
10}
11} 
12 public class Insurance
13 {
14 Patient myPat = new Patient();
15 void GetDeathDetails( )
16 {
17 //----------Do Something with the deathDate event----------//
18}
19 void Main( )
21 //--------Subscribe the function GetDeathDetails----------//
22 myPat.deathDate += GetDeathDetails;
23}
24}
25 public class Bank
26 {
27 Patient myPat = new Patient( );
28 void GetPatlnfo ( )
29 {
30 //--------Do Something with the deathDate event--------//
31}
32 void Main( )
33 {
34 //--------Subscribe the function GetPatlnfo----------//
35 myPat.deathDate += GetPatlnfo;
36}
37}
38}

Question 38.
What are the different types of Delegates?
Answer:
The Different Types of Delegates are:

Single Delegate – A delegate which can call a single method.
Multicast Delegate – A delegate which can call multiple methods. + and – operators are used to subscribing and unsubscribing respectively.
Generic Delegate – It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs, and Predicate.

  • Action- In the above example of delegates and events, we can replace the definition of delegate and event using the Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result
Public delegate void deathlnfo( );

Public event deathlnfo deathDate;

//Replacing with Action//

Public event Action deathDate;

Action implicitly refers to a delegate.
  • Func- A Func delegate defines a method that can be called on arguments and returns a result.
    Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
  • Predicate – Defines a method that can be called on arguments and always returns the bool.
    Predicate<string> myDel is same as delegate bool myDelfstring s);

Question 39.
What’s a multicast delegate?
Answer:
A delegate having multiple handlers assigned to it is called a multicast delegate. Each handler is assigned to a method. In other words
A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using the + and += operators.

Consider the Example from previous delegate question

There are two subscribers for death event, GetPatlnfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.

Question 40.
Explain Publishers and Subscribers in Events.
Answer:
A Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but an Event as discussed in the above questions.

From the Example in Question 32, Class Patient is the Publisher class. It is generating an Event death event, which the other classes receive.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Question 32, Class Insurance and Bank are Subscribers. They are interested in event death event of type void.

Question 41.
How do you inherit a class into another class in C#?
Answer:
Colon is used as an inheritance operator in C#. Just place a colon and then the class name, public class DerivedClass: BaseClass

Question 42.
What is the base class in .net from which all the classes are derived from?
Answer:
System.Object

Question 43.
What is the difference between method overriding and method overloading?
Answer:
In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.

Question 44.
What are the different ways a method can be overloaded?
Answer:
Methods can be overloaded using different data types for a parameter, different order of parameters, and different numbers of parameters.

Question 45.
Why can’t you specify the accessibility modifier for methods inside the interface?
Answer:
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.

Question 46.
How can we set the class to be inherited, but prevent the method from being over-ridden?
Answer:
Declare the class as public and make the method sealed to prevent it from being overridden.

Question 47.
What happens if the inherited interfaces have conflicting method names?
Answer:
The implement is up to you as the method is inside your own class. There might be a problem when the methods from different interfaces expect different data, but as far as the compiler cares you’re okay.

Question 48.
What is the difference between a Struct and a Class?
Answer:
Structs are value-type variables, and classes are reference types. Structs stored on the Stack cause additional overhead but faster retrieval. Structs cannot be inherited.

Class

Supports Inheritance
Class is Pass by reference (reference type)
Members are private by default
Good for larger complex objects
Can use waste collector for memory management

Struct

Does not support Inheritance
Struct is Pass by Copy (Value type)
Members are public by default
Good for Small isolated models
Cannot use Garbage collector and hence no Memory management

Question 49.
How to use nullable types in .Net?
Answer:
Value types can take either their normal values or a null value. Such types are called nullable types.

Int? somelD = null;
If(somelD.HasVAIue)
{
}

Question 50.
How we can create an array with non-default values?
Answer:
We can create an array with non-default values using Enumerable. Repeat.

Question 51.
What is the difference between “is” and “as” operators in c#?
Answer:
“is” operator is used to checking the compatibility of an object with a given type, and it returns the result as Boolean.
“as” operator is used for casting an object to a type or a class.

Question 52.
What are indexers in C# .NET?
Answer:
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as an array.
Eg:
public int this[int index] // Indexer declaration

Question 53.
What is the difference between the “throw” and “throw ex” in .NET?
Answer:
The “Throw” statement preserves the original error stack whereas “throw ex” has the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

Question 54.
What are C# attributes and their significance?
Answer:
C# provides developers a way to define declarative tags on certain entities, eg. Class, method, etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.

Question 55.
How to implement a singleton design pattern in C#?
Answer:
In a singleton pattern, a class can only have one instance and provides an access point to it globally.

Eg:

Public sealed class Singleton

{

Private static readonly Singleton Jnstance = new Singleton();

}

Question 56.
What is the difference between direct cast and type?
Answer:
DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the type.

Question 57.
What is Managed and Unmanaged code?
Answer:
Ans: Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the
.Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by the application runtime of any other framework apart from .Net. The application runtime will take care of memory, security, and other performance operations.

Question 58.
Is C# code is managed or unmanaged code?
Answer:
C# is managed code because Common language runtime can compile C# code to Intermediate language.

Question 59.
What is a Console application?
Answer:
A console application is an application that can be run in the command prompt in Windows. For any beginner on .Net, building a console application is ideally the first step, to begin with.

Question 60.
Give an example of removing an element from the queue
Answer:
The dequeue method is used to remove an element from the queue,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
class Program
{
static void Main(string[ ] args)
{
Queue qt = new Queue( );
qt.Enqueue(1);
qt.Enqueue(2);
qt.Enqueue(3);

foreach (Object obj in qt)
{
Console.WriteLine(obj);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("The number of elements in the Queue " + qt.Count);
Console.WriteLine("Does the Queue contain " + qt.Contains(3));
Console.ReadKey( );
}
}
}

Question 61.
What are the fundamental OOP concepts?
Answer:
The four fundamental concepts of Object-Oriented Programming are:
• Encapsulation – The Internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
• Abstraction – It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
• Inheritance – It is the ability to create new classes from another class. It is done by accessing, modifying, and extending the behavior of objects in the parent class.
• Polymorphism – The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

Question 62.
What are the different types of classes in C#?
Answer:
The different types of classes in C# are:

• Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.

• Sealed class – It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.

• Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.

• Static class – It is a class that does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

Question 63.
Explain Code compilation in C#.
Answer:
There are four steps in code compilation which include:

  • Compiling the source code into Managed code by C# compiler.
  • Combining the newly created code into assemblies.
  • Loading the Common Language Runtime(CLR).
  • Executing the assembly by CLR.

Question 64.
What is the difference between the Virtual method and the Abstract method?
Answer:
A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

Question 65.
Explain Namespaces in C#.
Answer:
They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own namespace and use one namespace in another, which are called Nested Namespaces.
They are denoted by the keyword “namespace”.

Question 66.
Explain Abstraction.
Answer:
Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides unnecessary information.

Let us take an example of a Car:

A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn’t have to know is an Internal engine, Exhaust system.

So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using tire private keyword.

Question 67.
Explain Polymorphism?
Answer:
Programmatically, Polymorphism means the same method but different implementations. It is of 2 types, Compile-time and Runtime.

Compile-time polymorphism is achieved by operator overloading.

Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.

For Example. If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

Question 68.
What are C# I/O Classes? What are the commonly used I/O Classes?
Answer:
C# has System.10 namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.

Some commonly used I/O classes are:

  • File – Helps in manipulating a file.
  • StreamWriter – Used for writing characters to a stream.
  • StreamReader – Used for reading characters to a stream.
  • StringWriter – Used for reading a string buffer.
  • StringReader – Used for writing a string buffer.
  • Path – Used for performing operations related to the path information.

Question 69.
What is the StreamReader/StreamWriter class?
Answer:
StreamReader and StreamWriter are classes of namespace System.10. They are used when we want to read or write charact90, Reader-based data, respectively.

Some of the members of StreamReader are: Close( ), Read( ), Readline( ).

Members of StreamWriter are: Close( ), Write( ), Writeline( ).

1 Class Programl
2{
3 using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
4{
5 //——–code to read———//
6}
7 using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
8{
9 //———Code to write——-//
10}
11}

Question 70.
What is a Destructor in C#?
Answer:
A Destructor is used to clean up the memory and free tire resources. But in C# this is done by the garbage collector on its own. System.GC.Collect( ) is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.
For Example:

~Car( )

{

Console.writeline("....");

}

Question 71.
What are Boxing and Unboxing?
Answer:
Converting a value type to reference type is called Boxing.

For Example:

int Valuel -= 10;
//——Boxing——–//
object boxedValue = Valuel;

Explicit conversion of the same reference type (created by boxing) back to value type is called Unboxing.

For Example:

//——-UnBoxing——–//
int UnBoxing = int (boxed value);

Question 72.
What is the difference between Continue and Break Statement?
Answer:
Break statement breaks the loop. It makes the control of the program exit the loop. Continue statement makes the control of the program exit only the current iteration. It does not break the loop.

Question 73.
What is the difference between the final and finalize blocks?
Answer:
finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.

finalize method is called just before garbage collection. It is used to perform clean-up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.

Question 74.
What is a String? What are the properties of a String Class?
Answer:
A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;

A string class in C# represents a string.

The properties of the String class are Chars and Length.
Chars get the Char object in the current String.
Length gets the number of objects in the current String.

Question 75.
What is an Escape Sequence? Name some String escape sequences in C#.
Answer:
An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered a single character.

String escape sequences are as follows:

\n – Newline character
\b- Backspace
\\- Backslash
\’ – Single quote
\” – Double Quote

Question 76.
What are Regular expressions? Search a string using regular expressions?
Answer:
Ans: Regular expression is a template to match a set of input. The pattern can consist of operators, constructs, or character literals. Regex is used for string parsing and replacing the character string.

For Example:

* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab, and so on.

Searching a string using Regex
1 static void Main(string[ ] args)
2{
3 string}] languages = {"C#", "Python", "Java" };
4 foreach(string s in languages)
5{
6 if(System.Text.RegularExpressions.Regex.lsMatch(s,"Python"))
7{
8 Console.WriteLine("Match found");
9 }
10}
11}

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

Question 77.
What are the basic String Operations? Explain.
Answer:
Some of the basic string operations are:

• Concatenate –Two strings can be concatenated either by using a System.String.Concat or by using + operator.
• Modify – Replace(a,b) is used to replace a string with another string. Trim( ) is used to trim the string at the end or at the beginning.
• Compare – System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
• Search – start with, EndsWith methods are used to search a particular string.

Question 78.
What is Parsing? How to Parse a Date Time String?
Answer:
Parsing is converting a string into another data type.

For Example:

string text = “500”; int num = int.Parse(text);
500 is an integer. So, Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

Question 79.
What are Synchronous and Asynchronous operations?
Answer:
Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.
The asynchronous call waits for the method to complete before continuing with the program flow. Synchronous programming badly affects the Ul operations, when the user tries to perform time-consuming operations since only one thread will be used.
In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

Question 80.
What is Reflection in C#?
Answer:
Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.

The namespace System. Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, for example, to view the properties of a button in a windows form.
The Memberlnfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get the type of a class, we can simply use
Type my type = myClass.GetType( );
Once we have a type of class, the other information of the class can be easily accessed.
System.Reflection.Memberlnfo Info = mytype.GetMethod(“AddNumbers”);
Above statement tries to find a method with name AddNumbers in the class myClass.

Question 81.
Explain Get and Set Accessor properties?
Answer:
Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.
Get Property is used to return the value of a property Set Property accessor is used to set the value.

Question 82.
What is a Thread? What is Multithreading?
Answer:
A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System. Threading is the namespace that needs to be included to create threads and use its members.

Threads are created by extending the Thread class. Start( ) method is used to begin thread execution.

//CallThread is the target method//

ThreadStart methodThread = newThreadStart(CallThread);

Thread childThread = new Thread(methodThread);

childThread.Start( );

C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.

There are several thread methods that are used to handle the multi-threaded operations:

Start, Sleep, Abort, Suspend, Resume and Join.

Most of these methods are self-explanatory.

Question 83.
Name some properties of Thread Class.
Answer:
Few Properties of thread class are:

  • IsAlive-contains value True when a thread is Active.
  • Wame – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • background – gets or sets a value that indicates whether a thread should be a background process or foreground.
  • ThreadState- describes the thread state.

Question 84.
What are the different states of a Thread?
Answer:
Different states of a thread are:

  • Unstarted – Thread is created.
  • Running- Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – The thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

Question 85.
What are Async and Await?
Answer:
Async and Await keywords are used to create asynchronous methods in C.
Asynchronous programming means that the process runs independently of main or other processes.

  • Async keyword is used for the method declaration.
  • The count is of a task of type int which calls the method CalculateCount( ).
  • Calculatecount( ) starts execution and calculates something.
  • Independent work is done on my thread and then await count statement is reached.
  • If the Calculatecount is not finished, my method will return to its calling method, thus the main thread doesn’t get blocked.
  • If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step will continue in the same thread. However, it is not the situation in the above case where a Delay of 1 second is involved.

Question 86.
What is a Deadlock?
Answer:
A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a Shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

Question 87.
Explain lock, Monitors, and Mutex Objects in Threading.
Answer:
Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

A Mutex is also like a lock but it can work across multiple processes at a time. WaitOne( ) is used to lock and ReleaseMutex( ) is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

Monitor.Enter and Monitor. Exit implements lock internally, a lock is a shortcut for Monitors. lock(objA) internally calls.

Monitor. Enter(ObjA); try
{ 
}
Finally {Monitor.Exit(ObjA));}

Question 88.
What is a Race Condition?
Answer:
A Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.
If we have two threads, T1 and T2, and they are trying to access a shared resource called X., And if both the threads try to write a value to X, the last value written to X will be saved.

Question 89.
What is Thread Pooling?
Answer:
A Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.

System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.

System.Threading.ThreadPool.QueuellserWorkltem(new
System.Threading.WaitCallback(SomeTask));

The above line queues a task. SomeTask methods should have a parameter of type Object.

Question 90.
What is Serialization?
Answer:
When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

Another Explanation for this

Serialization is the process of converting a code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage device. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the c# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

Question 91.
What are the types of Serialization?
Answer:
The different types of Serialization are XML serialization, SOAP, and Binary.

• XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.

• SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.

• Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

Question 92.
What is an XSD file?
Answer:
An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

 

OOPS and Core Java Interview Questions in Java

We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on OOPS and Core Java

Question 1.
Discuss the significance of the Java language.
Answer:
Java is the preeminent language of the Internet. Apart from this, many of its features are influencing upcoming languages such as C#. Java not only opened the door to immense possibilities on the Internet but is inherently suitable for administrative data processing (via database processing), for development using client/server architectures as well as for something it was tailor-made: industrial and loaded data processing.

Without any doubt, we can say that Java shall remain a popular programming language for many future years to come.

Question 2.
Elaborate briefly upon the evolution of Java.
Answer:
A research team at Sun Microsystems was working on the development of home automation applications that could be integrated into cellular telephones and real-time portable systems all of which were developed using C++. This type of development imposed certain restrictions due to the different hardware architectures, interconnection problems between different machines, etc. C++ was not particularly suitable for this kind of development as it is greedy on memory, lacks portability across processes, and pointer management risks the deletion of data vital to the operation of the application.

Given such problems, one of the team members, namely James Gosling endeavored to write a new programming language. Given its application domain, this language needed to be object-oriented, high performance-oriented, fast, and such to ensure portability between different types of hardware. At first, it was called C++–, then Oak, and finally Java – a slang term for “coffee” – due to the amount of coffee consumed by the developers.

Question 3.
Compare in brief C/C++, C#, and Java.
Answer:
Java derives its syntax from C. Many of the object-oriented features of Java were strongly influenced by C++. But, it would be improper to consider Java as the “Internet version of C++”. C# and Java are similar in the sense that they both share the same C++ syntax, support distributed programming, and both make use of the same object model. But, in spite of this, there are stark differences between the two.

We have already stated that Java is closely related to both C and C++, deriving its syntax from C and the object-oriented features from C++. Now, we shall see in what ways it differs from them in terms of programming.

Differences between Java & C:

  • Java does not have the C keywords: size, typedef, auto, extern, register, signed, unsigned.
  • Java adds new operators such as instanceof and >>> (unsigned right shift).
  • Java adds labeled break and continues statements.
  • Java does not support the data types struct and union.
  • Java does not have an explicit pointer type.
  • Java does not have a preprocessor and thus, does not support any preprocessor directive such as Refine, #include, #ifdef, etc.

Differences between Java & C++:

  • Java does not support operator overloading.
  • Java does not allow default arguments.
  • Java does not support multiple inheritances.
  • Although Java supports constructors, it does not have destructors. Instead, it has a finalize( ) function.
  • Java does not allow the goto.
  • Java does not have the delete operator.
  • Java does not support global variables/functions as all the code in a Java program is encapsulated within one or more classes.
  • The << and >> in Java are not overloaded for I/O operations.
  • In Java, objects are passed by reference only. In C++, they could be passed by reference as well as by value.
  • Java adds multithreading, packages, interfaces, a third comment type: the documentation comment that begins with /** and ends with */, and a built-in string type called String.
  • Java does not have C++ type libraries but has its own set of API (Application Program Interface) classes.
  • While both Java and C++ support a boolean data type, their implementation is different.
  • In C++, a nonzero value is true while a zero value is false. But, in Java, true and false are treated as predefined literals.
  • In a C++ class, the access operators apply to a group of statements while in Java, they apply only to the declarations they immediately precede.
  • Both Java and C++ support exception handling. But, in C++, there is no particular requirement that a thrown exception be necessarily caught as is the case in Java.

Question 4.
Elaborate on the main features of Java.
Answer:
Some of the main features of Java include the following:-

  • Simple and secure
  • Portable and architecture-neutral
  • Object-oriented
  • Robust and multithreaded
  • Interpreted and high performance
  • Distributed and dynamic

Question 5.
Name and enumerate the three Object-Oriented Programming (OOP) principles.
Answer:
The three object-oriented programmings (OOP) principles are:-

  • Encapsulation
  • Inheritance
  • Polymorphism

These three principles work together in unison.

Question 6.
Distinguish between “call-by-value” and “call-by-reference”.
Answer:
There are, in general, two ways that a computer language can pass an argument to a subroutine. The first way is referred to as “call-by-value” while the second is known as “call-by-reference”. In “call-by-value”, the method copies the value of an argument into the formal parameter of the subroutine, and whence, changes made to the parameter of the subroutine have no effect on the argument. In contrast to this, a reference to an argument, and, not the value of the argument is passed to the parameter in the “call-by-reference” approach. Inside the subroutine, this reference is then used to access the actual argument specified in the call so that changes made to the parameter will affect the argument used to call the subroutine.

In Java, when a simple type is passed to a method, it is done through “call-by-value” whereas objects are passed through “call-by-reference”.

Question 7.
What is recursion? Does Java support recursion?
Answer:
Recursion is the process of defining something in terms of itself. Java does support recursion as it allows a method to call itself. Such a method is said to be recursive. A classic case of recursion is computing the factorial of a number.

Question 8.
How can you determine the size of an array?
Answer:
The size of an array, that is to say, the number of elements it can hold is found in its length instance variable.

Question 9.
How are command-line arguments passed in Java?
Answer:
In Java, all command-line arguments are passed as strings only. If you wish to pass numeric values, they must be converted to their internal forms manually.

Question 10.
What is the difference between the prefix increment ++x and the postfix increment x++?
Answer:
The statement:-
y = y + x++;
adds the current values of x and y and assigns this result back to y. The value of x is only incremented after the value of y has been thus obtained.
On the other hand, the statement:-
y = y + ++x;
obtains the value of x, increments x, then adds that value to the current value of y, and this result is assigned to y.

You can see for yourself (by assigning some initial values to x and y) that simply changing ++x to x++ changes the results quite substantially when both of the above statements are run over a loop.

Question 11.
What is the use of short-circuit logical operators | | OR and && AND?
Answer:
Contrary to the normal counterparts | and &, the short. circuit operators | | and && evaluate the second operand only when necessary. That is to say, the result of the OR operation will always be true if the first operand is true irrespective of the second operand. Similarly, the result of the AND operation will always be false if the first operand is false irrespective of the second operand. In both these cases, | | and && do not evaluate the second operand unlike their normal counterparts I and &, which evaluate both the operands in all situations.

Question 12.
Can you name an operator in Java that takes three operands?
Answer:
The ternary operator with the most general form:-
exp1? exp2: exp3;

(if exp1 is true, exp2 becomes the value of the whole expression else exp3 becomes the value of the whole expression)

Question 13.
Can you create a ‘for’ loop without any conditional expressions? What does it amount to?
Answer:
Leaving the conditional expressions in a ‘for’ loop makes it an infinite loop that will run forever:-
for ( ; ; ) / / intentional infinite loop
{
……………….
………………
}

Question 14.
Can Objects be passed as parameters just like simple types?
Answer:
Yes! The answer to this query is in the affirmative.

Question 15.
What do the break and continue statements do? Bring out the main point of difference between them.
Answer:
The break statement causes early termination of the loop whereas the continue statement causes an early iteration of the loop.

Question 16.
Explain the use of the keyword new.
Answer:
The keyword new is used to create objects, e.g.
House building = new House ( );
Here, building by itself does not contain the object (House). Rather, it contains a reference to it.
On the other hand, consider:
int i = 100;
Here, i contains the value 100 since i is a variable of type int, which, in turn, is a value type.
Again, consider:
douse building1 = new House ( );
House building2 = new House ( );
building2 = building1;
House building3 = new House ( );
‘building2 = building3;

After the execution of this sequence, building2 refers to the same object (House) as building3. The object (House) referred to by building1 is unchanged.

Question 17.
What are the two uses of the keyword super?
Answer:

  • A subclass can call a constructor defined in its superclass by using the keyword super.
  • The second use of super relates to situations in which member names of a subclass hide members by the same name in the superclass. In such a case, you can refer to the superclass member by using super. member.

Question 18.
Point out the difference between C++ and Java as regards the release of previously allocated memory.
Answer:
In C++, the delete operator is used to free memory that was previously allocated. But, Java uses a different, more trouble-free approach, viz. garbage collection.

Question 19.
What is the purpose of the finalize( ) method in Java?
Answer:
We can define a method in Java that shall be called just prior to the object’s final destruction by the garbage collector. This method is known as the finalize( ) method, which can be used in some highly specialized situations to ensure that the object is destroyed/terminated cleanly.

Question 20.
What do you understand by ‘this’?
Answer:
When a method is called, it is, by itself, passed a reference to the invoking object, i.e. the object on which the method is called. This reference is referred to as ‘this’.

Question 21.
Can you elaborate on the concept of jagged arrays?
Answer:
In general, when we create a two-dimensional array, we are creating what is a rectangular array with the length of each row being the same for the entire array, e.g. a 2 x 3 array implies an array of two rows with three elements in each row. But, Java allows you to create a special two-dimensional array called a jagged array, which is an array of arrays, where the length of each array can differ. In this way, we can have a table where the lengths of the rows differ, e.g.

int jag [ ] [ ] = new int [4] [ ];
jag [0] = new int [10];  / / length of first array is ten
jag [1] = new int [2];   / / length of second array is two
jag [2] = new int [5];  / / length of third array is five
jag [3] = new int [8]; / / length of fourth array is eight

Question 22.
Can you point out the main difference between C/C++ strings and Java strings?
Answer:
In C/C++, strings are simply arrays of characters terminated by the ‘\0’ null character whereas, in Java, the string is a built-in data type. In fact, in Java, strings are objects and thus, reference types.

Question 23.
Can the contents of strings in Java be changed?
Answer:
No, strings in Java are immutable. This might seem to be a drawback but since unused string objects are automatically garbage-collected, you can simply create a new string with the desired changes. (Refer Q. 92 also)

Question 24.
What are Java’s access modifiers?
Answer:
In Java, member access control is achieved through three access modifiers, namely, public, private, and protected. The protected modifier applies only in the case of inheritance. When a member of a class is modified by the public specifier, then that member can be accessed by any code in your program. If a member of a class is specified to be private, it can then only be accessed by other members of its class so that methods in other classes will not be able to access a private member of another class.

Question 25.
Which feature of C/C++ is similar to overridden methods in Java?
Answer:
Overridden methods in Java are similar to virtual functions in C/C++.

Question 26.
Is it possible to have a variable number of arguments in Java?
Answer:
Yes, this is a recently added new feature to Java. It was added by JDK 5. The addition of this feature has enabled formatted output in Java akin to the print( ) family of functions in C.

We might also mention here that it is possible to have a normal parameter along with the variable-length parameter but in such cases, the variable-length parameter must be the last one in the method declaration. Moreover, you cannot have a method with more than one variable-length parameter.

Question 27.
Can you declare a class as both abstract and final?
Answer:
An abstract class is incomplete by itself and relies upon its subclasses to provide a complete implementation. Whence, it is illegal to declare a class as both abstract and final.

Question 28.
When do you declare an element as protected?
Answer:
In Java, if you want to allow an element to be visible outside your current package, but only to classes that subclass your class directly, then you declare that element as protected.

Question 29.
Where does the package statement occur in a Java source file?
Answer:
The package statement must be the first statement in a Java source file.

Question 30.
Where does the import statement occur in a Java source file?
Answer:
The import statement in a Java source file must occur immediately after the package statement, if any, and before any class definitions.

Question 31.
Specify the forms of the Main ( ) method available in Java.
Answer:
The following four versions of Main ( ) are currently available in Java:-

  • public static void main ( )
  • public static int main ( )
  • public static void main (String args[ ])
  • public static int main (String args[ ])

Question 32.
Elucidate the role of the keyword static.
Answer:
In general, a class member has to be accessed through an object of its instance. But, it is possible in Java to create a member that can be used by itself, without any reference to a specific instance. To create such a member, you have to precede its declaration with the keyword static.

Question 33.
Point out any four restrictions on static methods?
Answer:
First, a static method cannot have a ‘this’ reference. Second, a static method cannot refer to super in any way. Third, a static method can directly call only other static methods. Finally, a static method can have access only to static data.

Question 34.
Which feature of Java is akin to multiple inheritances in C++?
Answer:
Interfaces in Java provide most of the functionality associated with multiple inheritances in C++.

Question 35.
Can Java interfaces be inherited?
Answer:
The answer to this query is indeed in the affirmative.

Question 36.
Give a one-line definition of an exception. What do you mean by checked and unchecked exceptions?
Answer:
An exception is a run-time error. Most of the exceptions are directly available from the JVM (such as ArithmeticException, ArraylndexOutOfBoundsException, etc.) and need not be specified in the throws list of any method. All these exceptions are known as unchecked exceptions. Then, there are other exceptions such as IllegalAccessException defined by java. lang, which must be specified in the throws statement in case a method generates them but does not handle them by itself. Such exceptions are called checked exceptions.

Question 37.
Which class is at the top of the exception hierarchy?
Answer:
Throwable.

Question 38.
Which are the two important subclasses of Throwable?
Answer:
Exception and Error.

Question 39.
Can you name the all-important subclass of Exception?
Answer:
RuntimeException.

Question 40.
What is RuntimeException?
Answer:
RuntimeException is a subclass of Exception and includes such run-time programming error conditions such as divide-by-zero and invalid array index.

Question 41.
What does the throws clause do?
Answer:
A throws clause lists all the types of exceptions that a method might throw but does not handle them by itself.

Question 42.
How is java. Is lang related to exceptions?
Answer:
Inside its standard package java.lang, Java defines several exception classes. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java. lang is implicitly imported into all Java programs, most of the exceptions derived from RuntimeException are automatically available and need not be included in the throws list of any method. In terms of Java, these are known as unchecked exceptions since the Java compiler does not check to see if a method handles or throws these exceptions.

Question 43.
Can you create your own custom exceptions in Java?
Answer:
Although Java’s built-in exceptions are capable of handling the most common errors, there will still be occasions when you would like to create your own exception types specific to your applications. This is quite simply done by defining a subclass of Exception, which, in turn, is in fact a subclass of Throwable.

Question 44.
What do you understand by chained exceptions?
Answer:
Java 2, version 1.4 added the feature of chained exceptions to the exception subsystem of Java. This feature allows you to associate one exception with another where the second exception describes the cause of the first exception. For instance, take the case when an ArithmeticException occurred because of an attempt to divide by zero.

But, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set to zero. In such a scenario, the method must certainly throw an Arithmetic Exception but you also might want to let the calling code know that the underlying cause was an I/O error: chained exceptions allow you to do this and any similar situation where layers of exceptions exist, thus forming a chain.

Question 45.
Both the subclass and the superclass can have their own constructors. So, what constructor is responsible for building an object of the subclass – the one in the superclass, or the one in the subclass, or both?
Answer:
The constructor for the superclass constructs the superclass part of the object and the constructor for the subclass builds the subclass portion of the object.

Question 46.
How does a subclass call a constructor defined in its superclass?
Answer:
A subclass can call a constructor defined in its superclass by using the super keyword in the following manner-
super (Paramjit);
where Paramjit specifies any parameters required by the constructor in the superclass. Note that super must always be the first statement executed inside a subclass’ constructor.

Question 47.
In what order are constructors called in a class hierarchy?
Answer:
In a class hierarchy, constructors are called in their order of derivation, that is, from superclass to subclass.

Question 48.
What do you mean by method overriding?
Answer:
When a method in a subclass has the same name, return type, and signature as that in the superclass, it is said to override the method in the superclass and this phenomenon is referred to as method overriding in Java.

Question 49.
What do you understand by dynamic method dispatch?
Answer:
Dynamic method dispatch is the means by which a call to an overridden method is resolved at run-time rather than at compile time. It is important since Java implements run-time polymorphism this way.

Question 50.
Can you give one good reason for using overridden methods?
Answer:
Overridden methods are another way that Java implements the ‘one interface, multiple methods’ aspect of polymorphism. ’

Question 51.
Can an abstract method have a body? Can an abstract class have concrete methods (other than abstract ones)?
Answer:
While the answer to the first query is in the negative the answer to the second query is in the affirmative.

Question 52.
Can you create an object of an abstract class using new?
Answer:
An abstract class does not specify a complete implementation and whence, there can be no objects of an abstract class. Therefore, attempting to create an object of an abstract class using new will lead to a consequent compile-time error.

Question 53.
What are the three uses of the keyword final?
Answer:

  • You can use final to prevent a class from being inherited by preceding the class declaration with the keyword final.
  • You can use final to prevent further overriding of a method by preceding its declaration with the keyword final.
  • The keyword final can be used to create what is known as final named constants.

Question 54.
What do you mean or understand by type wrappers?
Answer:
In Java, simple types such as int or char are not part of the object hierarchy. They are passed by value to methods and cannot be directly passed by reference. Moreover, there is no way for two methods to refer to the same instance of an int. There will be occasions when you need to create an object representation for one of these simple types, e.g., there are the enumeration classes,

which deal only with objects, and thus, to store a simple type in one of these classes, you must wrap the simple type in a class. To take care of this need, Java provides classes that correspond to each of these simple types. These classes essentially encapsulate or wrap the simple types within a class and whence, they are commonly referred to as type wrappers.

Question 55.
What do you mean by autoboxing and auto-unboxing?
Answer:
Beginning with JDK 5, Java added two important features, namely, autoboxing and auto-unboxing. Auto-boxing is the process by which a primitive type is automatically encapsulated (“boxed”) into its equivalent type wrapper whenever an object of that type is required. There is thus, no need to construct an object explicitly as such.

Auto-unboxing is the process by means of which the value of a “boxed” object is automatically extracted (“unboxed”) from a type wrapper when its value is required. There is thus, no need to explicitly invoke a method such as intValue( ) or doubleValue( ), etc.

Question 56.
What is the Object class in Java?
Answer:
There is one special class, Object, defined by Java, which is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Moreover, since arrays are implemented as classes in Java, a variable of type Object can also refer to an array.

Question 57.
Define an interface in Java.
Answer:
An interface defines a set of methods that will be implemented by a class. An interface, by itself, does not implement any method. In this way, we see that an interface is a purely logical construct that describes functionality without defining any implementation whatsoever.

Question 58.
What is the similarity and difference between interfaces and abstract classes?
Answer:
Interfaces are syntactically similar to abstract classes. But, in an interface, no method can have a body. Thus, an interface does not provide any implementation at all. It tells what is to be done but is completely silent about how it is to be done. Once an interface is specified, any number of classes can implement it. Moreover, one class may implement any number of interfaces.

Question 59.
How will you choose between an interface and an abstract class?
Answer:
When you can fully describe the concept in terms of ‘what it does’ without any need to specify ‘how it does it’, you should use an interface. However, if you need to include at least some implementation details, you should use an abstract class to represent your concept.

Question 60.
What is an exception handler?
Answer:
As we have already stated in the answer to Q. 36, an exception is an error which occurs at run-time. Exception handling streamlines error handling by allowing the program to specify a block of code, called an exception handler, which is executed automatically in case of an error. Exception handler eliminates the need to manually check the success / failure of each specific operation or method call. In case an error occurs, it is processed / handled by the exception handler gracefully.

Question 61.
Can you elaborate on the consequences of an uncaught exception?
Answer:
In general, if your program does not catch an exception, it will be caught by the run-time system, which, in turn, will report an error and terminate the program abnormally / ungracefully.

Question 62.
What is the major benefit of exception handling?
Answer:
One of the major benefits of exception handling is that it enables your program to respond to an error and then continue running, that is, handle the error gracefully, and then continue further.

Question 63.
Can you have a try block followed by a finally block with no catch clauses?
Answer:
Syntactically, when a finally block follows a try block, no catch clauses are technically required. In such a case, the finally block gets executed after exit from the try block, but no exceptions are handled in such a case / event.

Question 64.
Explain the concept of an inner class.
Answer:
Classes present inside another class are termed inner classes. A point to note is that inner classes increase the complexity of code and must be used only if absolutely necessary. In this context, it would be worthwhile to mention that inner classes are used to implement adapters in an AWT program.

class X
      {
           
        int x;
        public void do( )
        {     }
        // Inner class
        Class Y
        {
      
            public void done( )
            {
                 /* can access the instance variables of the outer class */
                 x = 100;
            }
        }
      }

Question 65.
Explain the concept of anonymous classes.
Answer:
An anonymous class is an inner class without a name. An anonymous class, in general, makes the code difficult to read and understand. Its use must be limited to very small classes (with a method or two) and whose use is well understood such as in the case of the AWT event¬handling adapter classes.

Question 66.
What types of variables are allowed in an interface?
Answer:
All the variables in an interface must be public, static, and final, that is to say, constants.

Question 67.
Are there any restrictions imposed on interfaces vis-a-vis classes?
Answer:
An interface is akin to a class with a few restrictions including the following:-

  1. As mentioned in the previous problem, all variables in an interface must be public, static, and final, i.e. constants.
  2. All methods in an interface are implicitly declared public and abstract.

Another point to note is that a class can inherit multiple interfaces.

Question 68.
What is a stream in Java?
Answer:
Java programs perform Input / Output through streams. A stream is an abstraction that produces/consumes information. A stream is liked a physical device by the I/O system. It is useful to note that all streams behave in the same manner irrespective of the physical device they might be linked to.

Question 69.
Compare and contrast byte streams with character streams.
Answer:
The following four are the major points of difference between Byte Streams and Character Streams:-

  1. java.io.InputStream and java.io.OutputStream are the base byte streams while java.io.Reader and java.io. Writer are the base character streams.
  2. Byte streams are 8 bit streams while character streams are 16 bit Unicode streams.
  3. In byte streams, method names end with the suffix InputStream or OutputStream while in case of character streams, method names end with the suffix Reader or Writer.
  4. Since character streams are Unicode, they are internationalized and more efficient than byte streams.

Question 70.
Elucidate the benefits of the streams.
Answer:
The streaming interface to I/O in Java provides a clean abstraction for a complex and often cumbersome task. The composition of the filtered stream classes allows you to dynamically build the custom streaming interface to suit your data transfer requirements. Java programs written to adhere to the abstract, high-level InputStream, OutputStream, Reader, and Writer classes will function properly even in the future when new and improved concrete stream classes are invented.

This model works very well even when we switch from a file system-based set of streams to the network and socket streams. Moreover, serialization of objects is expected to play an increasingly important role in the future Java programming. In fact, Java’s serialization I/O classes provide a portable solution to this sometimes tricky task/proposition.

Question 71.
Name the predefined I/O streams in Java.
Answer:
System.in, System.out, and System.err are the three predefined I/O streams in Java. By default, System.in refers to the keyboard while System.out and System.err refer to the console.

Question 72.
Name the two byte streams and the two character streams related to File I/O in Java, respectively.
Answer:
File Input St ream & FileOutputStream are the two byte streams and FIleReader & FileWriter are the two character streams, respectively, related to File I/O in Java.

Question 73.
How is binary data read and written?
Answer:
Binary data is read and written using the DatalnputStream and DataOutputStream streams, respectively.

Question 74.
Name the two classes at the top of the byte stream classes.
Answer:
InputStream and OutputStream.

Question 75.
Name the two classes at the top of the character stream classes.
Answer:
Reader and Writer.

Question 76.
Does Java have a generalized console input formatter akin to the standard C function scanf() or the C++ input operators?
Answer:
Yes, added by JDK 5 recently Java has the Scanner class which reads formatted input and converts it into its binary form. The Scanner class is the complement of the Formatter class of Java which has made formatted output in Java very easy akin to the printfO style of functions in C/C++.

Question 77.
Elucidate the New I/O system.
Answer:
Java 2, version 1.4 added a new way to handle I/O operations. Called the new I/O APIs, it supports a channel-based approach to I/O operations. The new I/O (NIO) system is built on two foundational items, viz. buffers and channels. A buffer holds data. A channel represents an open connection to an 1/O device, such as a file or a socket. In general, to use the NIO system, you obtain a channel to an I/O device and a buffer to hold data. You then operate on the buffer, inputting / outputting data as needed. We must, at this stage, sound a caveat as to whether NIO is the future of 1/O handling? The channel/buffer based NIO approach is currently designed to supplement, and not supplant the traditional and standard stream-based I/O mechanisms.

Question 78.
What types of comments are supported by Java? Does it support documentation comments?
Answer:
Java supports three types of comments – the first two are // and /* */• The third type is called a documentation comment. A documentation comment begins with /** and ends with */. Using such documentation comments, you can embed information about your program into the program itself; and, later on, you can use the javadoc utility program to extract this information and put it into an HTML file.

Question 79.
Define a package.
Answer:
A package is a container for classes that is used to keep the class name space compartmentalized.

Question 80.
Can you create a hierarchy of packages?
Answer:
You can indeed create a hierarchy of packages. To do so, simply separate each package name from the one above it by using a period. The most general form of a multileveled package statement is as follows:-
package pkg1[.pkg2[.pkg3.[pkg4]]];

Note that a package hierarchy must be reflected in the file system of your Java development system.

Question 81.
What does the Math class contain?
Answer:
The Math class contains all the floating-point functions that are used for geometry and trigonometry such as sin( ), as well as several general-purpose methods such as sqrt( ).

Question 82.
What do you mean by generics?
Answer:
Generics imply parameterized types. They provide a streamlined and type-safe approach to deal with different data types as also promote reusability of code. Generics were introduced by JDK 5 and are somewhat similar to templates in C++.

Question 83.
How is java.util useful?
Answer:
The java.util package contains one of Java’s most powerful subsystems, viz. collections. In addition to collections, java.util contains a wide assortment of classes and interfaces, which support a broad range of functionality such as generating pseudorandom numbers, manipulating date and time, observing events, manipulating sets of bits, and tokenizing strings. These classes and interfaces are used throughout the core Java packages and are, of course, available for use in the programs you write.

Question 84.
Elucidate the utility of collections.
Answer:
Collections simplify many programs by providing off-the-shelf solutions to several common but at times difficult to develop data structures. For instance, there are built-in collections that support dynamic arrays, linked lists, stacks, queues, and hash tables.

Question 85.
On what principle does a Stack operate?
Answer:
Stack is a First-in, Last-out list. To visualize a stack, imagine a stack of plates on a table. The first plate put down is the last one to be retrieved.

Question 86.
What is the principle behind the Queue?
Answer:
Queue is a First-in, First-out list, i.e. the first item put in a queue is the first item retrieved from it. Queues are common in real life, e.g. lines at a bank or railway reservation center are queues.

Question 87.
What is a Hashtable?
Answer:
Hashtable creates a collection which uses a hash table for ‘storage (the hash table, in turn, stores information using a mechanism known as hashing).

Question 88.
What is the ArrayList class?
Answer:
The ArrayList class supports dynamic arrays, which can grow or shrink as per the user requirements.

Question 89.
Should collections be limited to “large jobs” such as corporate databases, inventory systems, or mailing lists?
Answer:
Collections need not be reserved for only the “large jobs” such as corporate databases, inventory systems, or mailing lists. They are equally effective when applied to smaller jobs, e.g., a TreeMap would be ideal to hold the directory structure of a set of files and a TreeSet would be an excellent choice for storing project-management information.

Question 90.
How can you obtain an Array from an ArrayList?
Answer:
When working with ArrayList, you might want to obtain an actual array, which contains the contents of the list. You can easily accomplish this by calling the toArrayi) method.

Question 91.
Are the == and the equals( ) method the same? If not, point out the difference between the two.
Answer:
It is important to understand that the equals( ) method and the = = operator perform two different operations. While the equals( ) method compares the characters inside a String object, the = = operator compares two object references to see whether they refer to the same instance.

Question 92.
How can you create a string in Java that is mutable?
Answer:
A mutable string in Java can be created by means of the StringBuffer class. In the StringBuffer class, characters can be inserted in the middle or appended to the end of a string.

Question 93.
Can an enumeration be used to control a switch statement?
Answer:
Yes, enumerations can easily be used to control a switch statement. Of course, all of the case statements must use constants from the same enum as that used by the switch expression.

Question 94.
Can you assign floating point values to integers in Java as in C/C++?
ANS.
No! Not at all!! This is due to the fact that Java is a very strongly typed language unlike C/C++.

Question 95.
How will you declare a three-dimensional array of shorts and a string variable called surname in Java? How will you determine the size of an array?
Answer:
A three-dimensional array of shorts can be declared in Java in the following manner:-
short s_arr[ ][ ][ ];
A string variable called surname can be declared as:-
String surname[ ];
In Java, the size of an array can be determined by means of the property called length.

Question 96.
Can variables in the inner scope have the same name as the ones in the outer scope in Java as in C/C++?
Answer:
No! Not at all!! In C/C++, there is no such restriction. However, the designers of Java opined that such “name hiding” could very well lead to programming errors and whence, disallowed it.

Question 97.
Does Java have a foreach loop like C#?
Answer:
JDK5 introduced thefor-each style loop as a simple enhanced version of the ‘for’ loop unlike C# which uses the foreach keyword. The major advantage of this is that no keyword is required and no pre-existing legacy code is broken.
The most general form of for-each style loop is:
for (var_type var_name : coll)
{
statement(s);
}

where, var_type and varjname specify the type and name of the iteration variable and the collection being cycled through is referred to by coll.

Question 98.
What are the two uses of the keyword ‘super’?
Answer:
The Java keyword, super, can be used in two distinct ways. Its first use is to call/ invoke a super class constructor. Its second use lies in accessing a member of the superclass that has been hidden by a member of the subclass having the same name.

A subclass can call a constructor defined in its immediate superclass by using super as given below:
super(argumentjist);

where, argumentJist specifies any arguments needed by the constructor in the superclass. Note that super() must be the first statement executed in the constructor of the subclass always. Also, note that since constructors can be overloaded, super() can be invoked using any form defined by the superclass. The constructor that matches the parameters/arguments shall be the one to get executed.

Now, we introduce you to the second use of super that acts in a manner similar to this except for the fact that it always refers to the superclass of the subclass in which it is used. The most general form of this usage is:

super.member

where, member can either be an instance variable or a method. This form of super applies mostly to cases in which member names of a subclass hide members by the same name in the superclass.

Question 99.
Does Java support formatted output akin to the printfO style function in C/C++? If yes, when did Java begin to have this facility and why it could not provide it earlier?
Answer:
With the release of JDK 5 (Java Development Kit 5), Java added a new capability, viz. the ability to easily create formatted output akin to the printfO style of functions in C/C++. This feature was implemented using the Formatter class of Java.

You might wonder why Java was not able to earlier provide such a facility. The simple reason was that the printfO style formatting requires the use of variable-length arguments (varargs), which Java did not support before JDK 5.

Once varargs became available with the release of JDK 5, it was easy pickings to add a general- purpose formatter. At the roots of Java’s formatted output is the Formatter class, which provides format conversions that let you display numbers, strings, date and time in almost every format as per your requirements very much similar in fashion to the printfO function of C/C++.

The Formatter class works by converting the binary form of data used by a program into formatted text. It stores this text in a buffer from where it can be obtained any time you need. The buffer may be supplied explicitly or you can let the Formatter supply it on its own. Formatter may be constructed in a variety of ways including the following:-

Formatter( )
Formatter(Appendable buf)
Formatter(String file) throws FileNotFoundException
Formatter(File outF) throws FileNotFoundException
Formatter(OutputStream outStrm)

where, buf specifies a buffer for the formatted output, file specifies the name of the file which shall receive the formatted output, outF specifies a reference to an output file that shall receive the output, and outStrm specifies a reference to an output stream which shall receive the output.

After creating the Formatter, you can use the following forma t( ) method to create a formatted string:-

Formatter format( String fmtString, Object… args)

where, fmtString contains either character which is copied as such to the output buffer or format specifiers such as %d for integers, %/for floating-point data and %s for strings.

An integer placed between the % sign and format conversion code acts as the minimum field-width specifier. The default padding is done with spaces. If you want to pad with 0’s, place a 0 before the field-width specifier, e.g., %05d will pad a number of less than five digits with 0’s so that its length is five.

By default, all output is right-justified. You can force output to be left-justified by placing a minus sign directly after the % sign, e.g., %-10.2f left-justifies a floating point number with two decimal places in a 10-character field.

When displaying large numbers, it is often useful to add a comma separator/flag, e.g., ‘ 4337788990.23 is more easily read as 4,337, 788,990.23. Formatter lets you achieve this very easily. Formatter also includes a very useful feature that lets you specify the argument to which a format % specifier applies. In other words, it allows you to use an argument index.

Question 100.
Can you elaborate on the ‘why’ of Java?
Answer:
Java serves both as a programming language as well as a platform. As a programming language, Java is simple, object-oriented, distributed, interpreted, robust, secure, architectnre- neutral, portable, high performance based, multithreaded and dynamic. By definition, a platform is a hardware/software environment in which a program can be run. The majority of present day
platforms are a combination of hardware (the machine) and software (the operating system).

The Java platform is quite different in the sense that it consists only of a software component that can be run on varying hardware. It consists of the Java Virtual Machine (JVM) and the Java Application Programming Interface (JAVAAPI).

Java is simple with syntax similar to that of C and C++ but without their semantic complexity that make them confusing and insecure. Thus, there is no need for pointer management etc. Java is object-oriented unlike C but-likewise C++.

Java is distributed in the sense that network access protocols like TCP/IP, UDP, HTTP, and — FTP are supplied with it that allows for the development of client/server model in order to access
data on a distant/remote machine. Once again, a Java program does not operate in the normal way.

Rather, it is interpreted by the JVM. Java achieves robustness by strict program checking during compilation as well as execution. The Java code is verified both during compilation and run-time by the interpreter making it free from errors and ensuring security.

Java is inherently architecture-neutral as the Java compiler produces Java bytecodes independent of any specific environment. The primary data in Java is primarily of the same size (generally IEEE754) ensuring portability across varying platforms. Although the Java program is interpreted resulting in it being slow to a degree but, still, Java uses JIT (Just In Time), a code interpretation optimizing technique resulting in almost the same performance as C++.

Java introduces multithreading, a concept that allows for many things/applications being run simultaneously and increases response time. Finally, in Java, one doesn’t have to edit links (mandatory in C++) resulting in executables having a lower memory size. Thus, Java is dynamic as well!

The Java Virtual Machine (JVM) is the base of the Java platform and is essential for running the Java programs. It is compatible with any type of computer machine. The JVM undertakes the loading of Java bytecodes, classes, memory management, security management and, if necessary, interfacing with native code such as C. The JAVAAPI package contains a collection of prefabricated software components that supply a number of functions like the management of graphical interface etc.

The Java Application Interface is organized as a collection of packages just as libraries in C/ C++. Each package has Java classes that are predefined language objects directly reusable. The Java platform consisting of the JVM and the JAVAAPI is the link between the hardware and the Java program.

To compile Java source code, we need to use the compiler dedicated to our machine. After compilation, the file remains independent of the hardware platform and the operating system. The interpreter rims Java programs.

To run Java applets, the interpreter is incorporated into Java compatible Web browsers such as Hotjava (refer Chapter 2), Netscape Navigator etc. To run independent stand alone Java applications, we need to run the virtual machine (JVM) supplied with the Java development Kit (JDK) or the Java runtime Environment (JRE).

OOPS and Core Java Interview Questions in Java Chapter 1 img 1

As discussed above, a Java program is independent of the operating system/platform on which it is run. This is achieved by means of the Java Virtual Machine (JVM) that converts the original source code into bytecodes (which is platform independent). Finally, the Java interpreter on the concerned operating system converts these bytecodes into machine code which can be run on that particular machine. Figure 1 illustrates all this.

Question 101.
Can you explain the difference between a .class file and an .exe file?
Answer:
There is basically one main point of difference between the two. While a .class file contains bytecodes for the JVM and is thus system independent, an .exe file contains machine language for the microprocessor and is thus system dependent.

Question 102.
What do you understand by an API document? Elucidate.
Answer:
An API document is essentially an .html file having complete details of all the features of a software/product/technology. It is very much handy for the users in using the relevant software/product/technology.

Question 103.
Can you explain the difference between the #include statement of C/C++ and the import statement of Java?
Answer:
The import statement of Java is a much better option than the #include statement of C/C++ since the import statement makes the JVM go to the standard Java library, run the code over there, and finally, substitute the result into the Java program thus avoiding any wastage of memory/processor’s time while the #include directive of C/C++ makes the compiler go to the standard C/C++ library and copy the code from the header files into the C/C++ program leading to a considerable increase in the program size, which, in turn, results in wastage of memory and the processor time.

Question 104.
Suppose, String args [ ] is not written in the main( ) method; will the program still run? Elucidate.
Answer:
Suppose, we write the main( ) method without String args [] as follows:-
public static void main( )
The compiler will not report any error in such a case but the Java Virtual Machine environment, which always looks for the main( ) method with String args [ ] as parameter, will not be able to recognize the main( ) method in such a case and, whence, the program shall not run/ execute.

Question 105.
Is it possible in Java to call the main( ) method of a class from another class? Elucidate.
Answer:
Yes! It is very much possible!! This is achieved by the use of the relevant clas$mme.main( ). Note that at the time of calling main( ), you will have to pass a string type array to it.

Question 106.
Is it possible in Java to compile and run a program without the main( ) method? Elucidate.
Answer:
Yes! It is very much possible!! This is achieved by the use of a static block in the relevant Java program.

Question 107.
Can you explain the difference between the float and double data types of Java?
Answer:
The float data type can store up to seven digits after the decimal point accurately; on the other hand, the double data type can store up to fifteen digits after the decimal point accurately.

Question 108.
Can you explain the difference between the return statement and the System. exit(0) statement of Java?
Answer:
The return statement can be used anywhere in a method to come out of it while System.exit(0) can be used anywhere in a method to come out of the Java program itself.

Question 109.
Can you explain the difference between the System. exit(1) statement and the System.exit(0) statement of Java?
Answer:
The System.exit(1) statement is used to exit the Java program abnormally because of some error encountered during its execution while System.exit(0) is used to exit the Java program normally without any error.

Question 110.
Can you explain the difference between the System.err and System.out?
Answer:
Although both System.out and System.err send messages to the monitor, by default, the difference lies in the fact that System.out displays normal output while System.err displays error messages.

Question 111.
What are the types of memory available in Java; incidentally, on which memory are arrays created in Java?
Answer:
There is no static memory in Java; there is only dynamic memory. As such, everything (objects, variables) as well as arrays are created on dynamic memory only.

Question 112.
Can you consider class as a data type?
Answer:
Yes! Indeed, a class is a user-defined data type.

Question 113.
What, according to you, is String – a class or a data type?
Answer:
String is a class in java.lang package. But as mentioned in the previous question, a class can be taken to be a data type as well. Whence, String can be considered as a data type too.

Question 114.
Can you explain the difference between the String class and the StringBuffer class of Java?
Answer:
There are two points of difference between String and StringBuffer classes of Java:-

  • String class objects are immutable so that their contents are not modifiable; StringBuffer class objects are mutable so that their contents are modifiable.
  • The methods that directly manipulate the contents of objects are available only in the StringBuffer class.

Question 115.
Can you explain the difference between the StringBuffer and StringBuilder classes of Java?
Answer:
StringBuilder is identical to StringBuffer with one important exception, viz. it’s not synchronized, which, in turn, implies that it’s not thread-safe. The main advantage and benefit of StringBuilder is faster performance. But, there is a caveat. In cases where you are using multithreading, you must make use of StringBuffer instead of StringBuilder since only StringBuffer is synchronized.

Question 116.
What do you understand by hash code? How can you determine the hash code of an object?
Answer:
Hash code is a unique identification number assigned to objects by the JVM. It is created based on the basis of the location of the object in memory and is unique for all objects with the sole exception of String objects. The hash code of an object can be determined using the hashCode( ) method of the Object class in java.lang package.

Question 117.
Can a class in Java be declared private?
Answer:
By declaring a class as private, it becomes unavailable to the Java compiler resulting in a compile-time error. However, inner classes can be declared to be private.

Question 118.
What do you understand by factory methods? Elucidate.
Answer:
A method that creates and returns an object to the class to which it belongs is known as a factory method. A single factory method can replace several different constructors in the class by accepting different options from the user while in the process of creating the object.

Question 119.
In what different ways can you create an object in Java?
Answer:
You can create an object in Java in any of the following ways:-

  • By the use of the new operator;
  • By cloning an already available object;
  • By the use of the newInstance( ) method; and,
  • By the use of factory methods.

Question 120.
What is the main point of difference between method overloading and method overriding?
Answer:
Writing two or more methods with the same name but different signatures is referred to as method overloading while writing two or more methods with the same name and the same signatures is referred to as method overriding.

Question 121.
Can you name the super class for all classes inclusive of your classes as well?
Answer:
The Object class.

Question 122.
Can you write an interface without any methods?
Answer:
YES!

Question 123.
Can you name the method used in cloning?
Answer:
The clone( ) method of the Object class.

Question 124.
What is an abstract method/class?
Answer:
An abstract method is simply a method without any body. It is generally used when the same method has to carry out different tasks based upon the object calling it. An abstract class is simply a class with one or more abstract methods.

Question 125.
Can you forcibly implement only the features of your class; if yes, how?
Answer:
This can be easily achieved by using an abstract class or by the use of an interface.

Question 126.
Can one interface be implemented from another?
Answer:
NO! Not at all!!

Question 127.
Do you think you need to write both the following statements:

  1. import java.awt.event.*;
  2. import java. awt. *;

Or, the second one alone is sufficient? Give appropriate reason(s) for your answer.
Answer:
event is a sub-package of java.awt package. However, when a package is imported, its sub-packages are not imported into the program by themselves. Whence, for every package or sub-package, you need to write a separate import statement. Therefore, if you want to import the classes and interfaces of both the java.awt.event and java.awt packages, you should include both the import statements in your program.

Question 128.
What do you understand by CLASSPATH? Elucidate.
Answer:
CLASSPATH is an environment variable which tells the Java compiler as to where to look for the class files to import.

Question 129.
What do you understand by a JAR file?
Answer:
A JAR or Java Archive file, as it is called, is a file containing compressed versions of different .class files, audio files, image files, and directories.

Question 130.
What is the scope of the default access specifier?
Answer:
Default members are available within the same package but not outside it.

Question 131.
Bring out the difference between an exception and an error.
Answer:
An exception is an error that can be handled gracefully but an error means a condition that cannot be handled and the program can do nothing to handle the situation.

Question 132.
Bring out the difference between throw and throws.
Answer:
throw is used to throw an exception explicitly and handle it using a try-catch block while throws is used to throw the exception out of a method without handling it there and then.

Question 133.
Can you name the Wrapper class with only one constructor?
Answer:
Character wrapper class.

Question 134.
Can a primitive data type be stored into a collection?
Answer:
NO! Not at all!! Collections can store only objects.

Question 135.
Bring out the major difference between ArrayList and Vector.
Answer:
ArrayList object is hot synchronized by default while Vector object is synchronized by default.

Question 136.
What do you understand by serialization? Are there any variables which cannot be serialized?
Answer:
Serialization is essentially the process of storing object contents into a file; static and transient variables cannot be serialized.

Question 137.
What do you understand by jenumerations?
Answer:
Enumerations were added to Java with the release of JDK 5. An enumeration is a way of assigning names to integer constants..

To give you a practical example of the need for enumerations, imagine a scenario where you wanted to represent the seasons of the year in a program. You could very well use the integers 0, 1,2, and 3 to represent spring, summer, autumn, and winter respectively. This solution would work but it is not very innovative, e.g., if you used the integer value 0 in the program code, it would not be very obvious that a particular 0 represented spring.

Furthermore, it would also not be a very robust solution to the problem, e.g., if you declare an integer variable called season, there is nothing to prevent you from assigning the variable season any legal integer value other than 0,1, 2, or 3. Enumerations offer a much better solution. You can create an enumeration (sometimes called an enum type), whose values would be limited to a set of symbolic names, e.g. in this particular case, it could be:

enum season!spring, summer, autumn, winter}

The most general form of an enumeration is:

enum enum_name {enumjist} // notice the keyword ‘enum’!

where enum_name is the name of the said enumeration and enumjist is a comma-separated list of identifiers.

Java enumerations are class types. Although an enum is not instantiated using new, it has more or less the same capabilities as other classes. This feature adds to the power of Java enumerations in a big way, e.g., you can give them constructors, add instance variables/methods, and even implement interfaces.

It is important to realize that each enum constant is an object of its enumeration type so that when you define a constructor for an enum, the constructor is invoked when each enum constant is created.

Question 138.
What do you understand by annotations?
Answer:
JDK 5 introduced a new feature into the Java language, viz. annotations (metadata) by means of which you could embed supplemental information into a source file.
In fact, this information is itself called an annotation, which leaves the semantics/actions of a program unchanged but can be used by various tools both during deployment and development, e.g., an annotation can be processed by a source-code generator.
An annotation is created by means of a mechanism based on the interface. To declare an annotation, say, MyAnnotation, we proceed as follows:

// A simple annotation type'
@interface MyAnnotation
{
String s( );
int value( );
}

Take note of the @ preceding the keyword interface. This indicates to the compiler that an annotation is being created. Now, take note of the two members, s( ) and value( ). All annotations

solely consist of method declarations. But, you don’t provide bodies for these methods; Java implements these methods instead. Also, the methods act much like fields as we shall see shortly.

Once an annotation is declared, it can be used to annotate any declaration, which means that any type of declaration can have an annotation associated with it, e.g., classes, methods, fields, parameters, and enum constants may be annotated. In fact, even an annotation may be annotated. In all cases, the annotation comes before the rest of the declaration. When applying an annotation, its members are given values, e.g., here is an example of MyAnnotation being applied to a method:

// Annotate a method
@MyAnnotation(s = "string”, value - 999)
public static void my Method( )
{
// ...............
}

Thus, MyAnnotation has linked with the method my Method( ). Take note of the annotation syntax. The name of the annotation, preceded by a @1, is followed by a parenthesized list of member initializations. Also, take note of the fact that no parentheses follow s or value in this assignment of initial values so that annotation members act like fields in this regard.

Question 139.
What do you understand by a generic type?
Answer:
A generic type is a class/interface which can act on any data type. In other words, it is type-safe.

Question 140.
Bring out the major difference between window and frame.
Answer:
A window is a frame without any borders/title while a frame does have borders/title.

Question 141.
Elucidate the MVC architecture in JFC/swing.
Answer:
MVC or Model-View-Controller, as it is called, is essentially a model used in swing components, wherein, Model is the data of the component, Vieiv is its appearance while Controller is a mediator between the. model and the view.

In other words, MVC is the separation of the model of an object from its view as well as how it is controlled.

Question 142.
Enumerate the various window panes available in the swing.
Answer:
The various window panes available in the swing are enumerated below:-

  • Content pane;
  • Glass pane;
  • Layered pane; and,
  • Root pane.

Question 143.
What do you understand by a layout manager?
Answer:
A layout manager essentially is a class helpful in arranging components (in a specific/ particular way) in a frame/container.

Question 144.
Consider the following Method whose sole purpose is to find out if the argument passed to it is odd:

public static boolean odd(int k)
{
return k % 2 ==1;
}
Does the Method work?

Does the Method work?
Answer:
An odd number is an integer that leaves 1 as the remainder when divided by 2. The expression k % 2 computes this remainder; so, it looks like that this Method ought to work. But, it returns the wrong answer one-quarter of the time. This is so since half of the integer values are negative and when half of these negative integer values are divided by 2, the remainder is -1, not 1.

Question 145.
Can you provide declarations for two variables z and k such that:
z+- k;
is legal while
z = z + k;
is illegal?
Answer:
Consider:
short z = 0;
int k – 1234;
The compound assignment:
z +- k;  // contains a hidden cast
// but compiles without error
ivhile the corresponding simple assignment:
z = z + k; // requires explicit cast
// and won’t compile
// due to possible loss of precision

Question 146.
Can you provide declarations for two variables z and k such that:
z+= k; is illegal
while
z = z + k; is legal?
Answer:
Consider:
Object z = “BE”;
String k = “YOURSELF ALWAYS!”;
The compound assignment:
z += k; // is illegal
// since LHS has an object reference type
// other than String
while the corresponding simple assignment:
z – z + k; I //is legal since RHS is of type String
// and String is an assignment
// compatible with-Ohject

Question 147.
Consider the following Program:

public class Hurrah
{
public static void main(String args [ ])
{
System.out.printlnC'H" + "A");
System.out.printlnCH' + 'A');
}
}

What does the Program print?
Answer:
HA
137

Question 148.
Consider the following Program:

public class Browser
{
public static void main(String args [ ])
}
System.out.printC explore":);
http://www.yahoo.mail;
System.out.printlnC -.maximize");
}
}

What does the program print?
Answer:
explore: :maximize

Question 149.
Consider the following Program:

public class Increase
{
public static void main(String args [ ])
{
int z = 0;
for (int y = 0; y < 100; y++)
z = z++;
System, out.println(z);
}
}

What does the Program print?
Answer:
0

Question 150.
Can you provide a declaration for a variable z such that the loop:
while (z != z + 0)
{ }
becomes an infinite loop (note that you are not allowed to declare z to be of type double or float)?
Answer:
z can be initialized to any value of type String:
String z = “BECOME YOURSELF ALWAYS!”;
The integer value 0 is converted to the string value “0” and appended to z. The resulting string is not equal to the original as computed by the equals() method; so, it can’t be surely identical, as computed by the == operator. Whence, the boolean expression:
(z != z + 0)
evaluates to true always and the loop never terminates.

Question 151.
Consider the following Program:

public class Indecision
{
public static void main(String args [])
}
System.out.println(indecisive( ));
}
static boolean indecisive( )
{
try
{
return false;
}
finally
{
return true;
}
}
}

What does the program print?
Answer:
true

Question 152.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
try
{
System.out.println(" Bye");
System.exit(0);
}
finally
{
System.out.println("Arunesh");
}
}
}

What does the Program print?
Answer:
Bye

Question 153.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
((null) null).Bye( );
}
public static void Bye( )
{
System.out.println("Arunesh");
}
}

What does the Program print?
Answer:
Arunesh

Question 154.
Consider the following Program:

public class World
{
public static void main(String args [ ])
{
System.out.println(Bye.Arunesh.Hello);
}
}
class Bye
{
static class Arunesh
{
static String Hello = "Arunesh";
}
static Z Arunesh = new Aruneshi);
}
class Z
{
String Hello = "Bye";
}

What does the Program print?
Answer:
Bye

Question 155.
Consider the following Program:

class World
{
public static final String ITEM = "10,000";
}
public class Hello extends World
{
public static final String ITEM - "1";
public static void main(String arg[ ])
{
The system, out.println (Hello. ITEM);
}
}

What does the Program print?
Answer:
1

Q. 156
Consider the following code:
for (int y = 0, int z = 0; y < 10; y++) { }
Will the code compile?
Answer:
No! You can declare the data type of at most one variable in the initialization section of the ‘for’ loop. The correct statement is:- for (int y – 0, z = 0; y < 10; y ++) { }

Question 157.
Consider the following Program:

class Hello
{
public static void main(String args[ ])
{
boolean b = 1;
System.out.println(b);
}
}

Will this program compile?
Answer:
No! Boolean variables can only take the values – true, false!!

Question 158.
Consider the following Program:

class Hello
{
public static void mainfString args[ ])
{
System.out.println(args[3]);
}
}

What does the Program print when run with the following command line?
java               Hello         VERY              GOOD           MORNING

  1. Hello
  2. VERY
  3. GOOD
  4. MORNING
  5. exception raised:java.lang.ArrayIndexOutOfBoundsException:3

Answer:
Unlike C/C++, java doesn’t start the parameter count with the program name. It does however start with zero. So, in this case, zero starts with VERY, GOOD would be l, MORNING would be 2 and there is no parameter 3; hence, an exception would be raised, and thus, the correct answer is:-

5. exception raised:javadang.ArrayIndexOutOfBoundsException:3

Question 159.
Which of the following statements is true?

  1. Methods cannot be overridden to be more private.
  2. static methods cannot be overloaded.
  3. Private methods cannot be overloaded.
  4. An overloaded method cannot throw exceptions which are not checked in the super/ base class.

Answer:

  1. Methods cannot be overridden to be more private.

Question 160.
Consider the following Program:

class base { }
class sub1 extends base { }
class sub2 extends base { }
public class cexcp
{
public static void main(String args[ ]>
{
base b = new base( );
sub1 s1 = (sub1) b;
}
}

What zoill happen if this program is compiled and executed?

  1. Compile and run without any error
  2. Compile-time exception is raised
  3. The run-time exception is raised

Answer:
3. Run-time exception is raised.

Question 161.
Consider the following Program:

class base
{
public void a_mthd(int z) { }
}
public class scope extends base
{
public static void main(String args[ ])
{
}
// Method HERE
}

Which of the following methods can be legally inserted in place of the comment //Method HERE?

  1. void a_mthd(int z) throws Exception {  }
  2. void a_mthd(long z) throws Exception { }
  3. void a_mthd(long z){ }
  4. public void a_mthd(int z) throws Exception { }

Answer:
2. void a_mthd(long z) throws Exception { }
3. void a_mthd(long z) { }

Question 162.
Consider the following Program:

public class Hello
{
public static void main(String args[ ])
{
/* Modifier at ZZ */ class InnerHello { }
}
}

What modifiers would be legal at ZZ in this program?

  1. public
  2. private
  3. static
  4. friend

Answer:

  1. public;
  2. private &
  3. static.

Question 163.
You need to create a class that will store unique object elements. You do not need to sort these elements but they must be unique.
What interface might be most suitable to satisfy this need?

  1. List
  2. Set
  3. Map
  4. Vector

Answer:
2. Set

Question 164.
Describe a java source file.
Answer:
A java source file must have “.java” extension. Also, it should have at least one top level public class definition and any number of non-public class definitions. The file name (without the extension) must match the public class name.

Question 165.
What is Bytecode?
Answer:
Every java program is converted into one or more class files. The content of each class file is a set of instructions referred to as Bytecode to be executed by the JVM. Java introduces Bytecode to produce platform independent program/code.

Question 166.
Why does the main method need a static identifier?
Answer:
The main method needs a static identifier since static methods and members do not require an instance of their class to invoke them and main is the first method that is called/’ invoked.

Question 167.
Will the program compile if the main method doesn’t have the static identifier?
Answer:
The program will still compile; but it can’t be executed or run.

Question 168.
Which is the default parent class for a Java class?
Answer:
java.lang.Object. By default, all java classes extend java.lang.Object unless they have their own parent class. Moreover, the package named java.lang is imported (by default) into all java files.

Question 169.
How are java objects passed to a method?
Answer:
Java passes both the primitive types and objects by value. During object passing, the object’s reference is copied.

Question 170.
What are native methods?
Answer:
Native methods are methods implemented in some other programming language such as C/C++. The Java Native Interface (JNI) is the API to invoke these native methods from a class in java.

Question 171.
What is the order of declaring class, package and import statements within a java.
file?
Answer:
The order should be the following:-

  1. package
  2. import statements
  3. class definition

Question 172.
Can a variable be an unsigned integer?
Answer:
No! Not at all!!
In java, all data types are signed numeric numbers.

Question 173.
Can a private method be static?
Answer:
YES!
A private method can indeed be static.

Question 174.
Enumerate and elucidate the various bit wise operators.
Answer:
The various bit wise operators are:-

  1.  ∼a           complement
  2.  a&b         bitwise AND
  3.  a | b         bit wise OR
  4.  a Λ b        bit wise exclusive OR (XOR)
  5.  a<<n       left shift n places
  6.  a>>n       right shift n places
  7.  a>>>n    ussigned right shift n places

Question 175.
Explain the use of ‘instanceof’ operator.
Answer:
The ‘instanceof’ operator verifies whether its first operand is an instance of its second operand.
Op1 instance of Op2 (Op1 must be the name of an object and Op2 must be the name of a class/interface/array type)
An object is considered to be an instance of a class if that object descends from that class directly/indirectly.
Example
Code:

class X
{ }
class Y extends class X
{   }
X x = new Y( );
if (x instance of X)
{
System.out.println("Instance of X");
}
if (x instance of Y)
{
System. out.println("Instance of Y");
}

Output:
An instance of X
Instance of Y

Question 176.
What are the access modifiers available for a class, method, and variable?
Answer:
public, private, protected, and default access.

Question 177.
Elucidate widening and narrowing conversions.
Answer:
A widening conversion occurs when we try to cast an object of lesser size to an object of larger size, e.g. short to long. A narrowing conversion, on the other hand, occurs when we try to cast an object of larger size to an object of lesser size, e.g. long to short.

Question 178.
How do you create Java API documentation?
Answer:
Java API documentation can be created using the javadoc utility which parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields.

Question 179.
Explain the concept of jar, war and ear files.
Answer:
jar is Java Archive File used to package classes, property files etc. as a single file. To create a jar file we can use the Jar command just like the zip command in windows, e.g. to create a jar file with all class files under the current directory, we can use:-

jar -cvf jarfilenatne.jar *.class

war is a Web Archive File used to package a web application, i.e. classes, JSP’s, property files etc. as a single file.

ear is an Enterprise Archive File. This format is used to package EJB, JSP, Servlets, property files etc. It is generally used to package an entire enterprise application. It can consist of multiple war files.

Each war and ear will have its own deployment descriptor which is a XML based file.

Question 180.
How many JVM’s can run on a single machine?
Answer:
A JVM is like any other process. Whence, there is no limit on the number of JVM’s which can run on a single machine.,

Question 181.
Explain the Just-In-Time (JIT) compiler.
Answer:
The Java interpreter on any platform will interpret the compiled bytecode into instructions understandable by the particular hardware. However, the JVM handles one bytecode instruction at a time. The java JIT (Just-In-Time) compiler compiles the bytecode into the particular machine code as if the program had been compiled initially on that platform. Once the code has been (re)-compiled by the JIT compiler, it will, in general, run more quickly on that system.

Question 182.
Can you retrieve Java code from Bytecode?
Answer:
YES!
Class files can be decompiled using utilities such as JAD, which takes the class file as an input and generates a java file. This feature comes especially handy when you are confused as to which version of the java file was used to generate the class file in a multi-user environment.

Question 183.
Explain the concept of garbage collector.
Answer:
When an object is no longer required and its reference count is zero, it needs to be cleaned up and freed. The garbage collector does exactly this.
In fact, the garbage collector is a thread running as a part of the JVM process. This thread scans the ‘ program for objects that will never again be accessed and releases their resources back to the system. The basic garbage collector uses the mark and sweep algorithm (which marks all the unused variables whose reference count is zero and sweeps them).

Question 184.
Can you force the garbage collector to run?
Answer:
NO!
There is no way that guarantees that the garbage collector will indeed run. It runs as and when appropriate.

Question 185.
Bring out the difference between:

  1. String si = new StnngCxyz”);
  2. String s2 = “xyz”;

Answer:
“xyz” is known as a string literal.

In the first case, a new memory space is allocated in the heap on account of the ‘new’ and also allocated in the string pool on account of the literal “xyz” * In the second case, when the statement is being compiled, a pointer to the string literal “xyz”
is stored in s2.

Question 186.
When intern( ) method on a String object is invoked, what happens?
Answer:
Interned strings avoid duplicate strings. There is only one copy of each String that has been interned, no matter how many references point to it. The process of converting duplicated strings to shared ones is called interning and is accomplished by means of the intern( ) method.

Question 187.
Bring out the purpose of the StringTokenizer class.
Answer:
The StringTokenizer class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish between identifiers, numbers, and quoted strings, nor do they recognize and skip comments. The set of delimiters (the characters which separate tokens, one from the other) can be specified either at creation time or on a pre-token basis.
Example

Code:
StringTokenizer strtok = new StringTokenizer ("Testing IT OUT!");
while (sfrfok.hasMoreTokens( )
{
System.out.println(strtok.nextToken( ));
}

Output:
Testing
IT
OUT!

Question 188.
Which collection sorts data?
Answer:
TreeMap.

Question 189.
Bring out the difference between Hashtable and HashMap.
Answer:
The main point of difference between Hashtable and HashMap is that while in a Hashtable, methods are synchronized and thus thread safe, in a HashMap, methods are not synchronized, not thread safe, making it faster.

Question 190.
Bring out the difference between Enumeration and Iterator interface.
Answer:
The main point of difference between Iterators and Enumerations is that Iterators allow the caller to remove elements from the underlying collection during the iteration but Enumerations do not allow any such provision.

Question 191.
What do you understand by the Throwable class?
Answer:
The Throwable class is the superclass of all errors/exceptions in the Java language so that only objects that are instances of the Throwable class or one of its subclasses are thrown by the JVM. Thus, only the Throwable class or one of its subclasses can be the argument type in a catch clause.

Question 192.
How can you write your own customized exceptions?
Answer:
Customized exceptions can be written by extending the java.lang. Exception class. In this context, it would be worthwhile to mention that the toString( ) method should be overridden to print an appropriate error message.

Question 193.
Suppose an exception goes uncaught; what happens in such a case?
Answer:
An uncaught exception results in the uncaughtException( ) method of the thread’s ThreadGroup being called, which ultimately causes the termination of the program in which it is thrown.

Question 194.
What gets printed when the printStackTrace( ) method is invoked?
Answer:
public void printStackTrace( )
Prints this.throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of this output contains the result of the toString( ) method for this object while the remaining lines represent data previously recorded by the filllnStackTrace( ) method.

The exact format of all this information is implementation dependent but the following may be regarded as a typical case:-

java.lang.NullPointerException
at Cls.muchjCls.java: 9)
at Cls.lunch(Cls.java: 6)
at Cls.main(Cls.java: 3)
The above output was produced by executing the following program:-

class Cls
{
public static void main(string args[ ])
{
lunch(null);
}
static void lunch(int [ ] x)
{
much(x);
}
static void lunch(int [ ] y)
{
System.out.println(y[0]);
}
}

Question 195.
How do you use these ( ) and super( ) methods with constructors? Bring out the difference between their use.
Answer:
this( ) method within a constructor is used to invoke another constructor in the same class while the super( ) method within a constructor is used to invoke its immediate superclass constructor.

Question 196.
Does java support operator overload?
Answer:
No! Not at all!!
However, java internally supports operator overloading in the form of performing String concatenation using the ‘+’ operator.

Question 197.
Compare and contrast Interfaces with Abstract classes.
Answer:
In this context, consider the following main points:-

(1) Neither interfaces nor abstract classes can be instantiated.

(2) Direct multiple inheritance is not allowed in Java unlike C++. But, java provides for interfaces to take care of this problem. A class can implement any number of interfaces, but can extend only one class.

(3) An interface has all public members and no implementation whatsoever. An abstract class is a class which may have the usual features of class members such as private, protected etc. but has some abstract methods.
(4) Interfaces should be used as much as possible and an abstract class must be used only when you want to provide some but not complete implementation.

Question 198.
Can you instantiate an abstract class? Elaborate.
Answer:
As mentioned in the previous problem, we cannot instantiate an abstract class. In order to declare an abstract class, we use the modifier or keyword abstract before the class keyword in our class definition, e.g.

abstract public class Form
{
.....................
.....................
}
class Circle extends Form
{    }

If you try to create an instance of the abstract class Form, the compiler reports an error!

Question 199
Can you declare an abstract class as final? If not, why not?
Answer:
An abstract class cannot be declared as final.
The purpose of having an abstract class is that its subclasses can extend its functionality and this very purpose of declaring an abstract class will be defeated in case an abstract class is allowed to be declared as final.

Question 200.
Bring out the use of the ‘transient’ keyword. ,
Answer:
On Object Serialization, if any of the object’s members need not be serialized, they must be declared as transient.

ASP net mvc interview questions pdf – ASP.NET MVC Interview Questions and Answers

ASP net mvc interview questions pdf: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

ASP.NET MVC Interview Questions and Answers PDF Free Download

Question 1.
Define MVC.
Answer:
MVC means Model CONTROLLER & view is a software architecture pattern for implementation of the user interface, the MVC is a framework for building a web application using a model controller & design.

Model – the represent the application core for instance a list of database records.

view – the view displays the data records on the user interface.

controller – they handled the input to the database records & MVC is also provides full control over Html, CSS, javascript & angular js, etc.

Question 2.
Write the MVC Advantage.
Answer:
The following advantage of MVC as given below:
a) It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
b) It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
c) It provides better support for test-driven development (TDD).
d) It uses view state or server-based forms, which can make managing state information easier.
e) It works well for small teams of Web developers and designers who want to take advantage of a large number of components available for rapid application development
f) It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.

Question 3.
What is an abstract class give me an example?
Answer:
They are classes that can’t be instantiated frequently either partly implemented as abstract keywords. Drive class access parent class in abstraction. Members marked as abstract must be implemented by non-abstract classes that derive from the abstract class.
Ex.

Abstract class abd
{
Public abstract int Add number (int x, int y);
}
Abstract class mno:abd
{
Public overriding int add number(int x, int y)
{
return (x+y) }}

Question 4.
What is method overloading explain?
Answer:
Creating the method in a driving class with the same name, same parameters, and same return type as in the base class is called method overriding. The method overriding is an example of run time polymorphism. We can also say dynamic polymorphism.

Ex:

Public class abc
{
Public virtual int bal( )
{
Return 10;
}
Public class abc:abc
{
Public overriding int bal( )
{
Return 200;
}
}

Question 5.
What is method overloading explain?
Answer:
Creating multiple methods in classes with the same name but different parameters and is called method overloading. The method overloading is an example of compile-time polymorphism which is done at compile time. It’s also called static polymorphism & it’s binding early.

Ex:

Public method overloading
{
Public int add (int a, int b)
// 2 int type parameter in this method.
{
return (a+b);
}
Public int add (int a, int b, int c)
//3 int type parameter in this method with the same name.
{
return (a+b+c)
} }

Question 6.
What is partial class explaining?
Answer:
It’s possible to split the definition of class or structure interface or a method over two or more source files. Each source file contains a section of the type or method definition and all parts are combined the application is compiled. The splitting of the class used partial class.

Ex:

Public partial class emp1
{
Public void Work()
{
}
}
Public partial class emp1
{
Public void ToWork()
{
}
}

Question 7.
What is the MVC filter & Explain the filters?
Answer:
The MYC controllers define action methods that usually have a one-to-one relationship with possible user interactions, such as clicking a link or submitting a form. Sometimes you want to perform logic either before an action method is called or after an action method runs. To support this type ASP .Net MVC provide a filter.

a) Authorization Filter: The implementation of authorization filter and make security decisions about whether to execute an action method, such as performing authentication validating properties of the request. The Authorize Attribute class and require HTTPS attribute class are examples of an authorization filter.

b) Action filter: The implementation of actin filter and wrap the action method execution. The action filter interface declares two methods. action Executing and OnAction Executed OnAction Executing run before the action method call and OnAction Executed runs after the action method and can perform additional processing, such as providing extra data to the action method.

Ex: OnAction Executing Method
Void OnActionExecuting (ActionExecuting Context Filter Context)
OnAction Executed Method
Void OnActionExecuted (ActionExecuted Context Filter Context)

c) Result Filter: These implement result filter and wrap execution of the action result object. The resulting filter declares two methods. OnResultExecuting and OnResultExecuted. OnResultExecuting runs before the action result object is executed. OnResultExecuted runs after the result and can perform additional processing of the result such as modifying HTTP response.

d) Exception Filter: The Exception filter implements & execute if there is an unhandled exception throw during the executing of the ASP .NET MCV pipeline. Exception filters can be used for tasks such as logging or display an error page. Ex. HandleError Attribute.

Question 8.
What is Temp Data in MVC, Explain?
Answer:
Temp data in ASP .Net MVC is basically a dictionary object derived from the Temp data dictionary. Temp data say for subsequent HTTP requests as opposed to other options(View data & View Bag) those say only current requests, so Temp data can be used to maintain data between controller action as well as redirection & temp data avoid an error.

Ex:

public Result Temp Emp( ) // Temp emp1
{
Emp empl = new emp
{
EID = “100”,
Name = “Kumar”
};

Temp data [“Emp”] = empl;
Return redirectTo Action (“Pemp”);
}
Public ActionResult Pemp() // Controller action 2 Pemp
{
Emp empl = Tempdata [“emp”] as empl
Return view(empl);
}

Question 9.
Explain the Access modifier?
Answer:
Public: Access anywhere

Private: The type of member can only be accessed by code in the same classes.

Internal: The type or member can only be accessed by any code in the same assembly but no other assembly.

Protected Internal: The type or member can only be accessed by code in the same assembly or by any derived class in another assembly.

Private Protected: The type. or member can be accessed by code in the same class or in a driven class within the base class assembly.

Access Modifier: The Access modifier providing new features for developers can see the visibility of a class property or method.

Question 10.
OOPS, Concept?
Answer:
Class: The class is a collection of objects variable, array, method,s, etc. It’s the blueprint of data, behavior & type.

Object: Object means real-world entity such as pen, book, table, etc.

Inheritance: When one object acquires all the property and behavior of the parent object is know Inheritance.

Abstraction: Hiding internal information and showing functionality is known abstraction. Ex. The phone call we don’t internal process.

Encapsulation: Encapsulation is the process where code and data bind together in a close structure.

Polymorphism: Many forms when one task is performed in different ways is called polymorphism. Ex shape or rectangular. There is two types of polymorphism runtime polymorphism & compile-time polymorphism. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Question 11.
What is a virtual keyword?
Answer:
The virtual keyword is used to modify a method, property, index or event declare in the base class and allow it to be overridden in the drive class, this method can be overridden by any class that inherits it. By default, methods are non-virtual. You cannot override a non-virtual method.

Ex:

public virtual double Area( )
{
return x * y;
}

Question 12.
What is a partial view?
Answer:
A partial view is a Razor markup file (. cshtml) that renders HTML output within another markup file’s rendered output, partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages. The partial view generically refers to MVC views and Razor Pages as markup files. The partial view is the reusable view that can be used as a child view in multiple views. The use of a partial view is to Break up large markup files into smaller components & Reduce the duplication of common markup content across markup files.

Question 13.
MVC Life Cycle Explain?
Answer:
Routing: The asp .net MVC is nothing but matching incoming URL to action. MVC request work on base of routing data which is in route table. The routing engine forwards the request to the corresponding IRouteHandler for that request. The routing engine returns a 404 HTTP status code against that request if the patterns are not found in the Route Table.

MCV Handler: The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements the IHttpHandler interface and further processes the request by using the ProcessRequest method.

Controller: MvcHandler uses the IControllerFactory instance and tries to get an IController instance. If successful, the Execute method is called. The IControllerFactory could be the default controller factory or a custom factory initialized at the Application_Start event.

Action Execution: Once the controller has been instantiated, Controller’s Actionlnvoker determines which specific action to invoke on the controller. Action to be executed is chosen based on attributes ActionNameSelectorAttribute (by default method which has the same name as the action is chosen) and ActionMethodSelectorAttribute

View Result: The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

View Engine: The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by the IViewEngine interface of the view engine. By default, Asp.Net MVC uses WebForm and Razor view engines.

Question 14.
What is two factory Authentication in MVC?
Answer:
Authentication the user in a combination of username and password along with unique OTP by sending on their registered mobile number or email basically Microsoft twillio or ASP SMS & other SMS provided with register users.

Question 15.
List the different return types of controllers of the Action method?
Answer:

SL ActionResult HelperMethod Description
1 ViewResult View ViewResult Renders a view as a web page.
2 Partial ViewResult Partial view As the name describes PartialViewResult renders the partial view.
3 RedirectResult Redirect When you want to redirect to another action method we will                           use

RedirectResult

4 RedirectT oRouteResult RedirectoRoute Redirect to another action method
5 ContentResult Content Returns a user-defined content type
6 JsonResult Json When you want to return a serialized JSON object
7 JavaScriptResult Javascript Returns a script that can be executed on the client.
8 FileResult File Returns a binary output to write to the response
9 EmptyResult None Returns null result

Question 16.
The difference between Temp data & View Data in MVC.
Answer:

Temp Data View Data
Temp data is derived from the temp data dictionary. View data is used to pass data from controller to view.
Temp data is used to pass data from the current request to the next request. It is derived from the view data dictionary class.
It keeps the information for the time of HTTP request. It’s available for the current request only.
TempData is used to pass data between two consecutive requests. Its value becomes null if a redirection has occurred.

Question 17.
What is Razor in MVC?
Answer:
Razor is one of the view engines supported in ASP.NET MVC. Razor allows you to write a mix of HTML and server-side code using C# or Visual Basic. Razor view with visual basic syntax has .vbhtml file extension and C# syntax has .cshtml file extension.

Question 18.
Explain Scaffolding in MVC?
Answer:
It is a feature of ASP.NET that allows us to generate functional code rapidly. It is also known as a code generator framework. It is pre-installed in Visual Studio 2013 and higher versions. To create a basic CRUD application, scaffolding is the best choice. It reduces time amount and generate clean code. Here, we are using scaffolding to develop the CRUD application.

Question 19.
Difference between view data and view bag?
Answer:
View Data:

  • ViewData is the property of ControllerBase class.
  • ViewData is a type of dictionary object.
  • ViewData is a key-value dictionary collection.
  • ViewData was introduced in MVC 1.0 version.
  • ViewData works with .Net framework 3.5 and above.
  • Need to do type conversion of code while enumerating.

View Bag:

  • ViewBag is a property of ControllerBase class.
  • ViewBag is a type of dynamic object.
  • ViewBag is a type of object.
  • ViewBag was introduced in MVC 3.0 version.
  • ViewBag works with .Net framework 4.0 and above.

Question 20.
Types of MVC Routing?
Answer:
Conversation-based routing: that type of routing, you define one or more route templates, which are basically parameterized strings. When the framework receives a request, it matches the URI against the route template. We call this style conventional routing because it establishes a convention for URL paths:

  • the first path segment maps to the controller name
  • the second maps to the action name.
  • the third segment is used for an optional id used to map to a model entity

ex: routes.MapRoute(“default”j”{controller=Home}/{act ion=Index}/{id?}”);
Attribute-based routing: Attribute routing uses a set of attributes to map actions directly to route templates. In the following example, app.UseMvc(); is used in the Configure method and no route is passed. The HomeController will match a set of URLs similar to what the default route
Ex: {controller=Home}/{action=Index}/{id?} would match:

Question 21.
What is bundling & Minification MVC.
Answer:
Bundling: A bundle is a logical group of physical files, which loads in a single HTTP request. We have separate CSS files, which can be loaded in a single request with the help of bundling. The bundling also can create for JavaScript files separately. A bundle can’t contain both CSS and JavaScript files. We need to create a separate bundle for CSS and JavaScript files. We create a bundle, based on the use of CSS or JS files in the Application.

Minification: Minification is a technique for removing unnecessary characters (white space, newline, tab), comments, and short variable names from text-based files such as JavaScript and CSS files without expecting to alter functionality to reduce the size, which causes improved load times of a Webpage. There are some tools available to minify JS and CSS files. Ex. IE, Mozilla, Chrome.

Question 22.
Write a few MVC helpers.
Answer:
HtmlHelper class generates Html elements using the model class object in razor view. Ex.

  • Html.ActionLink( )
  • Html.BeginForm( )
  • Html. CheckB ox( )
  • Html.DropDownList( )
  • Html.EndForm( )
  • Html.Hidden( )
  • Html.ListBox( )
  • Html.Password( )
  • Html.RadioButton( )
  • Html.TextArea( )
  • Html.TextBox( )

Question 23.
Why use JSON results in MVC?
Answer:
The JSON format is an open standard format. It’s a very familiar and commonly used concept. It’s a data interchange medium and is very lightweight. Developers use different JSON types for data transformation. JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON).

• ContentEncoding: It helps to indicate the content encoding type, the default encoding for JSON is UTF-8.
• Content-Type: It helps to indicate the content type. The default content type for JSON is application/JSON; charset=utf-8.
•Data: This indicates what the content data is. That means what you will send in JSON format.
• JsonRequestBehavior: This property has two options. Those are AllowGet and DenyGet. The default option is DenyGet.
• Recursion Limit: Indicates the constraining number of object levels to the process. The default value is 100.

Question 24.
What is Synchronization & Asynchronous in MVC?
Answer:
The synchronous methods for the following conditions:

  • The operations are simple or short-running.
  • Simplicity is more important than efficiency.
  • The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.

The Asynchronous method for the following conditions:

  • You’re calling services that can be consumed through asynchronous methods, and you’re using .NET 4.5 or higher.
  • The operations are network-bound or I/O-bound instead of CPU-bound.
  • Parallelism is more important than the simplicity of code.
  • You want to provide a mechanism that lets users cancel a long-running request.

Question 25.
What is data annotation in MVC?
Answer:
Data annotations are nothing but certain validation that we put in our models to validate the input from the user, ASP .Net MVC provides a unique feature in which we can validate the models using the data annotation attribute. We can use the data annotation library.

Question 26.
Explain view & Partial View on MVC?
Answer:

  • The Partialview generally does not have any Layout while view content Layout.
  • Partial view mostly does not contain HTML attribute like head, tag, meta, and body while view can have all these attributes
  • Partial view is reusable content that is rendered inside view (parent page)
  • Partial view mostly used with Ajax request to process fast and update particular portion while view load whole page.
  • Partial view generally processes with MVC Ajax.ActionLink and Ajax.Beginform while View process with MVC Html.ActionLink and Html.Beginform.

Question 27.
Strongly type view Example?
Answer:
The strongly type views are used for rendering a specific type of model object instead of using a general view data structure. Ex: <% = model.Name%> <%=modle.Location%>.

Question 28.
What is dependency injection?
Answer:
The Dependency Injection is passing dependency to other objects or frameworks (dependency injector). The Service is made part of the client’s state. The DI can increase readability and code reuse. Dependency injection is one form of the broader technique of inversion of control. It’s part of the SOLID Principle.

Question 29.
What is Property Explain?
Answer:
A Property is a member of the class that provides a flexible mechanism for classes to expose private fields. Internally C# property is special methods called assessors.

Question 30.
What is Design Pattern in C#?
Answer:
Design Patterns may be said as a set of probable solutions for a particular problem that is tested to work best in certain solutions. The use is very hard to predict how the architecture will work for the application when the actual application is built.

Question 31.
Types of Design Pattern?
Answer:
The following types of design patterns are available as given below:

  • Creational Patterns – The patterns deal mainly with the creation of objects and classes.
  • Structural Pattern – The Structural Patterns deals with class and object composition.
  • Behaviors Pattern – There mainly deals with class object communication. That means they are concerned with communication between class and objects.

Question 32.
What is OMR in Entity Frameworks?
Answer:
The Entity Frameworks is an object relation mapper (OMR) that enables .Net Developers to work with a database using a .NET object. It eliminated the need for most of the data access code, which developers usually need to write EF6 is a tried and tested data access technology with many years of features and stabilization.
or
The ORM manages the mapping details between a set of objects and underlying relational databases, XML repositories. ORM hides and encapsulates the change in the data source itself, so that when data sources or their APIs change. The OMR supports NHibernate, Entity Framework, Linq-to-SQL.

Question 33.
What is Software Development Methodology?
Answer:
The following methodology is given below for software development:

a) Agile Methodology- The Agile Methodology & software development work under which requirement and solution involve through the collaborative effort of self-organizing cross-functional teams. It advocates adaptive planning and continuous improvement, and it encourages rapid flexible responses to change.

b) SCRUM – Individual development software. It’s designed for teams of 3 to 9 developers who break their work into actions that can be completed within timeboxed interactions called sprints (typically 2 weeks) and track progress and re-plan in a 15-minute stand-up meeting called SCRUM.

c) Waterfall Model – The waterfall model is a direction & development model that includes analysis, design, construction, testing, development & Maintenance.

Question 34.
What is used to keep and peek at temp data in the MVC projects?
Answer:
The Temp Data once is read to the current request it’s available to a subsequent request. If we want temp data to be read and available in the subsequent request then reading we need to call the “Keep” method in MVC Project. E.g.:

@TempData [“Sonali”];
TempData.keep[“Sonali”];
The peek function help to read as well as advice MVC to maintain “TempData” for the subsequent request.
E.g.:
String str = TempData.peek [“Sonali”].ToStringQ;

Question 35.
Which namespace is used for ASPX View Engine?
A. System.Web.Razor
B. System.Web.Mvc.WebFormViewEngine
C. Both A & B
D. None
Answer:
B. System.Web.Mvc.WebFormViewEngine

Question 36.
Which of the following are Actionselectors?
A. ActionName
B. NonAction
C. ActionVerbs
D. All of the above
Answer:
D. All of the above

Question 37.
What is the name of the configuration files that the App Start folder contains?
A. BundleConfig.es
B. FilterConfig.es
C. RouteConfig.es
D. All of these
Answer:
D. All of these

Question 38.
Attributes can be used for data validation in MVC.
A. DataAnnotations
B. Fluent API
C. DataModel
D. HtmlHelper
Answer:
D. HtmlHelper

Question 39.
RedirectToAction() Method for which Status code represents?
A) 304
B) 302
C) 301
D) 300
Answer:
B) 302

Question 40.
RedirectToActionPermanent() Method for which Status code represents?
A) 304
B) 302
C) 301
D) 300
Answer:
C) 301

Question 41.
In which format data can be return from XML into a table?
A) DataSet
B) Datatable
C) A and B
D) None
Answer:
A) DataSet

Question 42.
Can we use view state in MVC?
A) Yes
B) No
C) Both A & B
D) None
Answer:
B) No

Question 43.
What is default authentication in Internet Information Services (IIS)?
A) Standard User
B) Administrator
C) Anonymous
D) None
Answer:
C) Anonymous

Question 44.
Which Namespace is used for Razor View Engine?
A) System.Web.Razor
B) System.Web.Mvc.WebFormViewEngine
C) Both A & B
D) None
Answer:
A) System.Web.Razor

Question 45.
How can you comment using Razor Syntax?
A) *@ Comment line *@
B) @* Comment line *@
C) @* Comment line @*
D) *@ Comment line @*
Answer:
B) @* Comment line *@

Question 46.
The ASPX View Engine uses to render server-side content.
A) @
B) <%= %>
C) Both A & B
D) None
Answer:
B) <%= %>

Question 47.
Which is faster between ASPX View Engine and Razor View Engine.
A) ASPX View Engine
B) Razor View Engine
C) Both A & B
D) None
Answer:
D) None

Question 48.
What is RouteConfig.es in ASP.Net MVC?
A. RouteConfig.es is used to register MVC config statements, route config.
B. RouteConfig.css is used to register global MVC bundles.
C. None
D. All
Answer:
A. RouteConfig.es is used to register MVC config statements, route config.

Question 49.
What is the purpose of the Interface?
Answer:
The following feature/purpose of the interface is given below:

  • Allow for pluggable software.
  • Allow different objects to interact easily.
  • Hide implementation details of a class from each other.
  • The facility of reuse of software.

Answer:

  • Allow for pluggable software.

 

exit and atexit function in C

exit and atexit function in C

Interview Questions

  • What is exit function in C.
  • What is atexit function and can we call it more than once in a C program.

What is exit function in C.

The function void exit(int status); terminates calling process normally. Before terminating a process, it performs the following operations:

  • Functions registered with atexit are called.
  • All streams/files are closed and flushed if buffered, and all files created with tmpfile are removed.
  • Control is returned to the calling(host) environment.

Function prototype of exit function

void exit(int status);

exit and atexit function in C

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    printf("Program start\n");
    /* Terminating program using exit */
    exit(0);
    printf("It won't get printed ever\n");  
    return 0;
}

Output

Program start

What is atexit function and can we call it more than once in a C program.

The stdlib C Library function int atexit(void (*func)(void)); registers the function pointed to by func to be called when the program terminates. Upon normal termination of the program, function pointed by func is automatically called without arguments. You can register your termination function anywhere in program.

This function returns zero value, if the function was successfully registered, otherwise a non-zero value if unsuccessful.

What is atexit function and can we call it more than once in a C program

#include <stdio.h>
#include <stdlib.h>
 
void myFunction(){
    printf("Program end, Bye Bye\n");
    getch();
}
 
int main(){
    printf("Program start\n");
    atexit(myFunction);  
    return 0;
}

Output

Program start
Program end, Bye Bye

You can call atexit function more than once, they are all executed in reverse order of their call(the last function to be registered will be the first function to be called).

BONUS INTERVIEW QUESTIONS ON C#.NET Interview Questions in Java

We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on BONUS INTERVIEW QUESTIONS ON C#.NET

Question 1.
Compare in brief C++, Java, and C#.
Answer:
C++, Java, and C# share a common ancestry but differ in many ways. C# and lava are like close cousins. Both support distributed programming and both use intermediate code to achieve safety and portability. However, the details differ. Both also support run-time error checking, security, and managed execution. But, the details differ a lot once more. Furthermore, unlike Java, C# provides access to pointers, a facet supported by C++. In this way, we come to see that C# combines the raw power of C++ with the type safety of Java.

Question 2.
Discuss the evolution of the various versions of C#.
Answer:
Many new features have been added to C# ever since its initial version 1.0 in the year 2000, the first major revision being 2.0, followed by release 3.0, and eventually 4.0.

The most important change brought about by C# 2.0 was the revolutionary introduction of generics. LINQ (Language Integrated Query) and lambda expressions were the major additions made by the 3.0 release while named & optional arguments and the keyword dynamic (which relaxes type checking rules to run-time rather than at compile time) along with support for parallel programming by means of TPL (Task Parallel Library) and PLINQ (Parallel LINQ) were the major introductions made by the version 4.0 of C#.

Question 3.
Give two compelling reasons for the creation of C#.
Answer:
Java answered many of the needs of the programmers but was lacking on two scores, namely:-

  • Mixed-language programming / Cross-language interoperability
  • Full integration with the Windows platform ‘

C# was the result of mainly these two needs and Microsoft’s overall .NET strategy in the late 1990s.

Question 4.
Mention two main points as to how C# relates to the .NET Framework.
Answer:

  • First, C# was initially meant to program on the .NET Framework.
  • Secondly, the libraries used by C# are those as defined by the .NET Framework.

Question 5.
Distinguish between managed and unmanaged code.
Answer:
A normal C# program written under the control of the CLR (Common Language Runtime) is subject to several constraints and as such obtains consequent benefits thereof – such code is known as managed code. On the contrary, unmanaged code does not run under the control of the CLR. But, the point to be noted is that managed and unmanaged code can work together.

Question 6.
What are the value types allowed by C#?
Answer:
In addition to the thirteen simple types such as bool, char,decimal, double, float, int etc. C# allows enumerations, structures and nullable types, all of which are value types.

Question 7.
What is the decimal data type intended for?
Answer:
The decimal type is indeed the most interesting C# numeric type intended for use in monetary/financial calculations. It can successfully represent up to 29 decimal places without any rounding errors, a fact that makes it especially useful for computations involving money/ finance.

Question 8.
Is there any special significance of the char data type in C#?
Answer:
Unlike most other languages such as C++, which use the standard 8-bit ASCII character set, C# uses a 16-bit character type called Unicode, which is large enough to accommodate all of the characters found in all the human languages including Chinese, French, German, and, of .course, English.

Question 9.
What do you understand by a widening and a narrowing conversion?
Answer:
When one type of data is assigned to another type of variable, an implicit widening conversion takes place automatically in C# if the two types are compatible and the range of the destination type is greater than that of the source type. In all other cases, you need to apply a cast. When a cast includes a narrowing conversion such as from a float to an int, information may be lost due to truncation, e.g., if the value 1.14 is assigned to an integer, the resulting value will be just 1 and 0.14 is lost.

Note: You may like to compare this concept with Java. For this, you are advised to refer to chapter 1.

Question 10.
What is the difference between the use of the prefix increment ++x and the use of the postfix increment x++ in C# and Java?
Answer:
There is essentially no difference between the use of the postfix increment x++ and the prefix increment ++x in C# and Java. If you know how to use these operators in one of these languages, you can use them the same way in the other.

Question 11.
What is the difference between short-circuit logical operators || OR and && AND in C# and Java?
Answer:
The short circuit logical operators || OR and && AND operate in the same manner in both C# and Java.

Question 12.
Can you name an operator in C# that takes three operands?
Answer:
The ternary operator with the most general form:-
exp1? exp2: exp3;
(if exp1 is true, exp2 becomes the value of the whole expression else exp3 becomes the value of the whole expression)

Note: the use of the ternary operator in Java as well. It operates the same way.

Question 13.
Can you create a ‘for’ loop without any conditional expressions? What does it amount to?
Answer:
Leaving the conditional expressions in a ‘for’ loop makes it an infinite loop that will run forever:-
for (; 😉 // intentional infinite loop
{
………………………….
………………………….
}
An infinite for’ loop can be created in Java the same way.

Question 14.
What does each loop do?
Answer:
Each loop cycles through the elements of a collection.

Note that there is a for-each style loop in Java as well but without the foreach keyword.

Question 15.
What do the break and continue statements do? Bring out the main point of difference between them.
Answer:
The break statement causes early termination of the loop, whereas the continue statement causes an early iteration of the loop. Again, note that the break and continue statements work the same way in Java.

Question 16.
Explain the use of the keyword new.
Answer:
The keyword new is used to create objects, e.g.
Room classroom = new Room( );
Here, the classroom by itself does not contain the object (Room).
Rather, it contains a reference to it.
On the other hand, consider:-
int i = 100;
Here, i contains the value 100 since i is a variable of type int, which, in turn, is a value type. Again, consider:-
Room classroom1 = new Room ( );
Room classroom2 = new Room ( );
classroom2 = classroom1;
Room classroom3 = new Room ( );
classroom2 = classroom3;
After the execution of this sequence, classroom2 refers to the same object (Room) as classroom3. The object (Room) referred to by the classroom1 is unchanged.

Note: The keyword new works in essentially the same manner in Java.

Question 17.
Can now be used with value types?
Answer:
Yes, although new is mainly meant for reference types.
For example,
int k = new int ( );
initializes k to zero.

Question 18.
Point out the difference between C++ and C# as regards the release of previously allocated memory.
Answer:
In C++, the delete operator is used to free memory that was previously allocated. But, C# uses a different, more trouble-free approach, viz. garbage collection.

Note: Also, try to note the similarity between Java and C# in this respect, viz. garbage collection.

Question 19.
What is the purpose of the destructor in C#?
Answer:
We can define a method in C# that shall be called just prior to the object’s final destruction by the .garbage collector. This method is known as the destructor, which can be used in some highly specialized situations to ensure that the object is destroyed/terminated cleanly.

Question 20.
What do you understand by ‘this’?
Answer:
When a method is called, it is, by itself, passed a reference to the invoking object, i.e. the object on which the method is called. This reference is referred to as ‘this’.

Note: Try to see Java’s ‘this’ reference. Do you note any differences?

Question 21.
Can you elaborate on the concept of jagged arrays?
Answer:
In general, when we create a two-dimensional array, we are creating what is a rectangular array with the length of each row being the same for the entire array, e.g. a 2 x 3 array implies an array of two rows with three elements in each row. But, C# allows you to create a special two-dimensional array called a jagged array, which is an array of arrays, where the length of each array can differ. In this way, we can have a table where the lengths of the rows differ, e.g.

int [ ][ ] jag – new int [4] [ ];
jag [0] = new int [10]; //length of first array is ten
jag [1} ~ new int [2]; //length of second array is two
jag [2] = new int [5]; // length of third array is five
jag [3] = new int [8]; //length of fourth array is eight

Note: There is a concept of jagged arrays in Java as well. Try to see the difference in the declaration of multi-dimensional arrays in C# and Java. It would not be possible to take up the complete discussion here. However, if interested, you can refer to the authors’ works – “The Essentials of Java” & “The Essentials ofC# 4.0″ in this context.

Question 22.
Can you point out the main difference between C/C++ strings and C# strings?
Answer:
In C/C++, strings are simply arrays of characters terminated by the ‘\0’ null character whereas in C#, string is a built-in data type. In fact, in C#, strings are objects and thus, reference types.

Question 23.
Can the contents of strings in C# be changed?
Answer:
No, strings in C# are immutable (see also Question 586). This might seem to be a drawback but since unused string objects are automatically garbage-collected, you can simply create a new string with the desired changes.

Question 24.
What are C#’s access modifiers?
Answer:
In C#, member access control is achieved through four access modifiers, namely, public, private, protected and internal. The protected modifier applies only in case of inheritance; the internal modifier applies mostly to the use of an assembly, which for C# loosely implies a deployable program/library. When a member of a class is modified by the public specifier, then that member can be accessed by any code in your program. If a member of a class is specified to be private, it can then only be accessed by other members of its class so that methods in other classes will not be able to access a private member of another class.

Note: Try to see Java’s access specifiers. What differences do you note?

Question 25.
What is the use of the ref and out keywords?
Answer:
By means of the ref and out keywords, it becomes possible to pass any of the value types by reference.

Question 26.
Is it possible to have a variable number of arguments in C#?
Answer:
Yes, it can be achieved by means of the params modifier which represents an arbitrary number of parameters.

Note: Can a variable number of arguments be used in Java? Left as an exercise for you.

Question 27.
What is the use of the object initializers?
Answer:
The primary use of the object initializers is with the anonymous types created in a LINQ expression. Object initializers provide a means to create an object and initialize its fields and properties.

Question 28.
Can you elaborate on the use of the optional arguments?
Answer:
By means of optional arguments, you can specify a default value for a method’s parameter. This feature has been introduced in C# 4.0.

Question 29.
Can optional arguments result in ambiguity?
Answer:
One problem that can result while using optional arguments is ambiguity. This occurs when a method having optional arguments is overloaded.

Question 30.
What do you understand by named arguments?
Answer:
Named arguments are a feature related to the passing of arguments to a method. This feature has recently been introduced in C# 4.0. With the help of named arguments, one can specify the name of the parameter to which an argument applies.

Question 31.
Specify the forms of the Main ( ) method available in C#.
Answer:
The following four versions of Main ( ) are currently available in C#:-

  1. static void Main ( )
  2. static int Main ( )
  3. static void Main (string args[ ])
  4. static int Main (string args[ ])

Question 32.
Elucidate the role of the keyword static.
Answer:
In general, a class member has to be accessed through an object of its instance. But, it is possible in C# to create a member that can be used by itself, without any reference to a specific instance. To create such a member, you have to precede its declaration with the keyword static. Besides static variables and methods, we can even have static classes, which have two significant uses. First, a static class is used to contain a set of related static methods. Second, a static class is needed when creating extension methods, which relate mostly to LINQ.

Question 33.
Point out any two restrictions on static methods?
Answer:
First, a static method cannot have a ‘this’ reference. Second, a static method can directly call only other static methods of its class.

Question 34.
When an operator is overloaded, does its original meaning get lost?
Answer:
When we overload an operator relative to a class, none of its original meanings is lost. It is just that a new operation/meaning relative to that class gets added. For instance, overloading the – operator to handle the removal of a node from a linked list does not alter its original meaning relative to integers, i.e. subtraction.

Question 35.
What are indexers used for?
Answer:
Indexers provide the means by which an object can be indexed like an array. Array indexing is done using the [ ] operator. It is possible to define the [ ] operator for the classes one creates, but it is not done using an operator method. Rather, we use an indexer.

Question 36.
What are properties used for?
Answer:
Properties offer a streamlined approach to manage excess to the instance data of a class.

Question 37.
Are indexers and properties related to each other?
Answer:
Indexers and properties are related to each other as both of them depend upon another feature of C#, viz. the get & set accessors.

Question 38.
Can you overload an indexer?
Answer:
Yes, an indexer can be overloaded. The version executed shall be the one that is the closest type-match between its parameter and the argument used as an index.

Question 39.
Does an indexer require an underlying array?
Answer:
It is not necessary that an indexer necessarily operates on an underlying array. Rather, it must simply provide functionality that seems to be ‘array-like to the user of the indexer.

Question 40.
What is the main difference between a private variable and a property?
Answer:
Suppose, you want to limit the range of values that can be assigned to a field. It is possible to achieve this aim by means of a private variable along with methods to access its value. However, the property offers a much better, more streamlined way to achieve the same goal.

Question 41.
What do you mean by an auto-implemented property?
Answer:
Auto-implemented properties with the most general form:-
prop_data_type prop_name { get; set; }
where, prop_data_typerefers to the data type of the property and prop_name refers to its name, were introduced in C# 3.0.

Auto-implemented properties made it possible to implement very simple properties without having to explicitly specify the variable managed by the property. Instead, the compiler was assigned the task of automatically supplying the underlying variable.

Question 42.
Can properties be overloaded?
Answer:
No, you cannot overload a property. But, you can have two different properties with both accessing the same variable.

Question 43.
Can a property be passed as a ref or out parameter to a method?
Answer:
No, since the property does not specify a storage location, it cannot be passed as a ref or out parameter to a method.

Question 44.
Can you use a different access modifier with the get and set accessors than the one used for their indexer/property?
Answer:
By default, the get and set accessors have the same accessibility as that of their indexer/property But, you can use a different access modifier as well, e.g. if the indexer/property is public, you can give get or set its own access modifier such as private.

Question 45.
Both the base class and the derived class can have their own constructors. So, what constructor is responsible for building an object of the derived class – the one in the base class, or the one in the derived class, or both?
Answer:
The constructor for the base class constructs the base class part of the object and the constructor for the derived class builds the derived class portion of the object.

Note: This is similar to the concept of superclass and subclass in Java.

Question 46.
How does a derived class call a constructor defined in its base class?
Answer:
A derived class can call a constructor defined in its base class by using an expanded form of the derived class’ constructor declaration and the base keyword in the following manner:-
derived_class_constructor (parameter_list) : base (arg_list)
{
……………….
………………
}
where arg_list specifies any arguments required by the constructor in the base class.

Question 47.
In what order are constructors called in a class hierarchy?
Answer:
In a class hierarchy, constructors are called in their order of derivation (just like in Java).

Question 48.
What do you mean by method overriding?
Answer:
The process of redefining a virtual method inside a derived class is referred to as method overriding. When overriding a method, the name, return type, and signature of the overriding method must exactly be the same as that of the virtual method being overridden.

Question 49.
What do you understand by dynamic method dispatch?
Answer:
Dynamic method dispatch is the means by which a call to an overridden method is resolved at run-time rather than at compile tim£. It is important since C# implements run-time polymorphism this way.

Note: The concepts of method overriding and dynamic method dispatch work in the same way in Java as in C#.

Question 50.
Can properties/indexers be modified by the keyword virtual and overridden using override?
Answer:
The answer to both the queries is in the affirmative.

Question 51.
Can you give one good reason for using overridden methods?
Answer:
Overridden methods are another way that C# implements the ‘One interface, multiple methods’ aspect of polymorphism.

Question 52.
Can an abstract method have a body?
Answer:
No, not at all!

Question 53.
Can you use virtual and abstract together?
Answer:
An abstract method is, by itself, virtual and there is thus, no need to specify the virtual modifier. In fact, it’s an error to use virtual and abstract together!

Question 54.
Can you create an object of an abstract class using new?
Answer:
An abstract class does not specify a complete implementation and whence, there can be no objects of an abstract class. Therefore, attempting to create an object of an abstract class using new will lead to a consequent compile-time error.

Question 55.
What are the two uses of the keyword sealed?
Answer:

  1. You can use sealed to prevent a class from being inherited by preceding the class declaration with the keyword sealed.
  2. You can use sealed virtual methods to prevent further overrides.

Note: Is there a similar keyword in Java? Yes – the final’ keyword.

Question 56.
What do you mean by boxing and unboxing?
Answer:
When an object reference refers to a value type, the value type is said to be ‘boxed inside the object and this process is referred to as boxing. The reverse process of retrieving a value from a boxed object using an explicit cast from the object reference to its corresponding value type is referred to as unboxing.

Note: Are there any differences between C# and Java as regards the concepts of boxing and unboxing? Try to find out for yourself! We would just like to mention that there are concepts of auto-boxing and auto-unboxing in Java.

Question 57.
Is the object class a universal data type? If it is, what are its pitfalls?
Answer:
The object class is indeed a universal data type in C# and it is possible to use an object reference to refer to any type of data. This makes it possible to get past C#’s otherwise impregnable/strong type checking. But, this must be avoided as far as possible since it can lead to unexpected errors and bugs. Indeed, it’s best to save an object’s universal nature for highly special situations. More importantly, true generics are available ever since C# 2.0, and this feature enables you to easily define classes and algorithms that work automatically with different data types in a type-safe manner.

Note: Does Java too have such a similar superclass universal in nature? Yes, it has! Find it out!!

Question 58.
Define an interface in C#.
Answer:
An interface defines a set of methods that will be implemented by a class. An interface, by itself, does not implement any method. In this way, we see that an interface is a purely logical construct that describes functionality without defining any implementation whatsoever.

Question 59.
What is the main point of difference between structures and classes?
Answer:
Structures and classes are similar to each other except that structures are handled as value types whereas classes are treated as reference types.

Question 60.
What is the similarity and difference between interfaces and abstract classes?
Answer:
Interfaces are syntactically similar to abstract classes. But, in an interface, no method can have a body. Thus, an interface does not provide any implementation at all. It tells what is to be done but is completely silent about how it is to be done. Once an interface is specified, any number of classes can implement it. Moreover, one class may implement any number of interfaces.

Question 61.
How will you choose between an interface and an abstract class?
Answer:
When you can fully describe the concept in terms of ‘what it does’ without any need to specify ‘how it does it, you should use an interface. However, if you need to include at least some implementation details, you should use an abstract class to represent your concept.

Question 62.
When would you prefer to use a structure instead of a class?
Answer:
In general, if you need to just store a group of related data, but don’t need to operate on that data through a reference and don’t need inheritance, structures are a more efficient choice and should be preferred to classes.

Question 63.
Can an enumeration be used to control a switch statement or as a control variable in a ‘for’ loop?
Answer:
Since enumerations represent integer values, they can easily be used to control a switch statement or as the control variable in a ‘for’ loop.

Note: There are enumerations in Java as well. However, there remains many a difference between C# and Java in this respect.

Question 64.
What are an exception and an exception handler?
Answer:
An exception is an error that occurs at run-time. Exception handling streamlines error handling by allowing the program to specify a block of code, called an exception handler, which is executed automatically in case of an error. Exception handler eliminates the need to manually check the success/failure of each specific operation or method call. In case an error occurs, it is processed/handled by the exception handler gracefully.

Note: Once again, try to see Java’s exception handling mechanism. Do you note any differences?

Question 65.
Can you elaborate on the consequences of an uncaught exception?
Answer:
In general, if your program does not catch an exception, it will be caught by the run-time system, which, in turn, will report an error and terminate the program abnormally / ungracefully.

Question 66.
What is the major benefit of exception handling?
Answer:
One of the major benefits of exception handling is that it enables your program to respond to an error and then continue running, that is, handle the error gracefully, and then continue further.

Question 67.
What are the pitfalls of using the ‘catch all’ handler as a means of dealing with exceptions?
Answer:
The inappropriate use of the ‘catch all’ handler can result in situations where errors that would otherwise be detected during testing would go unnoticed. It is also difficult to correctly handle all types of exceptions with a single ‘catch all’ handler. The ‘catch all’ handler should therefore be used rarely in certain specialized and exceptional situations.

Question 68.
Can you have a try block followed by a final block with no catch clauses?
Answer:
Syntactically, when a final block follows a try block, no catch clauses are technically required. In such a case, the final block gets executed after exit from the try block, but no exceptions are handled in such a case/event.

Question 69.
Elucidate the use of the checked and unchecked keywords.
Answer:
Overflow exceptions in arithmetic computations are controlled by the keywords – checked and unchecked. To ignore the overflow, unchecked is used and to catch the overflow exception, checked is used.

Question 70.
What is a stream in C#?
Answer:
C# programs perform Input / Output through streams. A stream is an abstraction that produces/consumes information. A stream is liked a physical device by the I/O system. It is useful to note that all streams behave in the same manner irrespective of the physical device they might be linked to.

Note: Do streams in Java behave the same way? Left as an exercise for you!

Question 71.
Name the standard console I/O streams.
Answer:
Console.In, Console.Out, and Console. Error are the three standard console I/O streams.

Question 72.
How is binary data read and write?
Answer:
Binary values of the C# built-in types are read and written using the BinaryReader and BinaryWriter streams, respectively. It is pertinent to mention over here that this data is read and written using not its human-readable text format but using its internal, binary form.

Question 73.
Define a delegate and an event.
Answer:
A delegate is a means to encapsulate a method. It is useful to note that a delegate in C# is similar to a function pointer in C/C++. An event is a notification that an action has occurred. Delegates and events are related since an event is built upon a delegate.

Question 74.
What do you understand by multicasting?
Answer:
In simple language, multicasting is the creation of a chain of methods that shall be called by itself when the delegate is invoked; this chain can be created by instantiating the delegate, then using + or += operator to add methods to the chain, and – or -= operator to remove methods from the chain.

Question 75.
In what way are delegated useful?
Answer:
First of all, delegates are useful as they support events. Second, delegates provide a means to execute methods at run-time without having to precisely know what those methods are at compile time. This ability of the delegates comes in especially handy if we want to create a framework that allows components to be plugged in.

Question 76.
Name the two types of lambda expressions.
Answer:
The two types of lambda expressions are the expression lambdas and the statement lambdas.

Question 77.
How does an event work?
Answer:
An object that has an interest in an event registers an event handler for that event. When the event occurs, all registered handlers represented by delegates are invoked.

Question 78.
Define a namespace.
Answer:
A namespace is, in essence, a declarative region, which provides a way to keep a set of names separate and away from conflict with another.

Question 79.
Can namespaces be nested, one inside another?
Answer:
The answer to this query is in the affirmative.

Question 80.
List the C# preprocessor directives.
Answer:
Following is the required list of C# preprocessor directives;-

  1. #define
  2.  #elif
  3. #else
  4. #endif
  5. #endregion
  6. #error
  7. #if
  8. #line
  9. #pragma
  10. #region
  11. #undef
  12. #warning

Question 81.
What do you mean by generics?
Answer:
Generics imply parameterized types. They provide a streamlined and type-safe approach to deal with different data types as compared to the universal object class. They also promote the reusability of code. Generics were introduced by C# 2.0 and they have revolutionized the C# language ever since their inception.

Note: Generics have also been introduced in Java and are somewhat similar to templates in C++. However, differences remain.

Question 82.
Can properties/indexers/operators be generic?
Answer:
Properties/indexers/operators cannot be generic. But, they can be used in a generic class to make use of the generic type parameters provided therein.

Question 83.
Explain in brief the utility of LINQ.
Answer:
LINQ (Language Integrated Query) gives C# the ability to generate queries for any LINQ-compatible data source. Moreover, the syntax used for the query remains the same irrespective of the data source so that the syntax used to query data in a relational database is the same as the one used to query data stored in an array, for instance. There is no need to use SQL or any other mechanism not related to C# so that the query capability is fully and wholly integrated into the C# language.

LINQ can also be used along with SQL, XML files, ADO.NET Datasets as also with C# collections and arrays. Thus, we see that LINQ provides a uniform platform to access data in general.

Question 84.
What do you understand by nullable types?
Answer:
A nullable type is a special version of a value type that is represented by a structure. In addition to the values defined by the underlying type, it can also store the value null. In this way, we see that a nullable type has the same range and characteristics as its underlying type but has the additional capability to represent a value, which indicates that a variable of that type is unassigned. It may also be noted that only value types have nullable equivalents.

Question 85.
Differentiate between dynamic type and the object class.
Answer:
In one way, the dynamic type is similar to the object class since it can be used to refer to any type of object. The difference is that in the case of dynamic, all type checking is deferred until run-time whereas, with the object class, type checking still takes place at compile time.

Question 86.
How can you create a string in C# that is mutable?
Answer:
A mutable string in C# can be created by means of the StringBuilder class, which is in the System. Text namespace.

Note: Compare and contrast the way a mutable string is created in Java.

Question 87.
What do you understand by multithreading?
Answer:
C# has built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each such part is called a thread, and each thread defines a separate path of execution. A text editor formatting its text and printing at the same time is a good example of multithreading. In this way, we see that multithreading is a specialized version of multitasking.

Question 88.
What is meant by TPL?
Answer:
TPL (Task Parallel Library) is one of the most important features added to the .NET Framework by version 4.0. This library enhances multithreaded programming in two ways. First, it facilitates the creation and use of multiple threads. And, second, it automatically makes use of multiple processors.

Question 89.
What is meant by PLINQ?
Answer:
Another important feature added by .NET 4.0 is PLINQ (Parallel Language Integrated Query). PLINQ enables you to write queries that automatically make use of multiple processors and parallelism wherever appropriate. It enables the addition of parallelism to a query with minimal effort.

Question 90.
While using the TPL, what are the two basic ways in which you can add parallelism?
Answer:
Data Parallelism & Task Parallelism.

Question 91.
Elucidate the utility of collections.
Answer:
Collections simplify many programs by providing off-the-shelf solutions to several common but at times difficult to develop data structures. For instance, there are built-in collections that support dynamic arrays, linked lists, stacks, queues, and hash tables.

Question 92.
What is the ArrayList class?
Answer:
The tire ArrayList class supports dynamic arrays, which can grow or shrink as per the user requirements.

Question 93.
What is a Hashtable?
Answer:
Hashtable creates a collection that uses a hash table for storage (the hash table, in turn, stores information using a mechanism known as hashing).

Question 94.
Define a SortedList.
Answer:
SortedList creates a collection that stores key / value pairs in sorted order, based on the value of the keys.

Question 95.
On what principle does a Stack operate?
Answer:
Stack is a “First-in, Last-out” list. To visualize a stack, imagine a stack of plates on a table. The first plate put down is the last one to be retrieved.

Question 96.
What is the principle behind the Queue?
Answer:
The queue is a “First-in, First-out” list, i.e. the first item put in a queue is the first item retrieved from it. Queues are common in real life, e.g. lines at a bank or railway reservation center are queues.

Question 97.
What is a BitArray?
Answer:
The BitArray class supports a collection of bits. Since it stores bits rather than objects, its capabilities are different than those of other collections.

Question 98.
Elaborate on the role of the enumerator.
Answer:
Quite often, one needs to cycle through the elements in a collection, e.g. you may want to display each element. One way to do this is by means of the for each loop. Enumerator provides another way for the same.

Question 99.
What is the utility of the collection initializers?
Answer:
C# includes a feature called the collection initializer, which helps to initialize certain collections. The syntax is similar to an array initialization.

Question 100.
What types of comments are supported by C#? Does it support XML documentation comments?
Answer:
C# supports three types of comments – the first two are / / and /*’*/. The third type is based on XML tags and is called a documentation comment or an XML comment. A single line documentation comment begins with III while a multiline documentation comment begins with /** and ends with */•

Such documentation comments, in general, precede the declaration of things like classes, namespaces, methods, properties and events; you can embed information about your program into the program itself using these documentation comments and on compiling the program, you can have these comments placed into an XML file as well.

You are advised to compare and contrast the type of comments supported by Java for yourself (refer Chapter 1 in this context). .

Note :

 We have briefly referred to certain similarities and differences between Java and C# as regards various 
topics in the foregoing text, which could be of vital importance from the "INTERVIEW" point of view. 
As already pointed out, it would not be possible to take up a complete discussion of these here. However, 
you can refer to the authors' works - "The Essentials of Java" & " The Essentials of C# 4.0" in this context.

Basic .NET Framework Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Basic .NET Framework

Question 1.
What is an IL code? (B)What Is an IL?
Answer:
IL code is a partially compiled code.

Note: Half compiled means this code is not yet compiled to machine/CPU (Central Processing Unit) specific instructions.

Question 2.
Why is IL code not fully compiled?
Answer:
We do not know in what kind of environment the .NET code will run. In other words, we do not know what can be the Operating System (OS), CPU configuration, machine configuration, security configuration, etc. So the IL code is half compiled and on run-time, this code is compiled to machine-specific using the environmental properties (CPU, OS, machine configuration, etc).

Question 3.
Who compiles the IL code and how does it work?
Answer:
IL code is compiled by JIT (Just-in-time) compiler.

Question 4.
How does JIT compilation work?
Answer:
JIT compiles the code just before execution and then saves this translation in memory. Just before execution JIT can compile a profile, per function, or a code fragment.

Question 5.
What are the different types of JIT? (P)What are the different types of JIT?
Answer:
In Microsoft .NET there are three types of JIT compilers:

  • Normal-JIT (Default): Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and then they are stored in the cache. When the same methods are called again, the compiled code from the cache is used for execution.
  • Econo-JIT: Econo-JIT compiles only those methods that are called at runtime. However, these compiled methods are not stored in the cache so that RAM (Random Access Memory) can be utilized in an optimal manner.
  • Pre-JIT: Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application. We can implement Pre-JIT by using ngen.exe (The Native Image Generation).

Normal-JIT is the default implementation and it produces optimized code. Econo- JIT just replaces IL instruction with its native counterpart. It does not do any kind of optimization. Econo- JIT does not store the compiled code in the cache so it requires less memory.
The choice of Normal-JIT and Econo-JIT is decided internally. Econo-JIT is chosen when devices have

limited memory and CPU cycle issues like Windows CE-powered devices. When there is no memory crunch and CPU power is higher than Normal-JIT is used.

Pre-JIT is implemented by using ngen.exe which is explained in the next question.

Question 5.
What is Native Image Generator (Ngen.exe)?
Answer:
Ngen stores full compiled .NET native code into the cache. In other words, rather than dynamically compiling the code on runtime a full image of natively compiled code is stored in cache while installing the application. This leads to better performance as the assembly loads and executes faster.

In order to install full compiled native code in the cache, we can execute the below command line from your Visual Studio command prompt.

ngen.exe install <assemblyname>

Question 6.
So does it mean that NGEN.EXE will always improve performance?
Answer:
No, it’s not always necessary that ngen.exe produces optimized code because it uses the current environment’s parameters which can change over a period of time. For instance, a code compiled in the Windows XP environment will not be the optimized code to run under Windows 2008 server. So we need to test once with ‘ngen’ and without ‘ngen’ to conclude if really the performance increases.

Question 7.
Is it possible to view the IL code?
Answer:
Yes by using ILDASM (IL Disassembler) simple tool we can view an IL code of a DLL (Dynamic Link Library) or EXE (Executable). In order to view IL code using ILDASM, go to Visual Studio command prompt and run “ILDASM.EXE”. Once ILDASM is running you can view the IL code,

Question 8.
What is a CLR?
CLR (Common Language Runtime) is the heart of.NET framework and it does four primary tasks:

  • Garbage collection
  • CAS (Code Access Security)
  • CV (Code Verification)
  • IL to Native translation.
Note:  There are many other uses of CLR but I have kept it short for interview point of view. 
           In the further section, we will explain these questions briefly.

Question 9.
What is the difference between managed and unmanaged code?
Answer:
Code that executes under the CLR execution environment is called managed code. Unmanaged code executes outside the CLR boundary. Unmanaged code is nothing but code written in C++, VB6, VC++, etc. Unmanaged codes have their own environment in which the code runs and it’s completely outside the control of CLR.

Question 10.
What is a garbage collector?
Answer:
The garbage collector is a feature of CLR which cleans unused managed (it does not clean unmanaged objects) objects and reclaims memory. It’s a background thread that runs continuously and at specific intervals, it checks if there are any unused objects whose memory can be claimed.

Note: GC does not claim memory of unmanaged objects.
Note: Garbage collector is one of the very important interview topics due to complexity of 
          generations, double GC loop because of destructor, and the implementation of finalizing 
          and dispose pattern. So please go through the video of “What are Garbage collection, 
          Generation, Finalize, Dispose and Idisposable?” to ensure that you understand the fundamentals clearly.

Question 11.
What are generations in Garbage Collector (Gen 0, Gen 1, and Gen 2)?
Answer:
Generations define the age of the object. There are three generations:

  • Gen 0: When an application creates fresh objects they are marked as Gen 0.
  • Gen 1: When GC is not able to clear the objects from Gen 0 in the first round it moves them to Gen – 1 bucket.
  • Gen 2: When GC visits Gen 1 objects and it is not able to clear them it moves them Gen 2.

Generations are created to improve GC performance. The garbage collector will spend more time on Gen 0 objects rather than Gen 1 and Gen 2 thus improving performance.

Note: More the objects in Gen 0, the more your application is stable.

Question 12.
Garbage collector cleans managed code, how do we clean unmanaged code?
Answer:
Garbage collector only claims managed code memory. For unmanaged code, you need to put clean up in destructor / finalize.

Question 13.
But when we create a destructor the performance falls down?
Answer:
Yes, when we define a destructor, the garbage collector does not collect these objects in the first round. It moves them to Gen 1 and then reclaims these objects in the nex+ cycle.

As more objects are created in Gen 1 the performance of the application falls down because more memory is consumed.

Question 14.
So how can we clean unmanaged objects and also maintain performance?
Answer:
We need to follow the below steps:

  • Implement IDisposable interface and implement the Dispose function.
  • In Dispose function calls the “GC . SuppressFinalize” method.
  • At the client-side ensure that the “Dispose” function is called when the object is no more required.

Below goes the code, this is also called “Finalize and Dispose of pattern”. This ensures that your objects are created in Gen 0 rather than Gen 1. “GC. SuppressFinalize” tells the garbage collector to not worry about destructor and destroy the objects in the first call itself.

class clsMyClass: IDisposable
{
-clsMyClass( )
{
// In case the client forgets to call
// Dispose, destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
       if (disposing)
       {
            // Free managed objects.
       }
       // Free unmanaged objects
}
public void Dispose()
{
       Dispose(true);
       // Ensure that the destructor is not called
       GC.SuppressFinalize(this);
     }
}
Note:  Please do go through the videos of “What is IDisposable interface and finalize dispose 
           pattern in GC?” in which we have actually shov</ed how generation performance increases
          by using Finalize and Dispose pattern.

Question 15.
Can we force the garbage collectors to run? (l) Can we force the garbage collectors to run?
Answer:
“System.GC.Collect ( )” forces garbage collector to run. This is not a recommended practice but can be used if situations arise.

Question 16.
What is the difference between finalize and dispose?
Answer:

  • Finalize is a destructor and Dispose is a function that is implemented via the ‘ iDisposable’ interface.
  • Finalize is non-deterministic since it’s called by the garbage collector. Dispose is a function and needs to be called by the client

for clean up. In other Finalize is automatically called by the garbage collector while Dispose needs to be called forcefully.

Note:  As a good practice Finalize and Dispose are used collectively because of the double 
         garbage collector loop. You can talk about this small note. You can also talk about the above two differences.

Question 17.
What is CTS?
Answer:
In .NET there are lots of languages like C#, VB.NET, VF.NET, etc. There can be situations when we want to code in one language to be called in another language. In order to ensure smooth communication between these languages, the most important thing is that they should have a common type system. CTS (Common Types System) ensures that data types defined in two different languages get compiled to a common data type.

So “integer” data type in VB6 and i”int” data type in C++ will be converted to System. int32, which is data type of CTS.

Note: If you know COM programming, you would know how difficult it is to interface the VB6 application 
         with the VC++ application. As the data types of both languages did not have a common ground where 
        they can come and interface, having CTS interfacing is smooth.

Question 18.
What is a CLS (Common Language Specification)?
Answer:
CLS is a subset of CTS. CLS is a specification or set of rules or guidelines. When any programming language adheres to this set of rules it can be consumed by any .NET language.

For instance one of the rules which makes your application CLS non-compliant is when you declare your methods members with the same name and with only case differences in C#. You can try this. Create a simple class in C# with the same name with only case differences and try to consume the same in VB.NET, it will not work.

Question 19.
What is an Assembly?
Answer:
Assembly is a unit of deployments like EXE or a DLL.

Question 20.
What are the different types of Assembly?
Answer:
There are two types of assembly: Private and Public assembly. A private assembly is normally used by a single application and is stored in the application’s directory, or a sub-directory beneath. A shared assembly is stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime.

Shared assemblies are needed when we want the same assembly to be shared by various applications on the same computer.

Question 21.
What is Namespace?
Answer:
Namespace does two basic functionalities:

  • It logically groups classes, for instance, System. Web. UI namespace logically groups Ul-related features like text boxes, list control, etc.
  • In an Object-Oriented world, many times it is possible that programmers will use the same class name. Qualifying NameSpace with class names avoids this collision.

Question 22.
What is the difference between namespace and assembly?
Answer:
Following are the differences between namespace and assembly:

  • Assembly is the physical grouping of logical units, whereas namespace logically groups classes.
  • The namespace can span multiple assemblies while the assembly is a physical unit like EXE, DLL, etc.

Question 23.
What is ILDASM?
Answer:
ILDASM is a simple tool that helps you to view the IL code of a DLL or EXE. In order to view IL code using ILDASM, go to Visual Studio command prompt and run “ILDASM.EXE”. Once ILDASM is running you view the IL code. ‘

Question 24.
What is Manifest?
Assembly metadata is stored in Manifest. Manifest contains metadata that describes the following things:

  • Version of assembly
  • Security identity
  • Scope of the assembly
  • Resolve references to resources and classes

The assembly manifest is stored in the DLL itself.

Question 25.
Where is the version information stored of an assembly?
Answer:
Version information is stored in assembly inside the manifest.

Question 26.
Is versioning applicable to private assemblies?
Answer:
Yes, versioning is applicable to private assemblies also.

Question 27.
What is the use of strong names?
Answer:

Note: This question can also be asked in two different ways: What are weak references and strong 
          references or How do you create a strong name for a .NET assembly

When we talk about the .NET application it has two parts one is the class library or the DLL and the other the consumer like windows Ul, etc., using this DLL.

If the consumer identifies the DLL library by namespace and class names it’s called a weak reference. It’s very much possible in a deployment environment someone can delete the original class library and fake a similar class library with the same class name and namespace name.

A strong name is a unique name that is produced by the combination of the version number, culture information, public key, and digital signature. No one can fake this identity or generate the same name.

So your consumer or Ul will refer to the class library with strong names rather than class and namespace names. In order to create the strong name, right-click on the Class library, click on Properties, click on the Signing* tab, and click on the New menu to generate strong names as shown in Figure 2.1.

Basic .NET Framework Interview Questions in . NET chapter 2 img 1

Question 28.
What is Delay signing?
Answer:
The whole point about strong names is to ensure that the clients (Ul, External components, etc.) who are consuming the DLL knows that the DLL was published from a valid source. This authenticity is verified by using strong names. Strong name protection is good from external hackers but what if your own developers think of doing something mischievous.

That’s why delayed signing helps. The strong name key has two keys: a public key and a private key. You only share the public key with your developers so that they can work seamlessly. The private key is stored in a secured location and when the DLL is about to be deployed on production the key is injected for further security.

Question 30.
What is GAC?
Answer:
GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following situations:

  • If the application has to be shared among several application which is in the same computer.
  • If the assembly has some special security, requirements like only administrators can remove the assembly. If the assembly is private then a simple delete process of the assembly file will remove the assembly.

Question 31.
How to add and remove an assembly from GAC?
Answer:
You can use the ‘GacUtil’ tool which comes with Visual Studio. So to register an assembly into GAC go to “Visual Studio Command Prompt” and type “gacutil -i (assembly name)”, where (assembly name) is the DLL name of the project.

Once you have installed the assembly the DLL can be seen in ‘c: \windows\assemblyV folder.

When we have many DLLs to be deployed we need to create a setup and deployment package using windows installer. So the common way of deploying GAC DLL in production is done by using a windows installer.

Question 32.
If we have two versions of the same assembly in GAC how to we make a choice?
Answer:
When we have two versions of the same assembly in GAC we need to use binding redirect tag and specify the version we want to use in the new version property as shown in the below “app.config” file.

<configuration>
<runtime>
<assemblyBinding xmlns="urn: schemas-microsoft-com: asm.vl">
<dependentAssembly>
<assemblyldentity name="ComputerName" publicKeyToken="cfc68d722cd6al64'' />
<publisherPolicy apply="yes" />
<bindingRedirect oldVersion="l.1.0.0" newVersion="1.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Question 33.
What is Reflection and why we need it?
Answer:
Reflection is needed when you want to determine/inspect the contents of an assembly. For example, look at your Visual Studio Editor IntelliSense, when you type (dot) before any object, it gives you all members of the object. This is possible because of reflection.

Basic .NET Framework Interview Questions in . NET chapter 2 img 2

Reflection also goes one step further; it can also invoke a member which is inspected. For instance, if the reflection detects that there is a method called “GetChanges” in an object as shown in Figure 2.2. We can get a reference to that method instance and invoke the same on runtime.

Basic .NET Framework Interview Questions in . NET chapter 2 img 3

In simple words reflection passes through two steps: “Inspect” and “Invoke” (optional) as shown in Figure 2.3. The “Invoke” process is optional.

Question 34.
How do we implement reflection?
Answer:
Implementing reflection in C# is a two-step process, first, get the “type” of the object and then use the type to browse members like “methods”, “properties”, etc.

Step 1: The first step is to get the type of object. So, for example, you have a DLL called “ClassLibrary1.dll” which has a class called “ClassT’. We can use the “Assembly” class (belongs to System. Reflection namespace) to get a reference to the type of object. Later we can use “Activator. Createlnstance” to create an instance of the class. The “GetTypeO” function helps us to get a reference to the type of object. ,

var myAssembly = Assembly.LoadFile(@"C: \ClassLibraryl.dll");
var myType = myAssembly.GetType("ClassLibraryl.Classl");
dynamic objMyClass = Activator.Createlnstance(myType);
// Get the class type
Type parameterType = objMyClass.GetType( );

Step 2: Once we have referenced the type of the object we can then call “GetMembers” or “GetProperties” to browse through the methods and properties of the class.

// Browse through members
foreach (Memberlnfo objMemberlnfo in parameterType.GetMembers( ))
(Console.WriteLine(objMemberlnfo.Name);}
// Browse through properties.
foreach (Propertylnfo objPropertyInfo in parameterType.GetProperties( ))
{Console.WriteLine(objPropertylnfo.Name);}

In case you want to invoke the member which you have inspected you can use ” invokeMember” to invoke the method. Below is the code for the same.

parameterType.InvokeMember("Display",BindingFlags.Public|
BindingFlags.NonPublic | BindingFlags.InvokeMethod|
BindingFlags.Instance, null, objMyClass, null);

Question 35.
What are the practical uses of reflection?

  • If you are creating an application like Visual Studio editors where you want to show the internal of an object by using IntelliSense.
  • In unit testing sometimes we need to invoke private methods. It checks whether private members are proper or not.
  • Sometimes we would like to dump properties, methods, and assembly references to a file or probably show it on a screen.

Question 36.
What is the use of dynamic keywords?
Answer:
Programming languages can be divided into two categories strongly typed and dynamically typed. Strongly typed languages are those where the checks happen during compile-time while dynamic languages are those where type checks are bypassed during compile-time. In dynamic language object types are known only during runtime and type checks are activated only at runtime.

Basic .NET Framework Interview Questions in . NET chapter 2 img 4

So we would like to take advantage of both the world. Because many times we do not know object type until the code is executed. In other words, we are looking at something like a dynamically statically typed kind of environment. That’s what dynamic keyword helps us with.

If you create a variable using the “dynamic” keyword and if you try to see members of that object you will get a message as shown in Figure 2.5 “This operation will be resolved at runtime”.

Basic .NET Framework Interview Questions in . NET chapter 2 img 5

Now try the below code out. In the below code I have created a dynamic variable that is initialized with string data. And in the second line, I am trying to have fun by trying to execute a numeric incremental operation. So what will happen now?…. think.

dynamic x = “c#”;
x++;

Now, this code will compile successfully. But during runtime, it will throw an exception complaining that the mathematical operations cannot be executed on the variable as it is a string type as shown in Figure 2.6. In other words, during runtime, the dynamic object gets transformed from general data type to specific data type (ex: string for the below code).

Basic .NET Framework Interview Questions in . NET chapter 2 img 6

Question 37.
What are the practical uses of dynamic keywords?
Answer:
One of the biggest practical uses of dynamic keywords is when we operate on MS Office components via Interop.

So for example, if we are accessing Microsoft Excel components without dynamic keywords, you can see how complicated the below code is. Lots of casting happening in the below code, right.

// Before the introduction of dynamic.
Application excelApplication = new ApplicationO;
((Excel.Range)excelApp.Cells[1, l]).Value2 = "Name";
Excel.Range range2008 = (Excel.Range)excelApp.Cells[1, 1];

Now, look at how simple the code becomes by using the dynamic keyword. No casting needed and during runtime type checking also happens.

// After the introduction of dynamic, the access to the Value property and
// the conversion to Excel. The range is handled by the runtime COM binder, dynamic excelApp = new ApplicationO; excelApp.Cells[1, 1].Value = "Name";
Excel.Range range2010 = excelApp.Cells[1, 1];

Question 38.
What is the difference between Reflection and Dynamic?
Answer:

  • Both reflection and dynamic are used when we want to operate on an object during runtime.
  • Reflection is used to inspect metadata (data about data) of an object. It also has the ability to invoke members of an object on runtime.
  • Dynamic is a keyword that was introduced in .NET 4.0. It evaluates object calls during runtime. So until the method calls are made compiler is least bothered if those methods/properties exist or not.
  • Dynamic uses reflection internally. It caches the method calls made thus improving performance to a certain extent.
  • Reflection can invoke both public and private members of an object while dynamic can only invoke public members.
    Below is the detailed comparison Table which shows in which scenario they are suited.
E-mail Address xyz@pqr.com

abc@lmn.com

Email address data starts with some characters followed by”@” and then a “.” And finnaly the domin extension.
Phone number 901-9090-909023

909-999-1202920

Phone number data starts with an international code followed by a region code and then the phone number.

Figure 2.7 shows visually what reflection can do and what dynamic keywords can do.

Basic .NET Framework Interview Questions in . NET chapter 2 img 7

Question 39.
Explain the difference between early binding and late binding.
Answer:
Early binding or early bound means the target methods, properties, and functions are detected and checked during compile-time. If the method/function or property does not exist or has data type issues then the compiler throws an exception during compile-time.

Late binding is the opposite of early binding. Methods, properties, and functions are detected during runtime rather than compile-time. So if the method, function, or property does not exist during runtime application will throw an exception.

Note: In simple words, everything is early bound until you are using reflection or dynamic keyword.

Question 40.
What is the difference between var and dynamic keywords?
Answer:

Note: Comparing VAR and Dynamic keyword is like comparing Apples and oranges. Many 
          people confuse VAR with the variant datatype of VB6 and there’s where the interviewer 
          tries to confuse you. But there is absolutely no connection of var C# keyword with a variant of VB6.

var is early bound (statically checked) while dynamic is late-bound (dynamically evaluated).

Basic .NET Framework Interview Questions in . NET chapter 2 img 8

var keyword looks at your right-hand side data and then y = X. Length; during compile-time, it decides the left-hand side data type. (local variable) string x In other words var keyword just saves you typing a lot of things.

On the other hand, the dynamic keyword is for a completely different purpose. Dynamic objects are evaluated during runtime. For instance in the below code the “Length” property exists or not is evaluated during runtime.

dynamic z = “Dynamic”;
y = z. Length; // Is Length present or not checked during runtime

If for some reason you mistype the “Length” property to “length” (Small “I”) you would end up into a runtime exception as shown in figure 2.9.

Basic .NET Framework Interview Questions in . NET chapter 2 img 9

So in short sentence var does static check while dynamic evaluates and checks during runtime.

Question 41.
Explain term type safety and casting in C#.
Answer:
There are two types of languages one which is type-safe and one which is not. Type safety means preventing type errors. Type error occurs when the data type of one type is assigned to another type unknowingly and we get undesirable results.

For instance, JavaScript is not a type-safe language. In the below code “num” is a numeric variable and “str” is a string. Javascript allows me to do “num + str”, now guess will it do arithmetic or concatenation.

Now the result of the below code is “55” but the important point is the confusion created what kind of operation it will do.

This is happening because JavaScript is not a type-safe language. It allows setting one type of data to the other type without restrictions. ,

<script>
var num = 5; // numeric
var str = "5"; // string
var z = num + str; // arthimetic or concat????
alert(z); // displays "55" .
</script>

C# is a type-safe language. It does not allow one data type to be assigned to another data type. The below code does not allow the “+” operator on different data types.

Basic .NET Framework Interview Questions in . NET chapter 2 img 10

But in certain scenarios, we would like to convert the data type to achieve the given results that’s where we need to do conversion or casting. The next question talks about the same in detail.

Question 42.
Explain casting, implicit conversion, and explicit conversion.
Answer:

Note:  Some interviewers term this conversion as casting and some just prefer to call it as conversion,
          at the end of the day they mean the same thing.

To understand the implicit and explicit conversion of data types first let’s try to understand the typecasting concept. Typecasting is a mechanism where we convert one type of data to another type.

For example, below is a simple code where we want to move the integer (value without decimals) value to a double (value with decimals). When we try to move double data type to integer data typecasting occurs. Casting is also termed conversion.

int i = 100;
doubled = 0;
d = i; // casting

In the above example, there is no loss of data. In other words when we moved 100 integer values to double we get the 100 value as it. This is termed implicit conversion/casting.

Now consider the below code where we are trying to move a double to an integer. In this scenario, in integer, only 100 will be received and decimals will be removed. You can also see I need to explicitly specify that we need to convert into an integer. This is termed explicit conversion.

doubled = 100.23;
int i = 0;
i = (int) d; // this will have 100, 0.23 will truncated.

Question 43.
What are stack and heap?
Answer:
Stack and heap are memory types in an application. Stack memory stores data types like int, double, Boolean, etc., while heaping stores data types like string and objects.

For instance when the below code runs, the first two variables, i.e., “i” and “y” are stored in a stack and the last variable “o” is stored in heap.

void MyFunction()
{
int i = 1; // This is stored in stack,
int y = i; // This is stored in stack,
object o = null; // This is stored in heap.
}
// after this end the stack variable memory space is reclaimed while // the heap memory is reclaimed later by the garbage collector.

Question 44.
What are Value types and Reference types?
Answer:
Value types contain actual data while reference types contain pointers and the pointers point to the actual data. Value types are stored on the stack while reference types are stored on the heap. Value types are your normal data types like int, bool, double and reference types are all objects.

Question 45.
What is the concept of Boxing and Unboxing?
Answer:
When a value type is moved to a reference type it’s called boxing. The vice-versa is termed unboxing.
Below is a sample code of boxing and unboxing where integer data type is converted into an object and then vice versa.
int i = 1 ;
object obj = i; // boxing
int j = (int) obj; // unboxing

Question 46.
How performance is affected due to boxing and unboxing?
Answer:
When boxing and unboxing happens the data needs to jump from stack memory to heap and vice-versa which is a bit of a memory-intensive process. As a good practice avoid boxing and unboxing wherever possible.

Question 47.
How can we avoid boxing and unboxing?
Answer:
The first thing it’s very difficult to avoid boxing and unboxing. For instance most of the time you will move data from Ul objects like text boxes, etc., to business objects and also vice versa which will demand boxing and unboxing. Below are some key points to remember:
  • The first thing is it really necessary to use boxing and unboxing. If it’s unavoidable like moving data from Ul text boxes to internal C# data types, then go for it.
  • Try to see if you can use generics and avoid it.
Question 48.
If we have a class referencing value type, where is the value type stored?
Answer:
The value type will be stored in a heap.
Question 49.
Are static variables stored on a heap or stack?
Answer:
Static variables and even their value types are stored in a heap.
Question 50.
How to prevent my .NET DLL to be decompiled?
Answer:
As per the design, .NET embeds rich metadata inside the executable code using MSIL (Microsoft Intermediate Language). Anyone can easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for .NET which is a third party. Secondly, there are many third-party tools, which make this decompiling process a click away. So anyone can easily look into your assemblies and reverse engineer them back into actual source code and understand some real good logic, which can make it easy to crack your application.
The process by which you can stop this reverse engineering is using “obfuscation”. It is a technique, which will foil the decompilers. Many third parties (XenoCode, Demeanor for .NET) provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with Visual Studio.NET.
Note: We leave this as homework to the reader’s compile, a DLL obfuscates it using
        “Dotfuscator Community Edition” which comes with Visual Studio.NET, and 
         try viewing the same using ILDASM.
Question 51.
What is the difference between Convert.ToString and .ToString ( ) methods?
Answer:
To understand what the above question means see the code given.
int i =0;
MessageBox.Show(i.ToString( ));
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i . ToString ()” or “Convert.ToString” so what is the difference. The basic difference between them is the “Convert” function which handles NULLs while “i .ToString ( )” does not do. It will throw a NULL referencing exception error. So as a good coding practice using “Convert” is always safe.
Question 52.
What is the difference between String and string?
Answer:
“String” is an alias (the same thing called with different names) of “string”. So technically both the below code statements will give the same output.
String s = “C# interview questions”;
or
string s = “C# interview questions”;
In the same way, there are aliases for other C# data types as shown below.
  • object: System.Object
  • string: System. String
  • bool: System.Boolean
  • byte: System.Byte
  • byte: System. SByte
  • short: System. Inti6
  • ushort: System.UIntl6
  • int: System. Int32
  • uint: System.UInt32
  • long; System. Int64
  • ulong: System.UInt64
  • float: System. Single
Basic .NET Framework Interview Questions in . NET chapter 2 img 11
  • double: System.Double
  • decimal: System.Decimal
  • char: System. char
Question 53.
So when both mean the same thing why are they different?
Answer:
When we talk about .NET there are two different aspects one there is .NET framework and the other there are languages (C#, VB.NET, etc.) which use that Framework as shown in Figure 2.11.
Basic .NET Framework Interview Questions in . NET chapter 2 img 12
Question 54.
So when to use “String” and “string”?
Answer:
The first thing to avoid confusion use one of them consistently. But from best practices perspective when you do variable declaration it’s good to use “string” (small “s”) and when you are using it as a class name then “String” (capital “S”) is preferred.
In the below code a variable is declared on the left-hand side using “string”. On the right-hand side, a method is called so “String” is more sensible.
string s = String. ToUpper( ) ;
Question 55.
How can we handle exceptions in .NET?
Answer:
Exceptions are handled by the “System. Exception” base class. If you want to raise an error from a source you need to create the Exception object with the below code snippet.
throw new Exception (“Customer code cannot be more than 10'’);
Once the exception is raised, and if you want to catch the same you need to use the try-catch block as shown below.
try
{
    // This section will have the code which
   // which can throw exceptions.
}
catch(Exception e)
{
    // Handle what you want to
   // do with the exception
   label.text = e.Message;
}

Question 56.

How can I know from which source the exception occurred?
Answer:
“System. Exception. stack trace” allows you to identify series of call which lead to this exception.
Question 57.
What if we do not catch the exception?
Answer:
If you do not catch the error, .NET Framework will handle the same and you will get a message box as shown in Figure 2.13.
Basic .NET Framework Interview Questions in . NET chapter 2 img 13
Question 58.
What are system-level exceptions and application-level exceptions?
Answer:
Exceptions that are thrown by .NET Framework are called system exceptions. These errors are non-recoverable or fatal errors like ArgumentOutOfRangeException, indecent OfRangeException, StackOverflowException, etc.
Application exceptions are custom exceptions created for the application. Application exceptions are created by deriving from the “ApplicationException” class as shown below. You can then create the object of the below exception, throw the same from the code and catch the same on the client-side.
public class MyOwnException: ApplicationException
{
private string messageDetails = String.Empty;
public DateTime ErrorTimeStamp {get; set;}
public string CauseOfError {get; set;}
public MyOwnException(){ }
public MyOwnException(string message,
string cause, DateTime time)
{
      messageDetails = message;
      CauseOfError - cause;
      ErrorTimeStamp = time;
}
// Override the Exception. Message property.
public override string Message
{
     get
    {
            return string.Format("This is my own error message");
     }
   }
}

Question 59.

Can two catch blocks be executed?
Answer:
No, once the proper catch section is executed the control goes to the ‘finally’ block. So there is no chance by which multiple catch blocks will ‘execute’.
Question 60.
What are different types of collections in .NET?
Answer:
There are five important collections in .NET Arrays, Lists, Hashtable, stacks and queues.
Question 61.
What is the difference between ArrayList and List?
Answer:
  • Arrays are fixed in size while ArrayList is resizable.
  • Arrays are strongly typed, in other words, when you create an array it can store only one data type data. ArrayList can store any datatype.
Question 62.
Is ArrayList faster or Array?
Answer:
ArrayList takes any data type which leads to boxing and unboxing. As arrays are strongly typed they do not do boxing and unboxing. So arrays are faster as compared to ArrayList.
// Array definition
int[ ] str = new int[10];
// Arraylist definition
ArrayList MyList = new ArrayList( );

Question 63.

What are hashtable collections?
Answer:
In ArrayList or array if we have to access any data we need to use the internal index id generated by the ArrayList collection. For instance, the below code snippet shows how the internal id is used to fetch data from ArrayList.

In actual scenarios, we hardly remember internal id’s generated by collection we would like to fetch the data by using some application-defined key. There’s where hashtable comes into the picture.

string str = MyList[1]. ToString( );

Hashtable helps to locate data using keys as shown below. When we add data to hashtable it also has a provision where we can add keys with the data. This key will help us to fetch data later using a key rather than using internal indexes id’s generated by collections.

objHashtable.Add(“p001 ”, “MyData”);

This key is converted in to numeric hash value which is mapped with the key for the quick lookup.

Question 64.
What are Queues and stack collection?
Answer:
Queues are collection which helps us to add object and retrieve them in the manner they were added. In other word queues helps us to achieve the First In First Out (FIFO) collection behavior.

Stack collection helps us to achieve First In Last Out (FILO) behavior.

Question 65.
Can you explain generics in .NET?
Answer:
Generics help to separate logic and data type to increase reusability. In other words, you can create a class whose data type can be defined on runtime.

For instance below is a simple class “Class1” with a “Compare” function created using generics. You can see how the unknown data type is put in greater than and less than a symbol. Even the Compare method has the unknown data type attached.

public Class Classl<UNNKOWDATATYPE>
{
      public bool Compare(UNNKOWDATATYPE vl, UNNKOWDATATYPE v2 )
     {
             if (v1.Equals(v2))
             {
                    return true;
             }
             else
             {
                   return false;
             }
      }
}

During runtime, you can define the data type as shown in the below code snippet.

Class1<int> obj = new Class1<int>( );
bool b = obj.Compareme(1, 2); // This compares numeric
Class1<string> obj1 = new Classl<string>( );
bool bl = obj1.Compareme("shiv", "shiv"); // This does string comparison

Question 66.
Explain generic constraints and when should we use them.
Answer:
Generic’s helps to decouple logic from the data type. But many times some logic is very specific to specific data types.

public class CompareNumeric<UNNKOWDATATYPE>
{
public bool Compareme(UNNKOWDATATYPE v1, UNNKOWDATATYPE v2)
{
          if (v1>v2)
          {return true;}
          else
          {return false;}
  }
}

The example above is a simple generic class that does a comparison if one number is greater than another number. Now the greater and less than comparison is very specific to numeric data types. This kind of comparison cannot be done on non-numeric types like strings.

So if some uses the classes with “int” type it is perfectly valid.

CompareNumeric<int> obj = new CompareNumeric<int>( );
bool boolgreater = obj.Compare(10, 20);

If someone uses it with the “double” data type again perfectly valid.

CompareNumeric<double> obj = new CompareNumeric<double>( );
bool boolgreater = obj. Compare(100.23, 20.45);

But using string data type with this logic will lead undesirable results. So we would like to restrict or put a constraint on what kind of types can be attached to a generic class this is achieved by using “generic constraints”.

CompareNumeric<string> obj = new CompareNumeric<string>( );
bool boolgreater = obj.Compare(“interview’\ “interviewer”);

A generic type can be restricted by specifying data type using the “where” keyword after the generic class as shown in the code given below. Now if any client tries to attach “string” data type with the below class it will not allow, thus avoiding undesirable results.

public class CompareNumeric<UNNKOWDATATYPE> where UNNKOWDATATYPE; int, double
{
}

Question 67.
Can you explain the concept of the generic collection?
Answer:
Arraylist, Stack, and Queues provide collections that are not type safe. This leads two problems first it is not type-safe, and second it leads to boxing and unboxing.

By using generics we can have type safety, and also we can avoid boxing and unboxing. Below is a simple code snippet that shows a strongly typed list of type integers and strings.

List<int> obj; .
obj.add(l); // you can only add integers to this list
List<string> obj;
obj.add("shiv"); // you can only add string to this list

Question 68.
What is the difference between dictionary and hashtable?
Answer:
A Dictionary collection is a generic collection equivalent to a hashtable. Hashtable allows you to add keys and values of any type (i.e., objects). This leads to two problems one is boxing and unboxing issues and second it’s not strongly typed.

// Creates a strongly typed dictionary with integer key and value
// pair
Dictionary<int, int> obj = new Dictionarycint, int>( );
//We can only add integer value and key to the dictionary collection
Obj.Add(123, 550);

Question 69.
What is the generic equivalent for ArrayList, stack, queues and hashtable?
Answer:
Below are the listed generic equivalents for each of them:

  • ArrayList generic equivalent is List<int>.
  • Stack generic equivalent is stack<int>.
  • Queue generic equivalent is Queue<int>.
  • Hashtable generic equivalent is Dictionarycint, int>.

Question 70.
What is the use of (Enumerable, (Collection, Mist, and IDictionary?
Answer:

Basic .NET Framework Interview Questions in . NET chapter 2 img 14

The above four entities are nothing but interfaces implemented by collections as shown in Figure 2.14:

IEnumerable: All collection classes use this interface and it helps to iterate through all the collection elements.

ICollection: This interface has the count property and it is implemented by all collection elements.

IList: This interface allows random access, insertion, and deletion into the collection. It is implemented by ArrayList.

IDictionary: This interface is implemented by hashtable and dictionary.

Question 71.
Differentiate between |Enumerable and |Queryable.
Answer:
The first important point to remember is “IQueryable” interface is inherited from “IEnumerable”, so whatever “IEnumerable” can do, “IQueryable” can also do.

There are many differences but let us discuss the one big difference. The “IQueryable” interface is useful when your collection is loaded using LINQ or Entity Framework, and you want to apply a filter on the collection.

Basic .NET Framework Interview Questions in . NET chapter 2 img 15

Consider the code given below which uses ‘IEnumerable” with entity framework. It is using a “Where” filter to get records whose “Empid” is “2”.

EmpEntities ent = new EmpEntities( );
IEnumerable<Employee> emp = ent.Employees;
IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>( );

The filter is executed on the client side where the “iEnumerable” interface is coded. In other words, all the data is fetched from the database and then at the client, it scans and gets the record with “Empid” is “2” as shown in Figure 2.16.

Basic .NET Framework Interview Questions in . NET chapter 2 img 16

But now see the below code we have changed “IEnumerable” to “IQueryable”.

EmpEntities ent = new EmpEntities( );
IQueryable<Employee> emp = ent.Employees;
IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>( );

In this case the filter is applied on the database using the “SQL” query. So the client sends a request and on the server-side a selected query is filtered on the database and only necessary data is returned as shown in Figure 2.17

Basic .NET Framework Interview Questions in . NET chapter 2 img 17

So the difference between “IQueryable” and “IEnumerable” is the process of how the filter logic is executed. One executes on the client-side and the other executes on the database.

So if you working with only in-memory data collection “IEnumerable” is a good choice but if you want to query data collection which is connected with database “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL (Structured Query Language).

Question 72.
What is Code Access Security (CAS)?
Answer:
CAS is the part of the .NET security model which determines whether or not a particular code is allowed to run and what kind of resources can the code access.

Question 73.
So how does CAS actually work?
Answer:
It is a four step process as shown in Figure 2.18. These steps are as follows:

  • The first evidence is gathered about the assembly. In other words from where did this assembly come, who is the publisher, etc.
  • Depending on evidences the assembly is assigned to a code group. In other words what rights does the assembly depending on the evidence gathered.
  • Depending on the code group security rights are allocated.
  • Using the security rights the assembly is run within those rights.

Basic .NET Framework Interview Questions in . NET chapter 2 img 18

Question 74.
Is CAS supported in .NET 4.0?
Answer:
CAS is deprecated in .NET 4.0 and two major changes are brought in:

  • Permission granting is no more the work of CAS; it’s now the work of the hosting model. In other words, CAS is disabled in .NET 4.0 by default. The host will decide what rights to be given to the .NET assembly.
  • A new security model, i.e., security transparent model is introduced. The security transparent model puts code into separate compartments/boxes as per the risk associated. If you know a code can do something wrong you can compartmentalize the code as ‘Security transparent’ and if you have a code that you trust you can box them into ‘Security critical’.

Question 75.
What is sandboxing?
Answer:
If you have wanted to execute an untrusted third party DLL (Dynamic Link Library), you can create your own ‘app domain and assign permission sets so that your third party DLL runs under a control environment.

Question 76.
How can we create a Windows service using .NET?
Answer:
Windows Services are long-running processes that run at the background. It has the ability to start automatically when the computer boots and also can be manually paused, stopped, or even restarted.
Following are the steps to create a service:
Create a project of type “Windows Service”.

Basic .NET Framework Interview Questions in . NET chapter 2 img 19

If you see, the class created it is automatically inherited from “System. ServiceProcess. ServiceBase” .
You can override the following events provided by service and write your custom code. All three main events can be used that is Start, Stop and Continue.

protected override void OnStart(string[ ] args)
{
}
protected override void OnStop( )
{
}
protected override void OnContinue( )
{
}

Now to install the service you need to do run the lnstallUtil.exe.

Install Util <Project Path>\BIN\MyNewService.exe

Question 77.
What are serialization and deserialization in .NET?
Answer:
Serialization is a process where we can convert an object state in to the stream of bytes as shown in Figure 2.20. This stream can then be persisted in a file, database, or sent over a network, etc. Deserialization is just vice-versa of serialization where we convert a stream of bytes back to the original object.

Basic .NET Framework Interview Questions in . NET chapter 2 img 20

Below is a sample code of how to serialize and deserialize an object.
Let’s first start with serialization.

Step 1: Create the object and put some values

// Serialization
Customer obj = new Customer( ); // Create object
obj.CustomerCode = 123; // Set some values

Step 2: Create the file where the object is saved.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

IFormatter i = new BinaryFormatter( ); // Use the binary formatter
Stream stream = new Fi1eStrearn(“MyFi1e.txt” , FileMode.Create,
FileAccess.Write, FileShare.None); // Give file name

Step 3: Use Serialize method to save it to hard disk

i.Serialize(stream, o); // write it to the file
stream.Close( ); // Close the stream

Let’s also see a simple example of deserialization.

Step 1: Read the file

// Deserialization
IFormatter formatter = new BinaryFormatter( ); // Use binary formatter Stream stream = new FileStream(“MyFile.txt”, FileMode.Open, FileAccess.Read, FileShare.Read); // read the file

Step 2: Recreate it back to the original object.

Customer obj = (Customer)formatter.Deserialize(stream); // take data back to object
stream.Close( ); // close the stream

If you want to save as XML or any other content type use the appropriate formatter.

Question 78.
Can you mention some scenarios where we can use serialization?
Answer:
Below are some scenarios where serialization is needed:

  • Passing .NET objects across network. For example, .NET remoting, Web services or WCF services use serialization internally.
  • Copy and paste .NET objects on the Clipboard.
  • Saving the old state of the object and reverting back when needed. For example, when the user hits the Cancel button you would like to revert back to the previous state.

Question 79.
When should we use binary serialization as compared to XML serialization?
Answer:

  • Binary is smaller in size, so faster to send across the network and also faster to process.
  • XML is more verbose but easy to understand and human-readable. But due to the XML structure it is complex to parse and can impact performance.
Note: Many people answer that XML serialization should be used when you have different 
         platforms and binary serialization should be used when you have same platforms. But this 
         answer is actually not right as we have lot of binary serialization methodologies like ASN 
         (Abstract Syntax Notation), protbuf which are cross platform and widely accepted. 
         So the important difference is that one is XML which readable by eyes and the binary is not.

Question 80.
What is regular expression?
Answer:
Regular expression is a pattern matching technique. Most of the data follow patterns. Some examples of common data patterns are shown in the Table

Table

By using regular expression you can represent these data patterns and utilize the same for validations and manipulation of data.

In order to use regular expression we need to create the object of “Regex” class and pass the pattern to Regex. For example, the below pattern represents data pattern of 10 character length which can be any small characters from a to z.

Regex obj = new Regex(“[a-z]{10}”);

Once you have specified the pattern as described in the previous step you can then use the “isMatch” function to check if the data matches with the pattern.

if(obj.IsMatch("shivkoirala") )
{
      // proper data
}
else
{
    // improper data
}
Note: In some rare cases we have seen interviewers ask to write down Regex patterns. 
         So we would suggest to see the video “Explain Regex.”provided on the DVD which will 
         help you to write down any Regex pattern easily.

Question 81.
What is timeout support in Regex (regular expression)?
Answer:
This is a new feature of .NET 4.5. Some of the regular expressions are very complex and they can take lot of time to be evaluated.
For instance below is a simple regular expression.

var regEx = new Regex(@ ”h(\d+)+$”, RegexOptions. Singleline);

If someone inputs a huge number as shown in the below code snippet. It will take more than a minute to resolve the expression leading to a lot of loads on the application. So we would like to give a time out on the expression. So if the validation takes more than a specific interval we would like the application to give up and move ahead.

var match - regEx. Match(“123453109839109283090492309480329489812093809x’);

In .NET 4.5 we can now provide the timeout value as parameter on the constructor. For instance in the below code we have provided 2 seconds timeout on the Regex (regular expression). So if it exceeds more than 2 second “RegexMatchTimeOutException” will occur.

try
{
       var regEx = new Regex(A(\d+)+$", RegexOptions.Singleline,
       TimeSpan.FromSeconds(2));
       var match = regEx.Match
       ("123453109839109283090492309480329489812093809x");
}
catch (RegexMatchTimeOutException ex)
{
       Console.WriteLine("Regex Timeout");
}

Question 82.
Can you explain the concept of “Short Circuiting”?
Answer:
Short circuiting occurs when you do logical operations like ‘AND’ and ‘OR’.
“When we use short circuit operators only necessary evaluation is done rather than full evaluation.”
Let us try to understand the above sentence with a proper example. Consider a simple “AND” condition code as shown below. Please note we have only one operator in the below code.

if (Condition1 & Condition2)
{
}

In the above case “Condition2″ will be evaluated even if “Condition1” is “false”. Now if you think logically, it does not make sense to evaluate “Condition 2”, if “Condition 1” is false. It is a AND condition right? So if the first condition is false it means the complete AND condition is false and it makes no sense to evaluate “Condition2”.

There’s where we can use short circuit operator “&&”. For the below code “Condition 2” will be evaluated only when “Condition 1” is true.

if(Condition1 && Condition2)
{
}

The same applies for “OR” operation. For the below code (please note its only single pipe (” j “).) “Condition2” will be evaluated even if “Conditionl” is “true”. If you think logically we do not need to evaluate “Condition2” if “Conditionl” is “true”.

if(Condition1 | Condition2)
{
}

So if we change the same to double pipe (” | | “), i.e., implement short circuit operators as shown in the below code, “Condition2” will be evaluated only if “Conditionl” is “false”.

if(Condition1 || Condition2)
{
}

Question 83.
What is the difference between “Typeof” and “GetType”?
Answer:
Both “Typeof” and “GetType” help you to get the type. The difference is from where the information is extracted. “Typeof” gets the type from a class while “GetType” gets type from an object.

Question 84.
Will the following C# code compile?
Answer:
double db1 = 109.22;
int i = dbl;

No, the above code will give an error. Double size is larger than “int” so an implicit conversion will not take place. For that we need to do explicit conversion. In the below code we have done an explicit conversion.

double dbl = 109.22;
int i =(int) dbl; // this is explicit conversion / casting

Also note after explicit conversion we will have data loss. In variable ” i” we will get “109” value, the decimal values will be eliminated.

Question 85.
Explain the use of IComparable in C#.
Answer:
“|Comparable” interface helps to implement custom sorting for collections in C#. Let us try to understand the same concept with a simple C# example. For instance let’s say you have a list collection of people names as shown in the below code.

List<string> Peoples = new List<string>( );
Peoples.Add("Shiv");
Peoples.Add("Raju");
Peoples.Add("Sukesh");
Peoples.Add("Ajay");
foreach (string str in Peoples)
{
Console.WriteLine(str) ;
}

Now if you run the above program you will see that we have not applied sorting on the collection. It displays data as they were inserted.

Shiv
Raju
Sukesh
Ajay

But now if you call “Peoples. Sort ()” method on the collection you will get the following sorted output on the “name” value in ascending order.

Ajay
Raju
Shiv
Sukesh

But now let’s say that we need the person’s age also to be added in the list with the person name value. So logically you will create a, “Person” class with “Name” and “Age” properties as shown in the code below.

class Person
{
     private string _Name;
     public string Name
    {
          get { return _Name; }
          set { _Name = value; }
    }
    private int _Age;
    public int Age
   {
             get { return _Age; }
             set { _Age = value; }
   }
}

Once you create the class you would create an object of the Person class and add it to the list collection as shovyn in the below code snippet.

class Program
{
      static void Main(string[ ] args)
      {
            List<Person> Peoples = new List<Person>( );
            Peoples.Add(Createperson("Shiv", 20));
            Peoples.Add(Createperson("Raju", 20));
            Peoples.Add(Createperson("Sukesh", 30));
            Peoples.Add(Createperson("Ajay", 40)) ;
            Peoples.Sort( );
            foreach (Person obj in Peoples)
            {
                 Console.WriteLine(obj.Name + " " + obj.Age);
            }
     }
     static Person Createperson(string Name, int Age)
     {
           Person obj = new Person( );
           obj.Name = Name;
           obj.Age = Age;
           return”'obj ;
     }
}

But if you try to call the “Sort” method in the given List, there would be confusion like sort() method works on values given for “Name” or “Age”.

Basic .NET Framework Interview Questions in . NET chapter 2 img 21

If you run the application it will throw up the below exception text. The exception .text needs specific direction on how the sorting should work. This direction can be provided by using “incomparable” interface as shown in Figure 2.21.

Unhandled Exception: System. InvalidOperationException: Failed to compare two elements in the array. —> System.
ArgumentException: At least one object must implement |Comparable.

So in order to show a proper direction for the sort logic we need to implement ” incomparable” interface as shown in the code below. The logic of “Sort” method needs to be defined in the “CompareTo” method.

class Person: IComparable<Person>
{
      private string _Name;
      public string Name
      {
            get { return _Name; }
            set { _Name = value; }
      }
      private int _Age;
      public int Age
      {
           get { return _Age; }
           set { _Age = value; }
     }
     public int CompareTo(Person other)
     {
          if (other,Age == this.Age)
          {
                return this.Name.CompareTo(other.Name);
          }
          else
          {
               return other.Age.CompareTo(this.Age);
          }
     }
}

You can see in the “CompareTo” method that we have applied the logic saying if the “Age” value is same then sort by using the “Name” value else use “Age” value. If you run the application you would get the following output. You can see for “40” and “30” have been sorted on the basis of “Age” but for the remaining people the age is same so “Name” values have been sorted.

Loki 40
Sukesh 30
Ajay 20
Madan 20
Raju 20
Shiv 20

So “icomparable” interface customized sorting logic on the given list.

Question 86.
What is difference between Icomparable and IComparer?
Answer:

Pre-requisite: Please read “Explain the use of Icomparable in C#. ”, before reading this answer.

“Icomparable” interface helps you to implement a default sort implementation for the collection. But what if we want to sort using multiple criteria. For those instances “icomparable” has a limitation.

For example, if we want to sort the list by “Name” under some situation or sort by “Age” under some other situation we need to implement “IComparer” interface.

So the first step is to create different classes for each sort criteria. These classes will implement “IComparer” interface and will have sorting logic defined in the “Compare” method. You can see we have two different classes defined “CompareByName” and “CompareByAge”. One compares on the basis of “Name” and the other on the basis of “Name”.

class CompareByName: IComparer<Person>
{
       public int Compare(Person x( Person y)
       {
             return string.Compare(x.Name, y.Name);
       }
}
class CompareByAge: IComparer<Person>
{
       public int Compare(Person x, Person y)
       {
             if (x.Age > y.Age) return 1;
             if (x.Age < y.Age) return -1;
             return 0;
       }
}

If you see the logic for “CompareByName” it is simple. It uses the string comparison to evaluate the “Name” value sorting. But when we talk about numeric comparison there are three possible outputs Greater than, Less than or Equal. So if you see “CompareByAge” class it returns three values 1 (Greater than), -1 (Less than) and 0 (for Equal to).

Now that we have created the separate logics we can now invoke the ” Peoples” list by passing the class object. So for example if we want to sort by name, you will use the below code snippet.

Peoples.Sort(new CompareByName( ));

The output of the above code is nothing but alphabetically sorted data.

Ajay 20
Loki 40
Madan 20
Raju 20
Shiv 20
Sukesh 30

If you invoke the Sort ( ) method of the list by using the Age logic it will throw an output sorted on Age value.

Peoples. Sort (new CompareByAge( ));

Ajay 20
Raju 20
Shiv 20
Madan 20
Sukesh 30
Loki 40

So the difference is really default internal implementation or customizable external implementation. When we use “incomparable” we can have only one default sorting logic and that logic goes inside the collection itself. For “icomparator” the logic is outside the collection, in other words more extensible and the collection is not disturbed as shown in Figure 2.22.

Basic .NET Framework Interview Questions in . NET chapter 2 img 22

Question 87.
Can you explain Lazy Loading?
Answer:
Lazy loading is a concept where we delay the loading of the object unit the point where we need it. Putting in simple words on demand object loading rather than loading the objects unnecessarily.

For example, consider the below example where we have a simple “Customer” class and this “Customer” class has many “Order” objects inside it. Have a close look at the constructor of the “Customer” class. When the “Customer” object is created it also loads the “Order” object at that moment. So even if we need or do not need the address object, it is still loaded.

But how about just loading the “Customer” object initially and then on demand basis load the “Order” object,

public class Customer
{
        private List<Order> _Orders= null;
        ...
        ...
        public Customer( )
        {
               _CustomerName = "Shiv";
               _Orders = LoadOrders() ; // Loads the address object even though 
               //not needed
       }
       private List<Order> LoadOrders( )
       {
              List<Order> temp = new List<Order>( );
              Order o = new Order( );
              o.OrderNumber = "ord1001";
              temp.Add(o);
              o = new Order();
              o.OrderNumber = "ord1002";
              temp.Add(o);
              return temp;
      }
}

So let’s consider you have client code which consumes the “Customer” class as shown below. So when the “Customer” object is created no “Order” objects should be loaded at that moment. But as soon as the “foreach” loop runs you would like to load the “Order” object at that point (on demand object loading).

Customer o = new Customer(); // Address object not loaded Console.WriteLine(o.CustomerName);
foreach (Order ol in o.Orders) // Load address object only at this moment
{
Console.WriteLine(ol.OrderNumber);
}

Question 88.
So how do we implement “Lazy Loading”?
Answer:
So for the above example if we want to implement lazy loading we will need to make the following changes:

  • Remove the “Order” object loading from the constructor.
  • In the “Order” get property, load the “Order” object only if it is not loaded.
public class Customer
{
     private List<Order> _Orders= null;
     ...
     ...
public Customer( )
{
          _CustomerName = "Shiv";
}
public List<Order> Orders
{
    get
   {
         if (_Orders == null)
         {
              _Orders = LoadOrders( );
         }
         return _Orders;
     }
   }
}

Now if you run the client code and halt your debugger just before the “for each” loop runs over the “Order” object, you can see the “Order” object is null (i.e., not loaded) as shown in Figure 2.23. But as soon as the “ForEach” loop runs over the “Order” object, it creates the “Order” object collection.

Basic .NET Framework Interview Questions in . NET chapter 2 img 23

Question 89.
Are there any readymade objects in .NET by which we can implement lazy loading?
Answer:
In .NET we have “Lazy<T>” class which provides automatic support for lazy loading. So let’s say if you want to implement “Lazyo” in the above code we need to implement two steps for the same:
Create the object of orders using the “Lazy” generic class.

private Lazy<List<Order>> _Orders= null;

Attach this Lazyo object with the method which will help us load the order’s data.

Orders = new Lazy<List<Order>>(() => LoadOrders( ));

Now as soon as any client makes a call to the “_Orders” object, it will call the “LoadOrders” method to load the data.

You will get the “List<Orders>” data in the “Value” property.

public List<Order> Orders
{
      get
      {
          return _Orders.Value;
      }
}

Below goes the full code for the same

public class Customer
{
    private Lazy<List<Order>> _Orders= null;
    public List<Order> Orders
{
    get
   {
            return _Orders.Value;
   }
}
public Customer( )
{
        // Makes a database trip
        _CustomerName = "Shiv";
        _Orders = new Lazy<List<Order>>(( ) => LoadOrders( ));
   }
}

Question 90.
What are the advantages/disadvantages of lazy loading?
Answer:
Below are the advantages of lazy loading:

  • Minimizes start-up time of the application.
  • The application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.

The disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not. So must be there is a slight decrease in performance.
But the advantages are far more than the disadvantages.

FYI: The opposite of Lazy loading is Eager loading. So in eager loading we load the 
       all the objects in memory as soon as the object is created.

Question 91.
What is the difference between “is” and “as” keyword?
Answer:
“is” keyword is useful to check if objects are compatible with a type. For instance in the below code we are checking if “ocust” object is a type of “Customer” class.

object ocust = new Customer( );
if (ocust is Customer)
{

“as” keyword helps to do conversion from one type to other type. For instance in the below code we are converting object to a string data type. If the “as” keyword is not able to typecast it returns NULL

object o = “interview”;
string str = o as string;

Question 92.
What is the use of the “Yield” keyword?
Answer:
“Yield helps you to provide custom stateful iteration over .NET collections.”
There are two scenarios where “yield” keyword is useful:

  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.

Scenario 1: Customized iteration through a collection
Let’s try to understand what customized iteration means with an example. Consider the below code.

Let say we have a simple list called as “MyList” which has collection of five consecutive numeric values 1,2, 3, 4 and 5 as shown in Figure 2.24. This list is browsed/iterated from console application from within static void Main () method.

For now let’s visualize the “Main ( ) ” method as a caller. So the caller, i.e., “Main ( ) ” method calls the list and displays the items inside it. Simple…till now ;-).

static List<int> MyList = new List<int>( );
static void FillValues( )
{
          MyList.Add(1);
          MyList.Add(2);
          MyList.Add(3);
          MyList.Add(4);
          MyList.Add(5);
}
static void Main(string[ ] args) // Caller
{
         FillValues( ); // Fills the list with 5 values
         foreach (int i in MyList) // Browses through the list
         {
                Console.WriteLine(i);
         }
         Console.ReadLine( );
}

Basic .NET Framework Interview Questions in . NET chapter 2 img 24

Now let me complicate this situation lets say the caller only wants values greater than “3” from the collection. So the obvious thing as a C# developer we will create a function as shown below. This function ‘will be temporary collection of given values.
In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.

static IEnumerable<int> FilterWithoutYield( )
{
       List<int> temp = new List<int>( );
       foreach (int i in MyList)
       {
            if (i > 3)
            {
                temp.Add(i);
            }
      }
      return temp;
}

Basic .NET Framework Interview Questions in . NET chapter 2 img 25

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple as shown in Figure 2.25. This where “yield” keyword comes to help. Below is a sample code how we have used yield.

“yield” keyword will return back the control to the caller, the caller will do its work and re-enter the function from where it had left and continue iteration from that point onwards. In other words “yield” keyword moves control of the program to and from between caller and the collection.

static IEnumerable<int> FilterWithYield()
{
        foreach (int i in MyList)
        {
             if (i > 3) yield return i;
        }
}

So for the above code, following are steps how the control will flow between caller and collection. You can also see the pictorial representation in the Figure 2.26.

Basic .NET Framework Interview Questions in . NET chapter 2 img 26

• Step 1: Caller calls the function to iterate for number’s greater than 3.

• Step 2: Inside the function the for loop runs from 1 to 2, from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.

• Step 3: Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.

Scenario 2: Stateful iteration

Now let us add more complications to the above scenario. Let’s say we want to display running total of the above collection. What do I mean?.
In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable.
So we start with “1” the running total is “1 ”, we move to value “2” the running total is previous value “1 ” plus current value “2”, i.e., “3” and so on.

Basic .NET Framework Interview Questions in . NET chapter 2 img 27

Figure 2.27 shows the pictorial representation of the running total looks like.

In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller (i.e., console application). So the function now becomes something as shown below. The “runningtotal” variable will have the old value every time the caller re-enters the function.

static IEnumerable<int> RunningTotal( )
{
       int runningtotal=0;
       int index=0;
       foreach(int i in MyList)
       {
              index = index + 1;
              if(index==l)
              {
                   runningtotal = i;
              }
              else
              {
                  runningtotal = i + runningtotal;
              }
              yield return (runningtotal);
       }
}

Following is the caller code.

foreach (int i in RunningTotal( ))
{
Console.WriteLine(i);
}
Console.ReadLine( );

Basic .NET Framework Interview Questions in . NET chapter 2 img 28

The output of the above program is shown in Figure 2.28.

Question 93.
What is the difference between “==” and .Equals()?
Answer:
When we create any object there are two parts to the object one is the content and the other is reference to that content as shown in Figure 2.29.
So for example if you create an object as shown in below code:
1. “.NET Interview questions” is the content.
2. “o” is the reference to that content.

object o = “.NET Interview questions”;

Basic .NET Framework Interview Questions in . NET chapter 2 img 29

“==” compares if the object references are same while ” . Equals ( )” compares if the contents are same as shown in Figure 2.31.
So if you run the below code both “==” and “.Equals ( ) ” return true because content as well as references are same as shown in Figure 2.30.

Basic .NET Framework Interview Questions in . NET chapter 2 img 30

object o = “.NET Interview questions”;
object o1 = o;
Console.WriteLine(o == o1) ;
Console.WriteLine(o.Equals(o1));
Console.ReadLine();

True
True

Now consider the below code where we have the same content but they point towards different instances. So if you run the below code “==” will return false and “.EqualsO” will return true.

Basic .NET Framework Interview Questions in . NET chapter 2 img 31

object o = “.NET Interview questions”;
object ol = new string(“.NET Interview questions”.ToCharArray( ));
Console.WriteLine(o == o1);
Console.WriteLine(o.Equals(o1)) ;
Console.ReadLine();

False
True

When you are using string data type it always does the content comparison. In other words, you either use “. Equals ()” or “==” it always does the content comparison.

Question 94.
What’s the difference between catch with parameter and catch without parameter?
Answer:
First, let’s try to understand this question:

catch(Exception e)
{
...
}
VS
Catch
{
...
}

For this interview question, many people answer, “The second one will cause compile error”. But both the codes will work properly. Actually, from .NET 2.0, there is no difference. But in the initial versions of .NET, i.e., prior 2.0 some of the exceptions thrown by some COM components did not translate to “Exception” compatible objects.

From .NET 2.0 both codes will execute properly and there is no difference between them internally. Both catches will handle all kinds of exceptions.

After 2.0 a catch which does have any code written in it gives a warning as shown in Figure 2.23. So many developers mark this as a difference.

IMAGE

But you can always overcome this issue by not putting a variable as shown in the code below.

catch (Exception)
{
}

Question 95.
What are attributes and why do we need it?
Answer:
“Attribute is nothing but a piece of information”.
This information can be attached to your method, class, namespace, assembly, etc. Attributes are part of your code this makes developers’ life easier as it can see the information right up front in the code while it is calling the method or accessing the class and take actions accordingly.

For instance below is a simple class where “Method” is decorated by the “Obsolete” attribute. Attributes are defined by using the ” []” symbol. So when developers starting coding in this class they are alerted that “Method” is obsolete and code should be now written in “NewMethodl”.

public class Class1
{
[Obsolete]
public void Method1 ( )
{
}
public void NewMethod1( )
{
}
}

In the same way, if somebody is trying to create an object of “Class1” it gets an alert in the tooltip as shown in the below code snippet that “Method1” is obsolete and it should use “NewMethodl” as shown in Figure 2.33.

So in short Attributes are nothing small piece of information which is embedded declaratively in the code itself which developers can see upfront.

Basic .NET Framework Interview Questions in . NET chapter 2 img 33

In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

[Obsolete("Please use NewMethodl")]
public void Methodl( )
{
}

If you want to be a bit strict and do not developers to use that method, you can pass “true” to the “Obsolete” attribute as shown in the below code.

[Obsolete("Please use NewMethodl", true)]
public void Methodl()
{
}

If you want to be a bit strict and do not developers to use that method, you can pass “true” to the “Obsolete” attribute as shown in the below code.

[Obsolete("Please use NewMethodl", true)]
public void Methodl()
{
}

Now in case, developers try to make a call to “Method1” they will get errors and not just a simple warning.

Basic .NET Framework Interview Questions in . NET chapter 2 img 34

Question 96.
How can we create custom Attributes?
Answer:
The “Obsolete” attribute which we discussed at the top is a readymade attribute. To create custom attributes you need to inherit from the Attribute class. Below is a simple “HelpAttribute” which has a “HelpText” property.

class HelpAttribute: Attribute
{
public string HelpText { get; set; }
}
"HelpAttribute" is applied to the "Customer" as shown in the code below. Now developers who see this class, see the information right in the front of their eyes.
[Help(HelpText="This is a class")]
class Customer
{
private string _CustomerCode;
[Help(HelpText = "This is a property")]
public string CustomerCode
{
get { return _CustomerCode; }
set { _CustomerCode = value; }
}
[Help(HelpText = "This is a method")]
public void Add( )
{
}
}

Question 97.
How can we mark a method as deprecated?
Answer:
Refer to the previous answer.

Basic .NET Framework Interview Questions in . NET chapter 2 img 35

Question 98.
What is the difference between Build Solution, Rebuild Solution, and Clean Solution menus?
Answer:
Build solution menu: This will perform an incremental build. In other words, it will only build code files that have changed. If they have not changed those files will not touch.
Rebuild solution menu: This will delete all current compiled files (i.e., exe and dll’s) and i will build everything from scratch, irrespective if there is a code change in the file or not.

Basic .NET Framework Interview Questions in . NET chapter 2 img 36

Clean solution menu: This menu will delete all compiled files (i.e., EXE’s and DLL’s) from “bin” / “obj” directory.

Now if you read the above three points I have discussed you can conclude that:

Rebuild = Clean + Build

So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build”, what is the difference?

The difference is the way they build and clean sequence happens for every project. Let’s say if your solution has two projects “Projl” and “Proj2”.
If you do a rebuild it will take “Projl”, clean (delete) the compiled files for “Projl” and build it. After that it will take the second project “Proj2”, clean compiled files for “Proj2” and compile “Proj2”.

But if you do a “Clean” and “Build”. It will first delete all compiled files for “Proj1” and “Proj2” and then it will build “Projl” first followed by “Proj2”.

The below image explains the same in a more visual format.

Basic .NET Framework Interview Questions in . NET chapter 2 img 37

Question 99.
What is the difference between i++ and ++i?
Answer:
i++: In this scenario first the value is assigned and then increment happens. In the below code snippet first the value of “i” is assigned to ” j ” and then “i” is incremented.

Basic .NET Framework Interview Questions in . NET chapter 2 img 38

++i: In this scenario first the increment is done and then the value is assigned. In the below code snippet value of ” j ” is 2 and the value of “i” is also “2”.

If you visualize it in a pictorial manner below is how it looks like. So i++ is a postfix, it first assigns and then increments. While + + i is a prefix, it first increments and then assigns the value.

Basic .NET Framework Interview Questions in . NET chapter 2 img 39

Below is some sample codes where postfix and prefix fit in.

while (i < 5) //evaluates conditional statement
{
//some logic
++i; //increments i
}
while (i++ < 5) //evaluates conditional statement with i value before increment
{
//some logic
}
int i = 0;
int [ ] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[—i]; //temp is 1234

Question 100.
When should we use “??” (NULL Coalescing operator)?
Answer:
“??” is a null coalescing operator. If you see the English meaning of coalescing it says “consolidate together”. Coalescing operator returns the first non-null value from a chain. For example, below is a simple coalescing code that chains four strings.

So if “str1” is null it will try “str2”, if “str2″ is null it will try “str3” and so on until it finds a string with a non-null value.

string final =str1?? str2?? str3?? str4;

Question 101.
Explain the need for NULLABLE types.
Answer:
It is difficult to assign null directly for value types like int, bool, double, etc. By using nullable types you can set value types as null. To create a nullable type we need to put ” ?” before the data type as shown in the below code.

int? num1 = null;

Question 102.
In what scenario’s we will use NULLABLE types?
Answer:
The biggest user of nullable types is when you are reading values from the database. The database is one place where there is high possibility of columns having nulls. So when we want to read those values into value types nullable types make it easy as shown in the below code.

while (oreader.Read( ))
{
int? salary = oreader["Salary"] as int? ;
}

Question 103.
What is the benefit of coalescing?
Answer:
You do not need to write long if condition as shown below.

if (str1 != null)
{
       final = str1;
}
else
{
       if (str2 != null)
       {
           final = str2;
       }
       else
       {
          if (str3 != null)
          {
              final = str3;
          }
          else
          {
             if (str4 != null)
             {
                     final = str4;
             }
        }
    }
}

 

What is conditional operator and it’s syntax in C

What is conditional operator and it’s syntax in C

Conditional Operator is a powerful Operator which can be used to implement if-then-else type of logic. This operator is also known as ternary operator and it takes three arguments in the following form.

Conditional_Expression ? Expression_One : Expression_Two;

Ternary Operator will execute Expression_One if Conditional_Expression is true, otherwise it execute Expression_Two.
Ternary Operator is similar to if-else decision block as it evaluates only one code block depending on the result of Conditional_Expression.
For Example

int X = 25;
int Y = (X > 20 ? 1 : 2);

As X > 20, So after above statement Y’s value becomes 1.

What is assignment operators in C

Assignment Operators of C is used to assign a value to a variable. “=” is called simple arithmetic operator of C, it assigns values from right side operands(R value) to left side operand (L value). The general syntax of assignment operator is:

variable_name = expression;

For Example
value = 1234;
value = 4/2;

What is the bitwise operator in C

C is a middle level language, it support many operations which can be performed in assembly language like operations on bits. Bitwise operators performs bit-by-bit operations on operands. There are six bitwise operators supported by C programming language.

  • Bitwise OR Operator(|)
  • Bitwise AND Operator(&)
  • NOT Operator(One’s Complement)(~)
  • Bitwise Exclusive OR Operator(^)
  • Right Shift Operator(>>)
  • Left Shift Operator(<<)

Bitwise Operators can only be applied on char and integer operands. We cannot use bitwise operators with float, double, long double, void and other user define complex data types.