ASP.NET interview question pdf – ASP.NET Interview Questions and Answers for Freshers

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

C#.NET Interview Questions and Answers for Freshers Pdf Free Download

Question 1.
What is ASP.Net?
Answer:
It is a framework developed by Microsoft on which we can develop new generation websites using web forms(aspx), MVC, HTML, Javascript, CSS, etc. Its successor of Microsoft Active Server Pages(ASP). Currently, there is ASP.NET 4.0, which is used to develop websites. There are various page extensions provided by Microsoft that are being used for website development. Eg: aspx, asmx, ascx, ashx, cs, vb, HTML, XML etc.

Question 2.
What are the advantages of ASP.NET?
Answer:
ASP.Net is the next generation of ASP technology platform. It is superior to ASP in the following ways:

  • Highly Scalable
  • Compiled Code
  • User Authentication
  • Language Support
  • Third-party control
  • Configuration and Deployment are easy,
  • Object and Page caching
  • Strict coding requirements

Question 3.
What’s the use of Response.Output.Write( )?
Answer:
We can write formatted output using Response.Output.Write( ).

Question 4.
In which event of page cycle is the ViewState available?
Answer:
After the lnit( ) and before the Page_Load().

Question 5.
What is the difference between Server. Transfer and Response. Redirect?
Answer:
In Server. Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. The client url history list or current url Server does not update in the case of the Server. Transfer.

Response. Redirect is used to redirect the user’s browser to another page or site. It performs a trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

Question 6.
From which base class all Web Forms are inherited?
Answer:
Page class.

Question 7.
What are the different validators in ASP.NET?
Answer:

  1. Required Field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

Question 8.
Which validator control do you use if you need to make sure the values in two different controls matched?
Answer:
Compare Validator control.

Question 9.
What is the concept of Postback in ASP.NET?
Answer:
Postback is a request which is sent from a client to the server from the same page user is working with. There is an HTTP POST request mechanism in ASP.NET. It posts a complete page back to the server to refresh the whole page.

Question 10.
What is the use of “isPostBack” property?
Answer:
The “IsPostBack” property of the page object is used to check that the page is posted back or not.

Question 11.
How do you identify that the Page is PostBack?
Answer:
There is a property named “IsPostBack” property in Post object, which can be checked to know that the page is posted back.

Question 12.
What is ViewState?
Answer:
ViewState is used to retain the state of server-side objects between page post-backs.

Question 13.
Where the ViewState is stored after the page postback?
Answer:
ViewState is stored in a hidden field on the page on the client-side. ViewState is transported to the client and back to the server and is not stored on the server or any other external source.

Question 14.
How long the items in ViewState exists?
Answer:
They exist for the life of the current page.

Question 15.
What are the different Session state management options available in ASP.NET?
Answer:

  1. In-Process
  2. Out-of-Process.

In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server. The external server may be either a SQL Server or a State Server. All objects stored in session are required to be serializable for Out-of-Process state management.

Question 16.
How you can add an event handler?
Answer:
Using the Attributes property of server side control, e.g.
btnSubmit.Attributes.Add(“onMouseOver,,;,,JavascriptCode( );”)

Question 17.
What is caching?

Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.

Question 18.
what are the main requirements for caching?
Answer:

  • By caching the response, your request is served by the response already stored in memory.
  • You must be very careful while choosing the items to cache because Caching incurs overhead.
  • A frequently used web form which data doesn’t frequently change is good for caching.
  • A cached web form freezes form?s server-side content, and changes to that content do not appear until the cache is refreshed.

Question 19.
What are the different types of caching?ASP.NET has 3 kinds of caching :
Answer:

  1. Output Caching,
  2. Fragment Caching,
  3. Data Caching.

Question 20.
Which type if caching will be used if we want to cache the portion of a page instead of whole page?
Answer:
Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code:
<%@ OutputCache Duration=”120″ VaryByParam=”CategorylD;SelectedlD”%>

Question 21.
List the events in page life cycle.
Answer:

  1. Page_Prelnit
  2. Page_lnit
  3. Page_lnitComplete
  4. Page_PreLoad
  5. Page_Load
  6. Page_LoadComplete
  7. Page_PreRender
  8. Render

Question 22.
Can we have a web application running without web.Config file?
Answer:
Yes

Question 23.
What is the difference between ASP.NET Webforms and ASP.NET MVC?
Answer:
ASP.NET Webforms uses the page controller approach for rendering layout. In this approach, every page has its controller.
On the other hand, ASP.NET MVC uses the Front Controller approach. In this approach, there is a common controller for all pages.

Question 24.
Is it possible to create a web application with both webforms and MVC?
Answer:
Yes. We have to include the below MVC assembly references in the web forms application to create a hybrid application.

System.Web.Mvc 

System.Web.Razor


System. ComponentModel.DataAnnotations

Question 25.
Can we add code files of different languages in the App_Code folder?
Answer:
No. The code files must be in the same language to be kept in the App_code folder.

Question 26.
What is Protected Configuration?
Answer:
It is a feature used to secure connection string information.

Question 27.
Write code to send e-mail from an ASP.NET application?
Answer:

MailMessage mailMess = new MailMessage ( );
mailMess.From = "abc@gmail.com
             ";
mailMess.To = "xyz@gmail.com";
mailMess.Subject = "Test email";
mailMess.Body = "Hi This is a test mail.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (mailMess);

MailMessage and SmtpMail are classes defined System.Web.Mail namespace.

Question 28.
How can we prevent browser from caching an ASPX page?
Answer:
We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property:

Response.Cache.SetNoStore ( );
Response.Write (DateTime.Now.ToLongTimeString ());

Question 29.
What is the good practice to implement validations in aspx page?
Answer:
Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.

Question 30.
What is the use of Global.asax file?
Answer:
The Global.asax file is used to execute the application-level events and sets application- level variables.

Question 31.
What is event bubbling?
Answer:
When child control sends events to parent, it is termed as event bubbling. Server controls like Data Grid, Data List, and Repeater can have other child controls inside them.

Question 32.
What are the event handlers that we can have in Global.asax file?
Answer:
Application Events: Application_Start, Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache

Session Events: Session_Start,Session_End

Question 33.
Which protocol is used to call a Web service?
Answer:
HTTP Protocol

Question 34.
Can we have multiple web config files for an asp.net application?
Answer:
Yes.

Question 35.
What is the difference between web config and machine config?
Answer:
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

Question 36.
Explain role based security ?
Answer:
Role-based security is used in almost all organization, and the Role-based security assigns certain privileges to each role.

  • Each user is assigned a particular role from the list.
  • Privileges as per role restrict the user’s actions on the system and ensure that a user can do only what he is permitted to do on the system.
<AUTHORIZATION>< authorization >
< allow roles="Domain_Name\Administrators" / > < !-- Allow Administrators in domain. 
 — >
< deny users-'*" />                             < !-- Deny anyone else. -- >
< /authorization >

Question 37.
What is Cross Page Posting?
Answer:
When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted.

Question 38.
How can we apply Themes to an asp.net application?
Answer:
We can specify the theme in web.config file. Below is the code example to apply the theme:

<configuration> 

<system.web> 

<pages theme="Windows7" />

 </system.web> 

</configuration>

Question 39.
What is RedirectPermanent in ASP.Net?
Answer:
RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.

Question 40.
What is MVC?
Answer:
MVC is a framework used to create web applications. The web application base builds on Model-View-Controller pattern which separates the application logic from Ul, and the input and events from the user will be controlled by the Controller.

Question 41.
Explain the working of passport authentication.
Answer:
First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page

Question 42.
What are the advantages of Passport authentication?
Answer:
All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.

Users can maintain his/ her information in a single location.

Question 43.
What are the asp.net Security Controls?
Answer:

  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
  • <asp:Loginl\lame>: Allows you to display the name of the logged-in user
  • <asp:LoginStatus>: Displays whether the user is authenticated or not
  • <asp:LoginView>: Provides various login views depending on the selected template
  • <asp:PasswordRecovery>: email the users their lost password

Question 44.
How do you register JavaScript for webcontrols ?
Answer:
We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method.

Question 45.
In which event are the controls fully loaded?
Answer:
Page load event.

Question 46.
what is boxing and unboxing?
Answer:
Boxing is assigning a value type to reference type variable. Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.

Question 47.
Differentiate strong typing and weak typing
Answer:
In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.

Question 48.
How we can force all the validation controls to run?
Answer:
The Page.Validate( ) method is used to force all the validation controls to run and to perform validation.

Question 49.
List all templates of the Repeater control.
Answer:

  • ItemTemplate
  • AlternatingltemTemplate
  • SeparatorTemplate
  • HeaderTemplate
  • FooterTemplate

Question 50.
List the major built-in objects in ASP.NET?
Answer:

  • Application
  • Request
  • Response
  • Server
  • Session
  • Context

Question 51.
What is the appSettings Section in the web.config file?
Answer:
The appSettings block in the web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified Connectionstring section is used throughout the project for database connection:

<emxconfiguration>
<appSettings>
<add key-'ConnectionString" value="server=local; pwd=password; database=default" /> 
</appSettings></em>

Question 52.
Which data type does the RangeValidator control support?
Answer:
The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.

Question 53.
What is the difference between an HtmllnputCheckBox control and an HtmllnputRadioButton control?
Answer:
In HtmllnputCheckBoxcontrol, multiple item selection is possible whereas in HtmllnputRadioButton controls, we can select only single item from the group of items.

Question 54.
Which namespaces are necessary to create a localized application?
Answer:
System.Globalization
System.Resources

Question 55.
What is a cookie?
Answer:
A Cookie is a small piece of information which is stored at the client side. There are two types of cookie:

  • Session/Temporary Cookie: valid for a single session
  • Persistent Cookie: valid for multiple session

Question 56.
What is the default timeout for a cookie?
Answer:
30 minutes.

Question 57.
How would you turn off cookies on a page of a website?
Answer:
You have to follow the procedures given below:

  • Use the “Cookie.Discard” property,
  • It gets or sets the discard flag set by the server.
  • When set to true, this property instructs the client application not to save the Cookie on the hard disk of the user at the end of the session.

Question 58.
What are the different types of cookies in ASP.NET?
Answer:
Session Cookie – Resides on the client machine for a single session until the user does not log out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.

Question 59.
What is the file extension of web service?
Answer:
Web services have file extension .asmx..

Question 60.
What are the components of ADO.NET?
Answer:
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

Question 61.
What is the difference between ExecuteScalar and ExecuteNonQuery?
Answer:
ExecuteScalar returns output value where as ExecuteNonQuery ctoes not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

Question 62.
What is IIS?
Answer:
IIS stands for Internet Information Services. It is created by Microsoft to provide Internet-based services to ASP.NET Web applications.

Question 63.
What is the usage of IIS?
Answer:
Following are the main usage of IIS:

  • IIS is used to make your computer to work as a Web server and provides the functionality to develop and deploy Web applications on the server,
  • IIS handles the request and response cycle on the Web server,
  • IIS also offers the services of SMTP and Frontpage server extensions.
  • The SMTP is used to send emails and use Frontpage server extensions to get the dynamic features of IIS, such as form handler.

Question 64.
What is a multilingual website?
Answer:
If a website provides content in many languages, it is known as a multilingual website. It contains multiple copies of its content and other resources, such as date and time, in different languages.

Question 65.
What is the parent class of all web server control?
Answer:
System. Web. Ul.Control class

Question 66.
What is the difference between the GET method () and POST method ()?
Answer:
GetMethod

Data is affixed to the URL.
Data is not secured.
Data transmission is faster in this method.
It is a single call system.
Only a limited amount of data can be sent.
It is a default method for many browsers.

PostMethod

Data is not affixed to the URL Data is secured.
Data transmission is comparatively slow
It is a two call system
A large amount of data can be sent
It is not set as default. It should be explicitly specified

Question 67.
What is the difference between session object and application object?
Answer:
The session object is used to maintain the session of each user. A session id is generated if a user enters in the application and when the user leaves the application, the session id is automatically deleted.
On the other hand, the application object is used to store the information and access variables from any page in the application.
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 68.
What is the difference between trace and debug?
Answer:
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 69.
What is the difference between client-side and server-side validations in WebPages?
Answer:
The client-side validation happens at the client’s side with the help of JavaScript and VBScript. This validation has occurred before the Web page is sent to the server. The server-side validation happens at the server side.

Question 70.
What is the difference between file-based dependency and key-based dependency?
Answer:
File-based dependency: File-based dependency facilitates you to save the dependency on a file in a disk.
Key-based dependency: In key-based dependency, you depend on another cached item.

Question 71.
What is the difference between globalization and localization?
Answer:
Globalization: Globalization is a technique to identify the part of a Web application that is different for different languages and separate it out from the web application.

Localization: In localization, you try to configure a Web application so that it can be supported for a specific language or locale.

Question 72.
What is the difference between a page theme and a global theme?
Answer:
Page Theme: The page theme is applied to particular web pages of the project. It is stored inside a subfolder of the App_Themes folder.
Global Theme: The Global theme is applied to all the web applications on the web server. It is stored inside the Themes folder on a Web server.

Question 73.
What is the difference between early binding and late binding?
Answer:
Early Binding: In early binding, a non-virtual method is called which is decided at a compile time.
Late Binding: In late binding, a virtual method is called which is decided at runtime.

Question 74.
What is the difference between server-side scripting and client-side scripting?
Answer:
Server-side scripting: In server-side scripting, all the script are executed by the server and interpreted as needed.

Client-side scripting: In client-side scripting, the script will be executed immediately in the browser such as form field validation, email validation, etc. The client-side scripting is usually carried out in VBScript or JavaScript.

Question 75.
How to sign out from forms authentication?
Answer:
FormsAuthentication.Signout() method is used to sign out from forms authentication.

Question 76.
How to display validation messages in one control?
Answer:
By the help of ValidationSummary control, we can display all validation messages in one control.

Question 77.
What is the difference between authentication and authorization?
Answer:
Authentication is a process of identifying user whereas authorization is used to check the access rights of an identified user.

Question 78.
Which object encapsulates state or data of a user?
Answer:
Session object.

Question 79.
What are the differences between the Response.Write() and Response.Output.Write()?
Answer:
Response.Write( ) is used for normal output whereas Response.Output.Write() is used for formatted output.

Question 80.
Define the types of configuration files.
Answer:
There are two types of configuration files:

  • Application Level config = Web.config.
  • Machine Level config = Machine.config.

Question 81.
What is the difference between Web config and Machine config files?
Answer:
Web config file is specific to web application whereas Machine config file is specific to machine or server.
There can be multiple web config files in an application but only one machine config file.

Question 82.
What are the HTML server controls in ASP.NET?
Answer:

  • HTML server controls are just like HTML elements that we use on HTML pages.
  • HTML server controls are used to expose properties and events for use.
  • To make these controls programmatically accessible, we specify that the HTML controls act as a server control by adding the runat=Mserver” attribute.

Java swing interview questions – Abstract Windows Toolkit (AWT) Interview Questions in Java

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

Abstract Windows Toolkit (AWT) Interview Questions in Java

Question 1.
What is meant by controls and what are the different types of controls in AWT?
Answer:
Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

Question 2.
What is the difference between choice and list?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A-List may be displayed in such a way that several List items are visible and it supports the selection of one or more list items.

Question 3.
What is the difference between scrollbar and scrollpane?
Answer:
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 4.
What is a layout manager and what are the different types of layout managers available in java.awt?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.

Question 5.
How are the elements of different layouts organized?
Answer:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West)and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid.
However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 6.
Which containers use a Border layout as their default layout?
Answer:
Window, Frame, and Dialog classes use a BorderLayout as their layout.

Question 7.
Which containers use a Flow layout as, their default layout?
Answer:
Panel and Applet classes use the FlowLayout as their default layout.

Question 8.
Why the container does not support multiple layout managers?
Answer:
because when u r using a particular layout manager it useful frame for work you can use a grid bag layout for this purpose.

Question 9.
What is clipping?
Answer:
Clipping is the process of confining paint operations to a limited area or shape.

Question 10.
What is meant by controls and what are the different types of controls in AWT?
Answer:
Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

Question 11.
What is the difference between choice and list?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A-List may be displayed in such a way that several List items are visible and it supports the selection of one or more list items.

Question 12.
What is the difference between scrollbar and scrollpane?
Answer:
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 13.
What is a layout manager and what are the different types of layout managers available in java.awt?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.

Question 14.
What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default layout manager for the panel and the panel subclasses?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available in java.awt is:

• FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.

• BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

• CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

• GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.

• GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub-classes is FlowLayout.

Question 15.
Which containers use a Border layout as their default layout?
Answer:
Window, Frame, and Dialog classes use a BorderLayout as their layout.

Question 16.
Which containers use a Flow layout as their default layout?
Answer:
Panel and Applet classes use the FlowLayout as their default layout.

Question 17.
Assume that g is an object belonging to the Graphics class. What image would be produced by the following commands? Draw a picture as part of your answer.
g;setColor(Color.gray);
g.fiIlRect(0,0,40,40);
g.fillRect(50,50,0,0);
g.setColor(Color.black);
g.fill0val(50,0,40,40);
g.fill0val(0,50,40,40);
Answer:
The method “g.fillRect(x,y,w,h)” draw a solid rectangle with its upper left corner at the point (x,y). The other two parameters, w, and h, give the width and height of the rectangle. In the second line “g.fillRect(50,50,0,0)” doesn’t produce any image at all, since the width and height are specified as zero. The method “g.fillOval(x,y,w,h)” draw a solid oval that just fits inside the rectangle with upper. left corner at (x,y) and with width w and height h. So, the picture produced contains one gray square and two black circles, arranged like this:
(Note: I actually meant the second fine to be “g.fillRect(50,50,40,40).” Without this typo, the picture would have another gray square.)

Question 18.
What is the use of the window class?
Answer:
The window class can be used to create a plain, bare-bones window that does not have a border or menu. The Window class can also be used to display introduction or welcome screens.

Question 19.
What are the benefits of Swing over AWT?
Answer:
Swing components are lightweight. We can have a pluggable look & feel feature that shows us how they appear on other platforms. We can add images to Swing components. We have toolbars and tooltips in Swing.

Question 20.
Where the CardLayout is used?
Answer:
Card Layout is used where we need to have a bunch of panels or frames one laying over another. It is replaced by TabbedPane in Swing.

Question 21.
What is the difference between Grid and GridbagLayout?
Answer:
In Grid layout, the size of each grid is constant whereas in GridbagLayout grid size can Vareid.

Question 22.
How will you add a panel to a Frame?
Answer:
Frame.add(panel,BorderLayout.NORTH) or Frame.add(panel,’’North”).

Question 23.
What is the use of the window class?
Answer:
The window class can be used to create a plain, bare-bones window that does not have a border or menu. The Window class can also be used to display introduction or welcome screens.

Question 24.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

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

Question 26.
For which statements does it make sense to use a label?
Answer:
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

Question 27.
Which TextComponent method is used to set a TextComponent to the read-only state?
Answer:
setEditable( )

Question 28.
How are the elements of a CardLayout organized?
Answer:
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

Question 29.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

Question 30.
What is the difference between the paint( ) and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 31.
Which class is the immediate superclass of the Container class?
Answer:
Component

Question 32.
How can the Checkbox class be used to create a radio button?
Answer:
By associating Checkbox objects with a CheckboxGroup.

Question 33.
Name four Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 34.
What Checkbox method allows you to tell if a Checkbox is checked?
Answer:
getState( )

Question 35.
How are the elements of a GridLayout organized?
Answer:
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

Question 36.
Which Component subclass is used for drawing and painting?
Answer:
Canvas

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

Question 38.
What is Double Buffering?
Answer:
Double Buffering is a technique used to achieve smooth animations in Canvases or Panels. It is memory and CPU-consuming but is unavoidable as soon as you want to animate something. This technique is not applicable for native components like Buttons, Lists, etc… Since the redisplay is handled by the underlying toolkits (Motif or MsWin).

To handle double buffering, one must first draw the widget’s contents in an off¬screen image and then transfer the contents of the image to the visible window.

class DoubleBufferedcanvas extends Canvas {

    public void update(Graphics g) {
    Graphics offgc;
    Image offscreen = null;
    Dimension d = size( );

    // create the offscreen buffer and associated Graphics
    offscreen = createimage(d.width, d.height);
    offgc = off screen. getGraphics( );
    //clear the exposed area
    offgc.setColor(getBackground( ));
    offgc.fillRect(0, 0, d.width, d.height);
    offgc.setColor(getForeground( ));
    // do normal redraw
    paint(offgc);
    // transfer offscreen to window
    g.drawimage(offscreen, 0, 0, this);
   }
}

This method has one major drawback: it copies the whole buffer each time an update is required. This may consume a lot of time and CPU for a large window Hopefully, graphics contains a definition of the area that has to be redrawn: it is called clip region. The region, in Java Graphics, has two meanings:

  1. It tells which part needs to be drawn
  2. It clips drawing orders inside this area that means if you draw outside the clip region, nothing will appear.

Using clip regions, we can define an optimized version of the DoubleBufferedCanvas:

class OptimizedDoubleBufferedCanvas extends canvas {

   public void update(Graphics g) {
   Graphics offgc;
   Image offscreen = null;
   Rectangle box = g.getclipRect( );

   // create the offscreen buffer and associated Graphics
   offscreen = createimagefbox.width, box.height);
   offgc = offscreen.getGraphics( ));
   // clear the exposed area
   offgc.setcolor(getBackg round( ));
   offgc.fillRect(0, 0, box.width, box.height);
   offgc.setcolor(getForeground( ));
   // do normal redraw
   offgc.translateC-box.x, -box.y);
   paint(offgc);
   // transfer offscreen to window
   g.drawlmage(offscreen, box.x, box.y, this);
   }
}

Question 39.
What is the preferred size of a component?
Answer:
The preferred size of a component is the minimum component size that will allow the component to display normally.

Question 40.
What method is used to specify a container’s layout?
Answer:
The setLayout( ) method is used to specify a container’s layout.

Question 41.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and Applet classes use the FlowLayout as their default layout.

Question 42.
Name Component subclasses that support painting.
Answer:
The Canvas, Frame, Panel, and Applet classes support painting.

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

Question 44.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 45.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

Question 46.
What do heavy-weight components mean?
Answer:
Heavyweight components like Abstract Window Toolkit (AWT), depending on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavyweight.

Question 47.
How are the elements of a GridBagLayout organized?
Answer:
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 48.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems

Question 49.
What is the difference between the paint( ) and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 50.
Name Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 51.
What is the difference between a Scrollbar and a ScrollPane?
Answer:
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Question 52.
What is a Container in a GUI?
Answer:
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

Question 53.
How to add a menu shortcut to menu items?
Answer:
If you have a button instance called the about the button, you may add a menu shortcut by calling the about button.setMnemonic(A.’), so the user may be able to use Alt+A to click the button.

Question 54.
What is the difference between Swing and AWT components?
Answer:
AWT components are heavy-weight, whereas Swing components are lightweight. Heavyweight components depend on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Question 55.
What is meant by controls and what are the different types of controls?
Answer:
Controls are components that allow a user to interact with your application. The AWT supports the following types of controls:
Labels, Pushbuttons, Checkboxes, Choice lists, Lists, Scroll bars, Text components These controls are subclasses of Component.

Question 56.
How can we get all public methods of an object dynamically?
Answer:
By using
get methods( ): It returns an array of method objects corresponding to the methods of this class.
getFields( ): It returns an array of Filed objects corresponding to the Fields(variables) of this class.
getConstructors( ): It returns an array of constructor objects corresponding to public constructors of this class.

Question 57.
What is the SubClass of Text component Class?
Answer:
TextField and TextArea

Question 58.
Which method of the Component class is used to set the position and the size of a component?
Answer:
setBounds( )

Question 59.
Which TextComponent method is used to set A TextComponent to the read¬only state?
Answer:
setEditable( )

Question 60.
How can the Checkbox class be used to create a radio button?
Answer:
By associating Checkbox objects with a CheckboxGroup.

Question 61.
What Checkbox method allows you to tell if a Checkbox is checked?
Answer:
getState( )

Question 62.
Which Component method is used to access a component’s immediate Container?
Answer:
getParent( )

Question 63.
What methods are used to get and set the text label displayed by a Button object?
Answer:
getLabel( ) and setLabel( )

Question 64.
What is the difference between a Choice and a List?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.
A-List may be displayed in such a way that several List items are visible. A-List supports the selection of one or more List items.

Question 65.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 66.
What is the difference between a Scrollbar and a Scrollpane?
Answer:
A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 67.
Which Component subclass is used for drawing and painting?
Answer:
Canvas.

Question 68.
Which method is used to set the text of a Label object?
Answer:
setText( )

Question 69.
Which method will cause a Frame to be displayed?
Answer:

a) . show( )
b) . setVisible( )

Question 70.
All the component classes and container classes are derived from
class.
Answer:
Object.

Question 71.
Which method of the container class can be used to add components to a Panel?
Answer:
add ( ) method.

Question 72.
What are the subclasses of the Container class?
Answer:
The Container class has three major subclasses. They are:
Window, Panel, ScrollPane

Question 73.
Can the Choice component allow multiple selections?
Answer:
No

Question 74.
Which components are used to get text input from the user?
Answer:
TextField and TextArea.

Question 75.
Which object is needed to group Checkboxes to make them exclusive?
Answer:
CheckboxGroup.

Question 76.
What are the types of Checkboxes and what is the difference between them?
Answer:
Java supports two types of Checkboxes. They are:
Exclusive and Non-exclusive.
In the case of exclusive Checkboxes, only one among a group of items can be selected at a time. If an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called Radio buttons.
The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.

Question 77.
What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default layout manager for the panel and the panel subclasses?
Answer:
A layout manager is an object that is used to organize components in a container.

Question 78.
What are the different layouts available in java.awt :
Answer:
FlowLayout, BorderLayout, CardLayout, GridLayout, GridBag Layout. The default Layout Manager of Panel and Panel sub classes is FlowLayout”.

Question 79.
Can I exert control over the size and placement of components in my interface?
Answer:
Yes.

Question 80.
Can I add the same component to more than one container?
Answer:
No. Adding a component to a container automatically removes it from any previous parent (container).

Question 81.
How do I specify where a window is to be placed?
Answer:
Use setBounds, setSize, or setLocation methods to implement this.
setBounds(int x, int y, int width, int height)
setBounds(Rectangle r)
setSize(int width, int height)
setSize(Dimension d)
setLocation(int x, int y)
setLocation(Point p)

Question 82.
How can we create a borderless window?
Answer:
Create an instance of the Window class, give it a size, and show it on the screen.
Ex. Frame obj =…………………..
Window WA = new Window(obj);
WA.setLayout(new FlowLayoutO);
WA.add(new Button(“OK”));
WA.getBounds(50,50,200,200);
WA.show( );

Question 83.
Can I create a non-resizable window? If so, how?
Answer:
Yes. By using setResizable( ) method in class Frame.

Question 84.
What is the default Layout Manager for the Window and Window subclasses (Frame, Dialog)?
Answer:
BorderLayout( )

Question 85.
Which containers use a BorderLayout as their default layout?
Answer:
The Window, Frame, and Dialog classes use a BorderLayout as their default layout.

Question 86.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and the Applet classes use the FlowLayout as their default layout.

Question 87.
What is the preferred size of a component?
Answer:
The preferred size of a component size will allow the component to display normally.

Question 88.
Which method is a method to set the layout of a container?
Answer:
setLayout( )

Question 89.
Which method returns the preferred size of a component?
Answer:
getPreferredSize( )

Question 90.
Which layout should you use to organize the components of a container in a tabular form?
Answer:
GridLayout

Question 91.
What are the default layouts for an applet, a frame, and a panel?
Answer:
For an applet and a panel, Flow layout is the default layout, whereas Border layout is the default layout for a frame.

Question 92.
How can you change the current layout manager for a container?
Answer:
By using setLayout( ) method.

Question 93.
Which is the default layout for Applet?
Answer:
The default layout manager for an Applet is FlowLayout, and The FlowLayout manager attempts to honor the preferred size of any components.

Question 94.
Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu?
Answer:
itemStateChanged method.

Question 95.
Which is a dual state menu item?
Answer:
CheckboxMenuItem.

Question 96.
Which container may contain a menu bar?
Answer:
Frame

Question 97.
What is the difference between a Menultem and a CheckboxMenuItem?
Answer:
The CheckboxMenuItem class extends the Menultem class to support a menu item that may be checked or unchecked.

Question 98.
What is the correct ordering for the import, class, and package declarations when found in a single file?
Answer:
package, import, class

Question 99.
What is the parameter specification for the public static void main method?
Answer:

  1. String args [ ]
  2. String [ ] args

Question 100.
What is the sweep and paint algorithm?
Answer:
The painting algorithm takes as input a source image and a list of brush sizes, sweep algo is that it computes the arrangement of n lines in the plane … a correct algorithm,

Question 101.
What are the component and container classes?
Answer:
A component is a graphical object. A few examples of components are Button, Canvas, Checkbox, Choice, etc.

Question 102.
Explain the purpose of invalidating and validate methods.
Answer:
The invalidate method is called a side effect of adding or deleting some component. Calling invalidates ( ) is however the first step of processing a COMPONENTJtESIZED event.

Question 103.
What are AWT peers? When are peers created and destroyed?
Answer:
A Component is associated with a standard AWT button object, a peer object (hidden button object internal to the native GUI), and an interfacing button object constructed per the native GUI.

Question 104.
Show with an example the usage of the FileDialog object.
Answer:
class FileDialog extends from Dialog class. It is used to display a dialog window from which the user can select a file.

Question 105.
Explain the purposes of the component’s request focus method.
Answer:
The purpose of the request focus( ) is to get the focus on the particular component and also on the window that contains the component.

Question 106.
Which method of the Component class is used to set the position and size of a component?
Answer:
The methods are: set maximum size(Dimension maximum size) Sets the maximum size of this component to a constant value.

Question 107.
What interface is extended by AWT event listeners?
Answer:
The java. util.EventListener interface is extended by all the AWT event listeners.

Question 108.
What is the paint method? What should we put in the paint method? When is it invoked?
Answer:
The AWT uses a Callback mechanism for painting which is the same for heavyweight and lightweight components.

Question 109.
What is the purpose of the repaint method? When should we use the repaint method?
Answer:
repaint( ) requests can erase and redraw (update) after a small time delay. When you invoke repaint( )

Question 110.
Explain the use of the update method. When is it invoked?
Answer:
An update method is called on calling the repaint method. The default implementation of the update( ) method clears the screen and calls the paint( ) method.

Question 111.
How does the XOR drawing mode work? What are the properties of XOR j drawing?
Answer:
setXORMode(Color cl) sets the paint mode of this graphics context to alternate between a graphics context’s current color and the new specified color.

Question 112.
Explain how to load an image from the net into my applet.
Answer:
private Imagelcon image;
inside the init method
image = new ImageIcon(new URL(http://www.xyz.gif));

Question 113.
Explain how to load an image from a file in a java application.
Answer:
Imagelcon icon = createImageIcon(“images/xyz.gif’, “text string”);

Question 114.
What is the difference between a Window and a Frame?
Answer:
A frame is a resizable, movable window with a title bar and a close button. Usually, it contains Panels. It’s derived from a window and has a BorderLayout by default.

Question 115.
Explain how to draw text over a background image.
Answer:
Bufferedlmage img = ImageIO.read(new File(“xxx”)); // xxx is the path TextOnBackground test = new TextOnBackground(img);

Question 116.
Define canvas?
Answer:
It is a simple drawing surface that is used for painting images or to perform other graphical operations.

 

J2EE interview questions and answers for senior developers – Java J2EE Interview Questions and Answers for Freshers & Experienced

Java J2EE Interview Questions

J2EE interview questions and answers for senior developers: Java is the most popular programming language that helps developers to begin their software developer careers in various startups or top MNCs. The most difficult task to commence their career as Java Developers is cracking the interview rounds conducted by different industries. But holding & practicing with the best Java J2EE Interview Questions for Freshers with Answers tutorial, you can prove your knowledge of J2EE during an interview effortlessly and secure a developer job in the Java platform.

Must Refer:

Java J2EE Interview Questions and Answers for Freshers & Experienced

J2EE interview questions and answers for experienced: J2EE stands for ‘Java 2 Platform Enterprise Edition’. It is an open and standards-based platform for the development, deployment, and management of multi-tier, web-enabled, component-based, and server-centric enterprise applications.

Mainly, it covers various Application programming interfaces for building effective systems. The list of concept-wise Java J2EE Interview Questions for Beginners & Expert Developers is compiled here for a clear understanding of J2EE concepts, theories, and some common coding techniques for freshers and experienced candidates.

Java j2ee interview questions and answers for experienced: Be prepared with all J2EE concepts and left a great impression in front of the interviewers, by reviewing the most commonly asked Java 2 platform enterprise edition interview questions for freshers. Basically, companies ask interview questions to test & examine your basic understanding of the J2EE platform.

Also, they compare your knowledge of J2EE to other platforms during the interview process by throwing such Fresher Java 2 EE Interview Questions. Therefore, stick to this tutorial and collect all important questions and answers that are asked frequently about J2EE during interviews.

Frequently Asked Java J2EE Interview Questions for Freshers with Answers

  1. What is the Java 2 Platform Enterprise Edition (J2EE)?
  2. What are the main benefits of the J2EE platform?
  3. What technologies are included in the J2EE platform?
  4. What’s new in the J2EE 1.4 platform?
  5. What is the J2EE 1.4 SDK?
  6. What tools can I use to build J2EE applications?
  7. Who needs the J2EE platform?
  8. What is an EJB Platform?
  9. What are the roles of J2EE Architect?
  10. What are the responsibilities of the bean developer?

Basic J2EE Interview Questions 2021 for Beginners

  1. What do you understand by J2EE?
  2. What do you mean by J2EE Module?
  3. Define the Struts in the J2EE framework?
  4. What are the four types of J2EE modules?
  5. What does the application client module contain?
  6. Define Hashtable in J2EE?
  7. What does the web module contain?
  8. What does the Enterprise JavaBeans module contain?
  9. Define Hibernate and HQL?
  10. What does resource adapt module contain?
  11. What are the main components of the J2EE application?
  12. Define ORM and its working in J2EE?
  13. What is authorization?
  14. What are the major benefits of hibernate?
  15. How will you explain save() and saveorupdate() methods in hibernate?
  16. What is the concept of connection pooling?
  17. Give some advantages of ORM (object-relational mapping)?
  18. What is B2b?
  19. What are the main components of multi-tier architecture?
  20. Explain JTA, JNDI, and JMS.
  21. Describe the EAR, WAR, and JAR.
  22. What are the different modules used in Spring?
  23. What do you understand by ActionForm?
  24. How will you explain CDATA?
  25. What do you mean by the Component Contract?

Top 15 Fresher Java Interview Questions

  1. What are the key differences between C++ and Java?
  2. What is the static keyword?
  3. What is an interface?
  4. What is the use of Classloader in Java?
  5. What is the Java Collections Framework?
  6. Explain the JVM architecture?
  7. Which class is a superclass of all classes?
  8. What is the use of System class in Java?
  9. What is Type casting in Java?
  10. What is break and continue statement in java?
  11. What are finally and finalize in Java?
  12. What is the inner and anonymous inner class?
  13. What is aggregation in Java?
  14. What is an Iterator?
  15. What is an instanceof keyword?

For more interview questions for beginners on Java programming do check this – 200+ List of Simple Java Programming Interview Questions

This ultimate collection of topic-wise beginners’ interview questions on Java J2EE helps to practice well at the last moment of the interviews and boost up their confidence. Also, the Java J2EE Interview Questions for Freshers pdf covers the important areas of the J2EE programming language from basic to advanced level. So, the interview appeared candidates are advised to go with this best & most popular Java J2EE Fresher Interview Questions & Answers tutorial and prepare efficiently.

Do Check Related JAVA Tutorials: 

FAQs on Java 2 Enterprise Edition Interview Questions PDF for Senior Developers & Freshers

1. What is the purpose of Java J2EE?

The purpose of the J2EE platform in Java Programming Language is to grow multi-tier, web-based applications using a series of protocols, and application programming interfaces (APIs). It offers the enterprise level with a java platform ie., fast, safe & secure, enhance on the J2SE.

2. What are the types of J2EE modules?

You can observe four types of modules that are defined by J2EE. They are as follows:
Application Client Module.
WEB Module.
Enterprise JavaBeans Module.
Resource Adapter Module.

3. Write the list of Top 5 Java 2 Enterprise Edition Interview Questions and Answers?

Here are the top 5 commonly asked questions about J2EE during interviews:

1. What is J2EE?
2. What components comprise J2EE applications?
3. What are the J2EE client types?
4. What do you mean by J2EE Module?
5. What is a J2EE container?

4. From where freshers can find the most popular Java 2 EE Interview Questions List? 

Freshers, as well as expert coders, can really find the most popular Java J2EE Interview Question with Answers from various online education portals but the best one among them is BtechGeeks.com

Net interview questions and answers pdf – Top & Most Commonly Asked .NET Interview Questions and Answers (2021) for Freshers & Experienced

.NET Interview Questions and Answers

Net interview questions and answers pdf: Beginners, Freshers, and Experienced candidates who are looking for .Net Basic Interview Questions pdf can refer to this tutorial. Here we are mainly focusing on Core .Net Interview Questions for Freshers & Experts to master in .net coding language and crack the interviews in top companies. A basic understanding of common object-oriented concepts and front-end technologies such as HTML, CSS, and JavaScript is also expected while you’re giving interview for .Net job roles.

Therefore, go through with all those needed programming languages also take support from our C Programming Interview Questions, Java OOPS Interview Questions, and Java J2EE Interview Questions pages. At last, freshers or experienced people need to practice with Basic to Advanced .Net Interview Questions and Answers PDF and grab the desired job in the desired company.

.NET Interview Questions and Answers for Freshers & Experienced

Net core interview questions advanced: The following list contains top 100 dot net interview questions for freshers right from basic .net framework to advanced .net concepts like web api.net, asp.net. ado .net interview questions. Just tap the available pdf links of respective .net core interview questions and practice them thoroughly.

Top Most Popular .Net Interview Questions for Freshers

  1. What is the .Net framework?
  2. What is CTS?
  3. What is CLR?
  4. What is meant by Managed and Unmanaged code?
  5. What is ASP.Net?
  6. What is an Assembly? What are the different types of Assemblies?
  7. Explain the different parts of an Assembly.
  8. What is Caching?
  9. What is the difference between Function and Stored procedure?
  10. Explain CAS (Code Access Security).
  11. What is meant by Globalization and Localization?

Commonly Asked .NET Interview Questions For Experienced

  1. Explain role-based security in .NET
  2. Can we apply themes to ASP.NET applications?
  3. What are security controls available on ASP.NET?
  4. What do you mean by AutoPostBack?
  5. What is the appSettings section in the web.config file?
  6. What are the parameters that control most of connection pooling behaviors?
  7. How do you check whether a DataReader is closed or opened?
  8. Which architecture does a Dataset follow?
  9. Which method is used to enforce garbage collection in .NET?
  10. Which are the new features added in .NET framework 4.0?

The answers provided by expert coders for all the interview questions of dot net programming language are easy to understand for all types of learners. Let’s make use of these most commonly asked questions in .Net Interviews and hold your desired job role in top companies.

Conclusion

After going through the above list of freshers & experienced .Net Interview Questions, you will definitely answer all the coding questions asked in interviews and make you grab the opporttunity to work as .Net developer in software company.

MVC interview questions for 7 years experience – MVC Interview Questions in .NET

MVC interview questions for 7 years experience: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

MVC Interview Questions

Question 1.
How will you specify what version of the framework your application is targeting?
Answer:
You can define “targetFramework” in Web.config file to specify the framework version. It is introduced in Asp.net 4.0

1 <?xml version-‘1.0M?>
2 <configuration>
3 <system.web>
4 compilation targetFramework=M4.0M />
5 </system.web>
6 </configuration>

Question 2.
What is the difference between Static class and Singleton instance?
Answer:
– In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for some business reason or loC purposes, you can use the Singleton pattern without a static class.
– You can clone the object of Singleton but, you can not clone the static class object
– Singleton object stores in Heap but, static object stores in stack
– A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded

Question 3.
What is the difference between Unicode, UTF, ASCII, and ANSI code format of encoding?
Answer:
Character encoding interprets the zeros and ones into real characters.

Unicode:

Unicode is a standard that can handle characters for almost all modern languages and even some ancient languages at the same time, as long as the client has fonts for the particular language installed in his system

UTF:

Unicode assigns each character a unique number, or code point. It defines two mapping methods, the UTF (Unicode Transformation Format) encodings, and the UCS (Universal Character Set) encodings. Unicode-based encodings implement the Unicode standard and include UTF-8, UTF-16, and UTF-32/UCS-4. They go beyond 8-bits.

ASCII:

ASCII is abbreviated from American Standard Code for Information Interchange, is a character encoding standard.ASCII codes represent text in computers. lt is a code for representing characters as numbers, with each letter assigned a number from 0 to 127. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number

ANSI:

ANSI is abbreviated from American National Standards Institute, is a character encoding standard.ANSI includes all the ASCII characters with an additional 128 character codes. ASCII just defines a 7-bit code page with 128 symbols. ANSI extends this to 8 bit and there are several different code pages for the symbols 128 to 255.

Question 4.
Can you serialize hashtable and Why?
Answer:
No, You can’t Serialize the Hash table. Because the .NET Framework does not allow serialization of any object that implements the IDictionary interface

Question 5.
What is .PDB file?
Answer:
PDB is an abbreviation for Program Data Base. It is a repository (persistent storage as databases) to maintain the information required to run your program in debug mode. It contains much important relevant information required while debugging your code; for e.g. at what points you have inserted breakpoints where you expect the debugger to break rn Visual Studicr etc.

Question 6.
Why singleton pattern is considered an Anti-pattern?
Answer:
– Singletons aren’t easy to handle with unit tests. You can’t control their instantiation and they may retain state across invocations.
– Memory allocated to a Singleton can’t be freed.
– In a multithreaded environment, access to the singleton object may have to be guarded (e.g. via synchronization).
– Singletons promote tight coupling between classes, so it is hard to test

Question 7.
What are extension methods and where can we use them?
Answer:
Extension methods enable you to add new capabilities to an existing type. You don’t need to make any modifications to the existing type, just bring the extension method into the scope and you can call it like a regular instance method.
Extension methods need to be declared in a nongeneric, non-nested, static class.

Notes:

  • The difference between a regular static method and an extension method is the special keyword for the first argument,
  • An extension method cannot be declared on a class or struct,
  • It can also be declared on an interface (such as IEnumerable). Normally, an interface wouldn’t have any implementation. With extension methods, however, you can add methods that will be available on every concrete implementation of the interface
  • Language-Integrated Query (LINQ) is one of the best examples of how you can use this technique to enhance existing code.
    You can read the implementation of Extension Methods in C# here.

Question 8.
How to update the web. config programmatically?
Answer:
This file is an XML file, and reading/writing XML is supported by. NET. You can choose one of the methods as per your requirement:

  • Use System.Xml.XmlDocument class. It implements a DOM interface; this way is the easiest and good enough if the size of the document is not too big.
  • Use the classes System.Xml.XmlTextWriter and System.Xml.XmlTextReader; this is the fastest way of reading
  • Use the class System.Xml.Linq.XDocument; this is to support LINQ to XML Programming.

Question 9.
What is the difference between Stack and Heap memory in C#? Stack Memory
Answer:
Stack Memory

C# Professional (Expert) Interview Questions in .NET chapter 4 img 1

It is an array of memory.
It is a LIFO (Last In First Out) data structure.
In it, data can be added to and deleted only from the top of it.
“Things” declared with the following list of type declarations are Value Types (because they are from System.ValueType):
bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

Memory allocation is Static

C# Professional (Expert) Interview Questions in .NET chapter 4 img 2

Variables can’t be Resized Its access is fast
Its block allocation is reserved in LIFO.
The most recently reserved block is always the next block to be freed.
It can be visible/accessible only to the Owner Thread
In recursion calls, memory-filled up quickly
It can be used by one thread of execution
.NET Runtime throws exception “StackOverflowException” when stack space is exhausted
Local variables get wiped off once they lose the scope
It contains values for Integral Types, Primitive Types, and References to the Objects.

Heap Memory
C# Professional (Expert) Interview Questions in .NET chapter 4 img 3

It is an area of memory where chunks are allocated to store certain kinds of data objects.
In it data can be stored and removed in any order.
“Things” declared with the following list of type declarations are Reference Types
(and inherit from System. Object… except, of course, for an object which is the System. Object object):
class, interface, delegate, object, string
Memory allocation is Dynamic
It is stored indirectly

C# Professional (Expert) Interview Questions in .NET chapter 4 img 4

Variables can be Resized

Its access is Slow
Its block allocation is free and done at any time
It can be visible/accessible to all the threads
In recursion calls memory filled up slowly
It can be used by all the parts of the application
It is a special thread created by .NET runtime to monitor allocations of heap space.
It only collects heap memory since objects are only created in heap

Question 10.
What is the difference between covariance and contravariance?
Answer:
If you have an interface IFoo<T> it can be covariant in T (i.e. declare it as IFoocout T> if T is only used in an output position (e.g. a return type) within the interface. It can be contravariant in T (i.e. IFoo<in T>) if T is only used in an input position (e.g. a parameter type).

Covariance

Canonical examples: IEnumerable<out T>, Func<out T>

You can convert from IEnumerable<string> to IEnumerable<object>, or Func<string> to Func<object>. Values only come out from these objects.

It works because if you’re only taking values out of the API, and it’s going to return something specific (like string), you can treat that returned value as a more general type (like object).

Contravariance

Canonical examples: IComparer<in T>, Action<in T>

You can convert from IComparer<object> to IComparer<string>, or Action<object> to Action<string>; values only go into these objects.

This time it works because if the API is expecting something general (like object) you can give it something more specific (like string).

Question 11.
What are indexers in C# .NET? What is the difference between property & indexers?
Answer:
An indexer is a pair of get and set accessors, similar to those of properties.

  • Like a property, an indexer does not allocate memory for storage,
  • Both indexers and properties are used primarily for giving access to other data members with which they are associated and for which they provide get and set access.

– A property usually represents a single data member.
– An indexer usually represents multiple data members.

  • Like a property, an indexer can have either one or both of the accessors,
  • Indexers are always instance members; hence, an indexer cannot be declared static.
  • Like properties, the code implementing the get and set accessors does not have to be associated with any fields or properties. The code can do anything, or nothing, as long as the get accessor returns some value of the specified type.

Question 12.
What’s the difference between delegates and events?
Answer:
An event is just a wrapper for a multicast delegate.
Adding a public event to a class is almost the same as adding a public multicast delegate field.
In both cases, subscriber objects can register for notifications, and in both cases, the publisher object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we’d normally want to restrict to the publisher. Hence events – an event adds public methods to the containing class to add and remove receivers but does not make the invocation mechanism public.

Question 13.
Can we Overload the main( ) method rn C#?
Answer:
Yes, We can overload the main( ) method. A C# class can have any number of main() methods.
But to run the C# class, the class should have the main( ) method with signature as “public static void main(String[] args)”. If you do any modifications to this signature, the compilation will be successful. But, You will get a run time error as the main method is not found.

Question 14.
How to design a class (or data type) that sorts its data either ascending or descending by default
Answer:
You can do this by using Array.BinarySearch. Below is the implementation in C#.

class Program
{
static void Main(string[] args)
{
MySortedList list = new MySortedList( );
list.Add(13);
list.Add(Sl);
list.Add(25);
list.Add(9);
list.Add(33);
list.Add(46);
list.Add(1);
13 foreach (int v in list.ltems)
{
Console. WriteLine(v);
}
Console. ReadLine( );
}
}
class MySortedList
{
int[] items = new int[0];
public int[] Items
{
get {return items;}
set {items = value;}
} 

public void Add(int value)
{
int index = Array.BinarySearch(items, value);
if (index < 0)
index = ~index;


//Increase Items Array Size by 1
int lastlndex = items.Length;
int capacity = items.Length + 1;
int[ ] dupArray = new incapacity];
Array.Copy(items, dupArray, items.Length);
items = dupArray;


//Adjusting elements to insert element in its right index
if (index < lastlndex)
{
Array.Copy(items, index, items, index + 1, lastlndex - index);
}
items[index] = value;
} 
}

Question 15.
You have a component with 5 parameters and deployed to client-side now you changed your method which takes 6 parameters. How can you deploy this without affecting the client’s code?
Answer:
Instead of adding the 6th parameter to the existing method, write a new overloaded method with 6 parameters.

So when the old application calls this method, a method with 5 parameters will execute.
And method with 6 parameters will be used by the new application. That way we can provide backward compatibility to old applications.

Question 16.
What is Satellite Assembly?
Answer:
A satellite assembly is a compiled library (DLL) that contains “localizable” resources specific to a given culture such as strings, bitmaps, etc. You are likely to use satellite assemblies when creating a multilingual Ul application.

As per MSDN definition, A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language.

Question 17.
Explain the difference between Error and Exception in C#?
Answer:
Exception handling is a mechanism to detect and handle errors at a run time whereas Errors occurred at development/compile time. You can read more on exception handling in C# here.

Question 18.
What is the difference between == and .Equals method in c#?
Answer:
intx = 20;
int y = 20;
Console.WriteLine( x == y); Console. WriteLine(x.Equals(y));
Output:
True
True

For Reference Type:

== performs an identity comparison, i.e. it will only return true if both references point to the same object. While EqualsO method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:
StringBuilder si = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console. WriteLine(s1.Equals(s2));
Output:

False
True

In the above example, si and s2 are different objects hence “==” returns false, but they are equivalent hence “EqualsO” method returns true. Remember there is an exception to this rule, i.e. when you use the “==” operator with string class it compares value rather than identity.

When to use “==” operator and when to use “.EqualsO” method?

For value comparison, with Value Type use “==” operator and use “Equals( )” method while performing value comparison with Reference Type.

5. What is Partial class and What all are the What is Partial class and What all are the advantages of Partial class

Question 19.
What is a Partial class and What all are the advantages of a Partial class?
Answer:
The class declaration can be partitioned into several partial class declarations.

  • Each of the partial class declarations contains the declarations of some of the class members.
  • The partial class declarations of a class can be in the same file or in different files,
  • Each partial declaration must be labeled as a partial class, in contrast to the single keyword class.

Advantages of Partial Class:

By Using Partial Classes, multiple developers can work on the same class easily. Partial classes are mainly used by the code generators to keep different concerns separate you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.

Question 20.
What all are the Advantages and Disadvantages of Generics in C#?
Answer:

Advantages of Generics:

  • Generics provide type safety without the overhead of multiple implementations.
  • Generics eliminates boxing and unboxing.
  • There is no need to write code to test for the correct data type because it is enforced at compile time. The need for typecasting and the possibility of run¬time errors are reduced.
  • By providing strong typing, a class built from a generic lets visual studio provide IntelliSense.
  • Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types
  • Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.

Disadvantages of Generics:

  •  Generic types can be derived from most base classes, such as MarshalByRefObject (and constraints can be used to require that generic type parameters derive from base classes like MarshalByRefObject). However, the .NET Framework does not support context-bound generic types. A generic type can be derived from ContextBourrdObject, but trying to create an instance of that type causes a TypeLoadException.

• Enumerations cannot have generic type parameters.
• Lightweight dynamic methods cannot be generic.
• In C#, a nested type that is enclosed in a generic type cannot be instantiated unless types have been assigned to the type parameters of all enclosing types

Question 21.
Why C# main method is static?
Answer:
The C# main method is static because the object is not required to call static method if it were non-static method, the compiler creates object first then call main() method that will lead to the problem of extra memory allocation.

Question 22.
What is Implementation Inheritance and Interface Inheritance?
Answer:

Implementation inheritance:

  1. It is achieved when a class is derived from another class in such a way that it inherits all its members.
  2. It is called Class Inheritance.
  3. In this, it uses the ‘extends’ keyword in Java.
  4. The subclass is tightly coupled with the superclass.
  5. If there are any changes to superclass will break the whole relationship.

Interface inheritance:

  1. It is achieved when a class inherits only the signatures of the functions from another class.
  2. It is called Type inheritance and also called subtyping.
  3. In this, it uses the ‘implements’ keyword in Java.
  4. It is used for code reuse and polymorphism.
  5. It reduces coupling and implementation dependencies.

Question 23.
What is Assembly Manifest?
Answer:
Within every Assembly, there is an Assembly Manifest. It contains:

  1. The assembly’s identity (its name and version).
  2. A file table describing all the other files that make up the assembly, for example, any other assemblies you created that your .exe or .dll file relies on, or even bitmap or Readme files.
  3. An assembly reference list, which is a list of all external dependencies—.dlls or other files your application needs that may have been created by someone else. Assembly references contain references to both global and private objects. Global objects reside in the global assembly cache.

Question 24.
What is Reflection and what all are the common use of Reflection?
Answer:
Reflection is a process by which a program can examine and manipulate program objects at run time.
A common use of Reflection:

  1. Load assemblies at runtime
  2. it allows you to learn what assembly defines a particular item such as a class or enumeration
  3. List a class’s field, properties, constructors, event, and methods
  4. Get information about a property such as a type and if it is read-only
  5. Get and Set property’s value
  6. Get information about the item’s attribute etc.

Question 25.
What is Encapsulation and Data hiding in C#?
Answer:
– Encapsulation is a process of hiding the members from outside of class and implemented using access specifiers
– Encapsulation is also called information hiding.
– Encapsulation provides a way to preserve the integrity of state data. Rather than defining public fields, private data fields should be defined.
– Well-encapsulated class should hide its data and the details of how it operates on data from the outside world. This is termed black box programming.
– Using this, the implementation of the method can be changed by the class author without breaking any existing code making use of it.

Question 26.
What does the tilde (~) mean in C#?
Answer:
The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong. Also the ~ symbol is used to declare destructors.

You can read more on tilde(~) here.

Question 27.
Can you use tilde(~) with Enum in C#?
Answer:
Yes, You can use tilde(~) with Enum to flips the bits of its operand.

//using tilde(~)
[Flags]
public enum PurchaseMethod
{
All = ~0,
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4
}
//Alternative:
[Flags]
public enum PurchaseMethod
{
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4,
All = Cash | Check | CreditCard
}

– Source: Stack Overflow

Question 28.
What does placing a @ in front of a C# variable name do?
Answer:
It’s a way to allow declaring reserved keywords as vars. Example

1 void test(int @string)

Question 29.
How do you give a C# Auto-Property a default value?
Answer:
In C#5 and earlier, you can do it using a constructor.

class Employee
{ 
public Employee( )
{
Name = "Default Name";
}
public string Name {get; set;}
}

In C#6.0, You can do:

public string Name {get; set;} = “Default Name”

Question 30.
What is the use of the Yield keyword in C#?
Answer:
Yield keyword helps us to do custom stateful iteration over .NET collections. There are two scenarios where the “yield” keyword is useful:-

  • It helps to provide custom iteration without creating temp collections.
  • It helps to do state-full iteration

Question 31.
What is AsyncCallback in C#?
Answer:
When the async method finishes the processing, the AsyncCallback method is automatically called, where post-processing steps can be executed. With this technique, there is no need to poll or wait for the async thread to complete.

Question 32.
What is Nested types in C# and how to use it?
Answer:
Types are usually declared directly inside a namespace. You can, however, also declare types inside a class or struct declaration.
– Types declared inside another type declaration are called nested types. Like all type declarations, nested types are templates for an instance of the type.
– A nested type is declared like a member of the enclosing type.
– A nested type can be any type.
– An enclosing type can be either a class or a struct.

For example, the following code shows class MyClass, with a nested class called MyCounter.

class MyClass // Enclosing class
{
class MyCounter // Nested class
{
...
}
...
}

It is good to use Nested types if it is only meant to be used as a helper for the enclosing type.

attributes.

Question 33.
What is Null Coalescing Operator in C#?
Answer:
C# Supports a special operator called the null coalescing operator, which returns a non¬null value to an expression, in case a nullable type variable is null.
The null coalescing operator consists of two contiguous question marks and has two operands.

  • The first operand is a variable of a nullable type.
  • The second is a non-nullable value of the underlying type.
  • If at run time, the first operand (the nullable operand) evaluates to null, the non-nullable operand is returned as the result of the expression.

Example:

int? myl4 = null;
Console.WriteLine("myl4: {0}", myl4 ?? -1);
myl4= 10;
Console.WriteLine("myl4: {0}", myl4 ?? -1);
This code produces the following output:
myl4: -1
myl4:10

Question 34.
What are weak references in C#? How is it different than StrongReferences
Answer:
The garbage collector cannot collect an object in use by an application while the application’s code can reach that object. The application is said to have a strong reference to the object.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist. When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is established.

Weak references are useful for objects that use a lot of memory but can be recreated easily if they are reclaimed by garbage collection

Question 35.
What are XML namespaces for?
Answer:
XML namespaces are like packages in C#. They are for allowing multiple markup languages to be combined, without having to worry about conflicts of element and attribute names.

  • You can reuse a set of tags/attributes you define across different types of xml documents.
  • If you need to add some “aspect” to your XML; adding a namespace to your xml document is simpler than changing your whole xml schema definition.
  • Avoid polluting the “main” namespace: You don’t force your parser to work with a huge schema definition, just use the namespace you need to.

Question 36.
What is the difference between string and String in C#?
Answer:
String stands for System. String and it is a .NET Framework type, the string is an alias in the C# language for System. String. Both of them are compiled into System. String in IL (Intermediate Language), so there is no difference.

Question 37.
What’s the difference between the ‘ref and ‘out’ keywords in C#?
Answer:

The ref modifier means that:

  • The value is already set and
  • The method can read and modify it.

The out modifier means that:

  • The value isn’t set and can’t be read by the method until it is set.
  • The method must be set before returning.

semantically, ref provides both “in” and “out” functionality, whereas out only provides “out” functionality.

Question 38.
What is the difference between employee.GetType( ) and typeof(Employee) in at?
Answer:
The result of both would be exactly the same. lt will be your Employee type that derives from System. Type. The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType. If you don’t have an instance, but you know the type name, you would use typeof.
GetType gets resolved at runtime, while typeof is resolved at compile time.

Question 39.
What is the difference between an EXE and a DLL?
Answer:

EXE:

  • An executable file, can run independently
  • It runs in a separate process
  • It can’t be reused in an application
  • it has the main function

DLL:

  • Dynamic-link library is used as part of EXE or other DLL’s
  • It runs in application process memory,
  • It can be reused in an application
  • It does not have the main function

Question 40.
What are the advantages and disadvantages of using the GAC?
Answer:

  • GAC is a central repository in a system in which assemblies are registered to be shared between applications.
  • GACUtil.exe is used to view and change the content of GAC in the system
  • GAC can contain multiple versions on .net assemblies -Thegautil.exe/I is used to install the assembly in GAC

Advantages & Disadvantages:

  1. Loading assemblies from GAC mean less overhead and security that your application will always load correct version of the .NET library
  2. You shouldn’t get assemblies that are outside of GAC, because there will be almost no performance gain, in many cases even loss in performance.
  3. You’re already using GAC, because all standard .NET assemblies are actually in GAC and needed (during installation).
  4. Using GAC for your own libraries adds complexity to deployment, I would try to avoid it at all costs.
  5. Your users need to be logged as administrators during installation if you want to put something into GAC, quite a problem for many types of applications.

Question 41.
What is the difference between a process and a thread?
Answer:
Process: 

  1. An executing instance of a program is called a process.
  2. Some operating systems use the term ‘task’ to refer to a program that is being executed.
  3. A process is always stored in the main memory also termed as the primary memory or random access memory.
  4. Therefore, a process is termed an active entity. It disappears if the machine is rebooted.
  5. Several processes may be associated with the same program.
  6. On a multiprocessor system, multiple processes can be executed in parallel.
  7. On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.

Thread:

  1. A thread is a subset of the process.
  2. It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel.
  3. Usually, a process has only one thread of control – one set of machine instructions executing at a time.
  4. A process may also be made up of multiple threads of execution that execute instructions concurrently.
  5. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
  6. On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
  7. All the threads running within a process share the same address space, file descriptors, stack, and other process-related attributes.
  8. Since the threads of a process share the same memory, synchronizing the access to the shared data within the process gains unprecedented importance.
  9. Source: Knowledge Quest

Question 42.
If asynchronous execution takes less total time to finish than synchronous execution, why would anybody choose synchronous execution?
Answer:
In Synchronus mode, every task executes in sequence, so it’s easier to program. That’s the way we’ve been doing it for years.
With asynchronous execution, you have few challenges:

  • You must synchronize tasks, for e.g. you run a task that must be executed after the other three have finished. You will have to create a mechanism to wait for all tasks to finish before launching the new task.
  • You must address concurrency issues. If you have a shared resource, like a list that is written in one task and read in another, make sure that it’s kept in a known state. -There is no logical sequence anymore. The tasks can end at any time, and you don’t have control of which one finishes first.

But in synchronous programming we have the below disadvantages:

  • It takes longer to finish.
  • It may stop the user interface (Ul) thread. Typically, these programs have only one Ul thread, and when you use it as a blocking

the operation, you get the spinning wheel (and “not responding” in the caption title) in your program-not the best experience for your users.

It doesn’t use the multicore architecture of the new processors. Regardless of whether your program is running on a 1-core or a 64-core processor, – it will run as quickly (or slowly) on both.

Asynchronous programming eliminates these disadvantages: it won’t hang the Ul thread (because it can run as a background task), and it can use all the cores in your machine and make better use of machine resources. So, do you choose easier programming or better use of resources? Fortunately, you don’t have to make this decision. Microsoft has created several ways to minimize the difficulties of programming for asynchronous execution.

Question 43.
Why do we need C# delegates?
Answer:
you can call methods directly on the object but in below scenarios you may consider using Delegates:

  1. You want to call series of methods by using a single delegate without writing a lot of method calls.
  2. You want to implement an event-based system elegantly.
  3. You want to call two methods the same in signature but reside in different classes.
  4. You want to pass a method as a parameter.
  5. You don’t want to write a lot of polymorphic code like in UNO., you can provide a lot of implementation to the Select method.

Question 44.
why do we use the Dictionary class instead of the Hashtable class?
Answer:
Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can’t insert any random object into it, and you don’t have to cast the values you take out.

Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization.

Question 45.
Are nullable types reference types in C#?
Answer:
Nullable types are instances of the System. Nullable struct. Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. So nullable types are not referenced types.

Question 46.
What is the difference between System exceptions and Application exceptions?
Answer:
System exceptions are derived directly from a base class System.SystemException. A System-level Exception is normally thrown when a nonrecoverable error has occurred. Application exceptions can be user-defined exceptions thrown by the applications. If you are designing an application that needs to create its own exceptions class, you are advised to derive custom exceptions from the System.ApplicationException class. It is typically thrown when a recoverable error has occurred.

Question 47.
What is the difference between Var and Dynamics in C#?
Answer:

Dynamic

Introduced in C# 4.0

Dynamically typed – This means the type of variable declared is decided by the compiler at run time.

No need to initialize at the time of declaration,

e.g., dynamic str;

Looking at the value assigned to the variable str, the compiler will treat the variable str as a string. str=”l am a string”; //Works fine and compiles

Errors are caught at runtime

Since the compiler comes to about the type and the methods and properties of the type at the run time.

Intellisense help is not available for the dynamic type of variables since their type is unknown until run time. So intellisense help is not available. Even if you are informed by the compiler as “This operation will be resolved at run-time”.

Will compile

var

Introduced in C# 3.0

Statically typed – This means the type of variable declared is decided by the compiler at compile time.

var type of variables are required to be initialized at the time of declaration or else they encounter the compile-time error: Implicitly-typed local variables must be initialized.

e.g.; var str=”l am a string”;

Errors are caught at compile time.

Since the compiler knows about the type and the methods and properties of the type at the compile time itself

Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, the compiler that has all the information related to the type

will throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.

Question 48.
When to use Tuples in C#?
Answer:
Tuples are commonly used in four ways:

  • To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
  • To provide easy access to, and manipulation of, a data set.
  • To return multiple values from a method without using out parameters -To pass multiple values to a method through a single parameter. For example, the Thread. The start (Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple object as the method argument, you can supply the thread’s startup routine with three items of data.

Question 49.
How can you create responsive Ul without impacting users?
Answer:
You can create a responsive Ul using multithreading. You can split the work into small pieces and run it in the background without impacting the user.

Question 50.
How to Force Garbage Collection?
Answer:
You can force this by adding a call to GC.Collect. Example:

StreamWriter stream = File.CreateText("temp.dat");
stream.Write("some test data");
GC.Collect( );
GC.WaitForPendingFinalizers( );
File.Delete("temp.dat");

Question 51.
What is the difference between Lock and Monitor in C#?
Answer:
Monitor and lock is the way to provide thread safety in a multithreaded application in C#.Lock is the keyword in C# that will ensure one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section.

Question 52.
Why do we need Reflection in C#?
Answer:
We use Reflection in C#:

  1. Load assemblies at runtime
  2. it allows you to learn what assembly defines a particular item such as a class or enumeration
  3. List a class’s field, properties, constructors, event and methods
  4. Get information about a property such as a type and if it is read only
  5. Get and Set property’s value
  6. Get information about item’s attribute etc..

Question 53.
How do you mark a method as Obsolete/Deprecated?
Answer:
You can use Obsolete attribute to mark a method as Obsolete or Deprecated

Question 54.
Can you use ref and out parameters in Lambda expression, if declared outside?
Answer:
If you will use ref or out parameter outside of Larrrda Expression then you will get compile time error.

static void DoWork(int valln, out int valOut)
{
int local;

Action doCalc = ( ) =>
{
local = valln * 2; //this will work fine
//valOut = valln * i; // this will be a compile time error
};

// you can use the out parameter to assign result of lambda
Func<int> doCalc2 = () => valln * 2;
valOut = doCalc2(); //Allowed
}

Question 55.
How to return multiple values from a function in C#?
Answer:
In C#, There are several ways to return multiple values from a C# function.

  • Using KeyValue pair
  • Using ref/out parameters
  • Using Struct or Class
  • UsingTuple

of arrays.

Question 56.
How can you cancel an Async operation in C#?
Answer:
You can cancel your own async operation. There are two classes in the System.Threading.Tasks namespace that is designed for this purpose: CancellationToken and CancellationTokenSource.

A CancellationToken object contains the information about whether a task should be cancelled or not.
A task that has a CancellationToken object needs to periodically inspect it to see what the token’s state is. If the CancellationToken object’s IsCancellationRequested property is set to true, the task should halt its operations and return.
A CancellationToken is nonreversible and can only be used once. That is, once its IsCancellationRequested property is set to true, it can’t be changed.
A CancellationTokenSource object creates a CancellationToken object, which can then be given to various tasks. Any objects holding a CancellationTokenSource can call its Cancel method, which sets the CancellationToken’s IsCancellationRequested property to true.

Question 57.
Can an abstract class be Sealed in C#?
Answer:
An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

Question 58.
What is the main use of a final block in exception^ handling? ‘
Answer:
The finally block is linked with a try block and contains a block of statements that are executed irrespective of whether an exception occurs or not within the try block. Finally defines the code that is executed always. In the normal execution it is executed after the try block When an exception occurs, it is executed after the handler if any or before propagation as the case may be.

Question 59.
How to avoid Singleton instance creation by cloning?
Answer:
We can create a copy of an object using clone( ) method.
To avoid creating a clone of our singleton class, we can do the following :

  • Implement MethodwiseClone( )
  • Override the clone() method and throw CloneNotSupportedException from it.
protected object MemberwiseClone( )
{
throw new Exception("Cloning a singleton object is not allowed");
}

Question 60.
What are generations in GC?
Answer:
After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects.

This memory is called the managed heap, as opposed to a native heap in the operating system.

There is a managed heap for each managed process. All threads in the process allocate memory for objects on the same heap.

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly generation 0 collections unless they are large objects, in which case they go on the large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).
Generation 0 – Short-lived Objects
Generation 1- As a buffer between short-lived and long-lived objects Generation 2 – Long lived objects

Question 61.
How to catch multiple exceptions at once in C#?
Answer:
You can catch multiple exceptions using condition statements in C#. Example

catch (Exception ex)
{
if (ex is FormatException 11 ex is OverflowException)
{
testid = " ":
return;
}

throw;
}
catch (Exception ex) when (ex is FormatException 11 ex is 
OverflowException)

{

testid = " ";

return;

}

Question 62.
Write a Regular expression to validate the email address?
Answer:
A[a-zA – Z0 – 9. _%+-]+@[a-zA – ZO-9 . _%+-]+V[a-zA-Z]{2,4}$ In the above example:

  • the sequence A[a-zA – ZO-9. _%+-] matches letters,digits, underscores, %,+ and
  • The + (plus) sign after the 1st sequence means the string must include one or more of those characters
  • Next, the pattern matches @
  • Then the pattern matches another letter one or more times followed by a . and then between two to four letters

Question 63.
Can you loop through all Enum values in C#?
Answer:
Yes, you can loop through all Enum values using GetValues or the typed version.

public enum Color {
Red,
Blue,
Black,
White
}
var values = Enum.GetValues(typeof(Colors));
//Or the typed version
var values = Enum.GetValues(typeof(Colors)).Cast<Colors>( );

Question 64.
Should ‘using’ statements be inside or outside the namespace in C#?
Answer:
Let’s look at the below example to understand the difference between ‘using’ statements inside or outside the namespace, suppose there are 2 files.

// Filel.cs
using System;
namespace Outer.lnner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}

// File2.cs
namespace Outer
{
class Math
{
}
}

The compiler searches Outer before looking at those using statements outside the namespace, so it finds Outer. Math instead of System.Math. Outer. Math has no PI member, so Filel is now broken.
This changes if you put the “using” inside your namespace declaration, as follows:

// File lb. cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar( )
{
double d = Math. PI;
}
}
}

Now the compiler searches ‘System’ before searching ‘Outer’, finds ‘System. Math’. So this will work fine. So we can say it depends on the type of system we are creating.

Question 65.
Should a return statement be inside or outside a lock statement?
Answer:
Whether you put the return statement inside or outside a lock statement, It doesn’t make any difference; they’re both translated to the same thing by the compiler.

It is recommended to put the return inside the lock. Otherwise, you risk another thread entering the lock and modifying your variable before the return statement, therefore making the original caller receive a different value than expected.

Question 66.
How to iterate over a Dictionary in C#?
Answer:
You can use key-value pair to iterate over a dictionary in C#.

for each(KeyValuePair<string, string> entry in myDic)
{
// do something with entry.Value or entry.Key
}

If you are trying to use a generic Dictionary in C# like you would use an 
associative array in another language: 

foreach(var item in my dictionary)
{

foo(item.Key);

bar(item.Value);
}
Or, if you only need to iterate over the collection of keys, use 

foreach(var item in my dictionary.Keys)
{
foo(item);
}
And lastly, if you're only interested in the values: foreach(var item in my dictionary.Values)
{
foo(item);
}

Question 67.
What is the use of the IDisposable interface in C#
Answer:
The primary use of the IDisposable interface is to clean up unmanaged resources.”unmanaged” means things like database connections, sockets, window handles, etc. The garbage collector doesn’t know how to call DeleteHandle( ) on a variable of type IntPtr, it doesn’t know whether or not it needs to call DeleteHandle( ).
So Microsoft has faciliated the Idisposable Interface and Dispose method to clean up unmanaged resources.

Implement IDisposable and Dispose method:

using System;
using System.10;
class UnmangedWrapper: IDisposable
{
public FileStream Stream {get; private set;}
public UnmangedWrapper( )
{
this.Stream = File.Open("temp.dat", FileMode.Create);
}
~UnmangedWrapper( )
{
Dispose(false);
}
public void Close()
{
Dispose();
}
public void DisposeQ
{
Dispose(true);

System.GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{ 
if (Stream != null)
{
Stream. CloseQ;
}
}
}

Question 68.
What all are the difference between the Dictionary class and Hashtable class?
Answer:

Hashtable

A Hashtable is a non-generic collection.

Hashtable is defined under System. Collections namespace.

In Hashtable, you can store key/value pairs of the same type or of a different type.

In Hashtable, there is no need to specify the type of the key and value.

The data retrieval is slower than Dictionary due to boxing/ unboxing.

In Hashtable, if you try to access a key that doesn’t present in the given Hashtable, then it will give null values.

It is thread-safe.

It doesn’t maintain the order of stored values.

Dictionary

A Dictionary is a generic collection.

Dictionary is defined under System.Collections.Generic namespace.

In Dictionary, you can store key/value pairs of the same type.

In Dictionary, you must specify the type of key and value.

The data retrieval is faster than Hashtable due to no boxing/ unboxing.

In Dictionary, if you try to access a key that doesn’t present in the given Dictionary, then it will give an error.

It is also thread-safe but only for public static members.

It always maintains the order of stored values.

Question 69.
When to use struct instead of class in C#?
Answer:
Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
Do not define a structure unless the type has all of the following characteristics:

  1. It logically represents a single value, similar to primitive types (integer, double, and so on).
  2. It has an instance size smaller than 16 bytes.
  3. It is immutable.
  4. It will not have to be boxed frequently.

Question 70.
How do you generate a random number in C#?
Answer:
The Random class is used to create random numbers in C#.

//Example:

Random r = new Random( );

int n = r.Next( );

Question 71.
How to split a string using Regex in C#?
Answer:
The Regular Expressions SplitQ methods are similar to the String.split( ) method, except that Regex.split( ) method splits the string at a delimiter determined by a Regular Expression instead of a set of characters.

When using Regular Expressions you should use the following namespace:

using System.Text.RegularExpressions;
string str = "testl\n \ntest2\n \ntest3\n \n \ntest4";
string[ ] result = Regex.Split(str, "\n\\s*");
 for (int i = 0; i < result.Length; i++)
MessageBox.Show(result[i]);

//Output:
test1
test2
test3
test4

Question 72.
How can you get the assembly version in C#?
Answer:
You can get the assembly version in C#:

1 Version version = Assembly.GetEntryAssembly().GetName().Version;

Question 73.
How would you Read settings from app.config or web. config in C#?
Answer:
ConfigurationManager.AppSettings[“MySetting”]

You will need to add a reference to System. Configuration in your project’s references folder.

Question 74.
When you create and compile an application in C#, what are the files that get generated in Debug folder?
Answer:
When you will create and compile a program in C#, you will see the below files in Debug folder.

  • exe – the ‘normal’ executable
  • vshost.exe – a special version of the executable to aid debugging; see MSDN for details
  • pdb – the Program DataBase with debug symbols
  • vshost.exe.manifest – a kind of configuration file containing mostly dependencies on libraries

Question 75.
Can you add extension methods to an existing static class?
Answer:
No. Extension methods require an instance of an object. However, you can do something like this:

public static class Extensions
{
public static T Create<T>(this T @this)
where T : class, new()
{
return Utility<T>.Create();
}
}

public static class Utility<T>

where T : class, new()

{
static Utility()
{

Create =
Expression.Lambda<Func<T»(Expression.New(typeof(T).GetConstructor(Type.Empty Types))).Compile();

}
public static Func<T> Create { get; private set;}

}

Question 76.
What is the difference between Object pooling and Connection pooling in C#?
Answer:
The object pool implementation will increase the size of the pool up to the specified maximum. When the maximum is reached, instead of throwing an exception, it makes the client wait until an object is returned to the pool, and then gives the newly returned object to the waiting client.

The connection pool implementation does not have a maximum size parameter – it will keep creating new connections to meet demand (eventually it will hit some system limit and the request will fail in some way that isn’t specified.

Question 77.
What is the use of volatile keywords?
Answer:
The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

The volatile keyword can be applied to fields of these types:

  1. Reference types.
  2. Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a “pointer to volatile.”
  3. Integral types such as byte, byte, short, short, int, int, char, float, and bool.
  4. An enum type with an integral base type.
  5. Generic type parameters are known to be reference types.
  6. IntPtr and UlntPtr.

Question 78.
What is the use of Partial class in C#?
Answer:

  • By Using Partial Classes, multiple developers can work on the same class easily.
  • Partial classes are mainly used by the code generators to keep different concerns separate
  • you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.

Explain Constructor Overloading, Constructor Chaining, copy constructor

It is quite similar to Method overloading. It is the ability to redefine a Constructor in more than one form. A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures, i.e. the constructor must have the same name but with a different parameters list.
We can overload constructors in different ways as follows:

  • By using different types of arguments
  • By using a different number of arguments
  • By using a different order of arguments

By changing the Data types of the parameters

Example:

public ADD (int a, float b);

public ADD (string a, int b);

Here the name of the class is ADD. In the first constructor there are two parameters, first one is int and another one is float and in the second constructor, also there is two parameters, the first one is a string type and another one is int type.

Here the constructors have the same name but the types of the parameters are different, similar to the concept of method overloading.

// C# program to Demonstrate the overloading of
// constructor when the types of arguments
// are different
usingSystem;


classADD {


intx, y;
doublet;
strings;


// 1st constructor
publicADD(inta, doubleb)
{
x = a;
f = b;
}


// 2nd constructor
publicADD(inta, stringb)
{
y= a;
s = b;
} 


// showing 1st constructor's result
publicvoidshow( )
{
Console.WriteLine("lst constructor (int + float): {0}",
(x+f));

}


// shows 2nd constructor's result
publicvoidshowl( )
{
Console.WriteLine("2nd constructor (int + string): {0}",
(s + y));
}
}
// Driver Class
classGFG {


// Main Method
staticvoidMain( )
{
// Creating instance and
// passing arguments
// It will call the first constructor
ADD g = newADD(10, 20.2);


// calling the method
g.show( );


// Creating instance and
// passing arguments
// It will call the second constructor
ADD q = newADD(10, "Roll No. is ");


// calling the method
q.show1( ); >
}
}

Output:

1st constructor (int + float): 30.2
2nd constructor (int + string): Roll No. is 10

By changing the number of the parameters

In this case, we will use two or more constructors having a different number of parameters. The data types of arguments can be the same but the number of parameters will be different.

Example:

public ADD (int a, int b);
public ADD (int a, int b, int c);

Here, the class name is ADD. In the first constructor, the number of parameters is two and the type of the parameters is Int. In the second constructor, the number of parameters is three and the types of the parameters are also an int, there is no problem with the data types.

// C# Program to illustrate the overloading of
// constructor when the number of parameters
// are different
using system;


classADD {


intx, y;
intf, p, s;


// 1st constructor
publicADD(inta, intb)
{
x = a;
y = b; 
} 


// 2nd constructor
publicADD(inta, intb, intc)
{
f = a;
P = b; s = c;
}
// showing 1st constructor's result
publicvoidshow( )

{
Console.WriteLine("lst constructor (int + int): {0}",
(x + y));


// showing 2nd constructor's result
publicvoidshow1( )
{
Console.WriteLine("2nd constructor (int + int + int): {0}",
(f + p + s));

}
}

// Driver Class
classGFG {


// Main Method
staticvoidMain( )
{


// will call 1st constructor
ADD g = newADD(10, 20);


// calling method
g.show( );


// will call 2nd constructor
ADD q = newADD(10, 20, 30);


// calling method
q.show1( );
}
}

Output:
1st constructor (int + int): 30
2nd constructor (int + int + int): 60

By changing the Order of the parameters

Example:

public student(double a, int x, string s)
public student(string s, int x, double a)

Here, the two constructors hold the same types of parameters, that is, each constructor has one double type, one int type, and one string type parameter, but the positions of the parameters are different. The compiler will invoke the constructor according to their argument order.

// C# program to illustrate the overloading of
// constructor by changing the order of parameters
usingSystem;


classstudent {


publicintroll;
publicdoubleHeight;
publicstringname;


publicstudent(doublea, intx, strings)
{
roll = x;
name = s;
Height = a;
}


// order of the argument is different
// with respect to 1st constructor
publicstudent(strings, intx, doublea)
{
Height = a;
roll = x;
name = s;
} 


publicvoidshow( )
{
Console.WriteLine("Roll Number:"+ roll);
Console.WriteLine("Height:"+ Height + "feet");
Console.WriteLine("Name:"+name);
}
}


// Driver Class
classVaibhav {


// Main Method
staticvoidMain( )
{


// invoking 1st constructor
student si = newstudent(5.7,10, "Vaibhav Singh");


// invoking 2nd constructor
student s2 = newstudent("Peter Perker", 11, 6.0);


Console.WriteLinef'First Constructor:");
sl.show( );


Console.WriteLine( );


Console.WriteLine("Second Constructor:");
s2.show();
}
}

Output:
First Constructor:
Roll Number: 10
Height: 5.7feet
Name: Vaibhav Singh

Second Constructor:
Roll Number: 11
Height: 6feet
Name: Peter Perker

Invoke an Overloaded Constructor using “this” keyword

We can call an overloaded constructor from another constructor using this keyword but the constructor must belong to the same class because this keyword is pointing to the members of the same class in which this is used. This type of calling the overloaded constructor is also termed as Constructor Chaining.

Example:
Let the class name is gfg,
Now
public gfg( )
public gfg(int a): this( )
public gfg(double b): this(int)

Here the first constructor is default constructor, second and third constructor is parameterized Constructors, where one has int type and another one has a double type parameter.
In the second constructor, this( ) invoke the first constructor which is the default constructor. Here, after this keyword, there is only ( ) which means the compiler invokes a constructor that has no argument, which means default constructor.
In third constructor, this(int) invoke the second constructor which is parameterized constructor. Here, after this there is (int) which means the compiler invoke constructor that has int type argument.

// C# program to illustrate the invoking of
// overloaded constructor using this keyword
usingSystem; 

classGFG {


// Private data members
privateintLength, Height;
privatedoubleWidth;


// Default Constructor
publicGFG( )
{
Console.WriteLine("Default Constructor Invoked");
}


//The constructor calls the
// Default constructor
publicGFG(intl, doublew) : this()
{
Console.WriteLine("Parameterized Constructor in 2nd Constructor");


// assigning value of
// 'Length'and 'Width'
Length = I;
Width = w;


}

// The constructor call the
// parameterized constructor
publicGFG(intl, doublew, inth): this(l, w)
{
Console.WriteLine("Parameterized Constructor in 3rd Constructor");


// assign value of 'Height'
Height = h;


}


// Public Method to calculate volume
publicdoubleVolume( )
{
return(Length * Width * Height);
}
}
// Driver Class
classVaibhav
{


// Main Method
publicstaticvoidMain()
{


// Invoking 3rd Constructor
// here Constructor chaining 
// came into existence
GFG g = newGFG(10, 20.5, 30);


// calling the 'Volume' Method
Console.WriteLine("Volume is : {0}", g.Volume( ));
}
}

Output:
Default Constructor Invoked

Parameterized Constructor in 2nd Constructor

Parameterized Constructor in 3rd Constructor

Volume is : 6150

Overloading of Copy Constructor

A parameterized constructor that contains a parameter of the same class type is called a copy constructor. Basically, copy constructor is a constructor which copies the data of one object into another object. Its main use is to initialize a new instance to the values of an existing instance.

// C# program to illustrate the
// overloading of Copy Constructor
usingSystem; 


classGFG {


publicstringpl, p2;
publicintp3, p4;


// 1st Constructor
publicGFG(stringx, stringy)
{
pi = x;
p2 = y;
} 


// Copy Constructor of 1st Constructor
publicGFG(GFG gf)
{
p1 = gf.p1;
p2 = gf.p2;
}


// 2nd Constructor with different
// types pf parameter publicGFG(inta, intb)
{
p3 = a; p4 = b;
}


// Copy Constructor of 2nd Constructor
// Flere number of parameter is different
// with respect to 1st Constructor
publicGFG(GFG a, GFG b)
{
p3 = a.p3; p4 = b.p4;
}
}


// Driver Class
classVaibhav {


// Main Method
staticvoidMain( )
{


// Create instance to class 'GFG'
GFG g = newGFGf.NET Interview Questions", "By Er.Vaibhav singh Chauhan");


// Here 'g' details will copied to 'gl'
GFG gl = newGFG(g);


Console.WriteLine(gl.pl + " to "+ gl.p2);


// Create instance to class 'GFG'
// with different types of parameter
GFG G = newGFG(10, 20);


// Here ’G' details will copied to 'Gl'
GFG G1 = newGFG(G, G);


Console.WriteLine("Overloaded values : {0} and {1}",
Gl.p3, Gl.p4);
}
}

 

Output:
.NET Interview Questions By Er.Vaibhav Singh Chauhan

Overloaded values: 10 and 20

Question 80.
Can we overload Static Constructor?
Answer:
Static Constructors cannot be overload, because Static Constructors are parameterless constructors, but for overloading, we must need the parameterized constructors.

Question 81.
Can we overload Private Constructor?
Answer:
Private Constructor cannot be overload, because of its protection level. Private members cannot be accessed from outside the class.

Question 82.
Difference between Static Constructors and Non-Static Constructors?
Answer:
Static constructors are used to initializing the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initializing the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Constructors.

• Declaration: Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called Instance Constructors as they need instances to get executed.

Example:

// C# Program to demonstrate
// how to declare the static
// constructor and non-static
// constructor
usingSystem;


class Vaibhav {
// static variable
staticints;


// non-static variable
intns;


// declaration of
// static constructor
Static Vaibhav()
{
Console.WriteLine("lt is static constructor");
}
// declaration of // non-static constructor Vaibhav ()
{ 
Console.WriteLine("lt is non-static constructor");
}


// Main Method
Static void Main(string[] args)
{


// static constructor will call implicitly
// as soon as the class start to execute
// the first block of code to execute
// will be static constructor
// calling non-static constructor
Vaibhav obj1 = new Vaibhav ();
}
}

Output:
It is static constructor
It is non-static constructor

• Calling: Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.
Example: In the above program, we have a static constructor i.e static
Vaibhav( ) which is called in the main method implicitly. See the output carefully, the code inside the static constructor is executing. But to call a non-static constructor i.e Vaibhav(), you need to create an instance of the class, i.e objl. So the creation of the object is to call the non-static constructor explicitly.
• Execution: Static constructor executes as soon as the execution of a class starts and it is the first block of code that runs under a class. But the non-static constructors execute only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.

Example:

// C# Program to demonstrate
// the execution of static
// constructor and non-static
// constructor usingSystem;


class Vaibhav {


// declaration of
// static constructor
Static Vaibhav( )
{
Console.WriteLine("Static constructor");
}


// declaration of
// non-static constructor
Vaibhav( ) /
{
Console. WriteLine(" Non-Static constructor");
}
// Main Method
staticvoidMain(string[] args)
{


// static constructor will call implicitly
// as soon as the class start to execute
// the first block of code to execute /
/ inside the class will be static
// constructor


// calling non-static constructor
// here we are calling non-static
// constructor twice as we are
// creating two objects
Vaibhav objl = new Vaibhav( );
Vaibhav obj2 = new Vaibhav( );
}
}

 

Output:

Static constructor

Non-Static constructor

Non-Static constructor

Explanation: In the above program, there are two objects of Vaibhav^ class is created i.e objl and obj2. objl and obj2 will call the non-static constructor twice because each and every time the instance of the class is created, it will call the non¬static constructor. Although, in the Main method(entry point of a program), the first statement is “Vaibhav objl = new Vaibhavj);” but as soon as the compiler found the Main Method control will transfer to class and the static block will be executed first. That’s why you can see in the output that Static Constructor is called first.

• Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.
Example: In the above program, you can see the static constructor is executing only once but the non-static constructor is executing 2 times as the two instances of the class is created. If you will not create an instance of the class then the non-static constructor will not execute.

• Initialization of fields: Static constructors are used to initializing the static fields and non-static constructors are used to initialize the non-static fields.

Example:

// C# Program to demonstrate
//initialization of fields
// by using static constructor
// and non-static constructor
usingSystem;


classVaibhav {


//static variable
staticints;


// non-static variable
intns;

// declaration of
// static constructor
staticVaibhav( )
{
Console. WriteLine("Static constructor");
}


//declaration of
// non-static constructor
Vaibhav( )
{
Console.WriteLine("Non-Static constructor");
}


// Main Method
staticvoidMain(string[] args)
{
// static fields can
// be accessed directly
Console.WriteLinefValue of s is:"+ s);


// calling non-static constructor
Vaibhav objl = newVaibhav();


//printing the value
// of non-static field
Console.WriteLine("Value of ns is:"+ objl.ns);
}
}

 

Output:

Static constructor

Value of s is: 0

Non-Static constructor

Value of ns is: 0

  • Explanation: Here, both the static and non-static fields are initialized with default value. The default value of int type is zero. Static constructor will initialize only static fields. Here static field is s. While the non-static field(ns) is initialized by the non-static constructor.
  • Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error as shown in below example. However, we can pass the parameters to the non-static constructors.
    Example:
// C# Program to demonstrate
// the passing of paramters
// to constructor
usingSystem;


classVaibhav {


// static variable
staticints;



// non-static variable
intns;
// declaration of
// static constructor
// and passing parameter
// to static constructor
staticVaibhav(intk)
{


k = s;
Console.WriteLinef'Static constructor & K = "+ k);
}


// declaration of
// non-static constructor
Vaibhav( )
{
Console.WriteLine("Non-Static constructor");
}
// Main Method
staticvoidMain(string[] args)
{
}
} 

Runtime Error:
prog.cs(18,16): error CS0132: ‘Vaibhav.Vaibhav(int)’: The static constructor must be parameterless

Overloading: Non-static constructors can be overloaded but not static constructors. Overloading is done on the parameters criteria. So if you cannot pass the parameters to the static constructors then We can’t overload it.

Cases in which the constructor will be implicit:  Every class except the static class(which contains only static members) always contians an implicit constructor if the user is not defining any explicit constructor. If class contains any static fields then the static constructors are defined implicitly.

 

WCF interview questions and answers for experienced pdf – Remoting, Web Services and WCF Interview Questions in .NET

WCF interview questions and answers for experienced pdf: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Remoting, Web Services and WCF

Question 1.
What are Web services, remoting and WCF?
Answer:
When you want to communicate with remote application you will use one of them.
So when both the applications are of .NET technologies remoting is used or else you will use Web services or WCF.

Question 2.
What is an application domain?
Answer:
Application domain is a logical isolation inside a process. This logical isolation has its own memory and own boundary. Any process which runs inside this logical isolation if crashed will not affect other processes running in other application domain as shown in Figure 11.1.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 1

Application domain helps to isolate processes for better application stability.

Question 3.
What is .NET Remoting?
Answer:
.NET remoting helps to make remote object calls, which exist in different Application Domains or different machines or different geographical boundaries.
When a client wants to make a method call on the remote object it uses a proxy for it. These method calls are called “Messages”. Messages are serialized using “formatter” class and sent to client “Channel” as shown in Figure 11.2. Client Channel communicates with Server Channel. Server Channel uses as formatter to deserialize the message and sends to the remote object.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 2

Question 4.
Which class does the remote object has to inherit?
Answer:
All remote objects should inherit from System.MarshaibyRefobject.

Question 5.
What are two different types of remote object creation mode in .NET remoting?
Answer:
There are two different ways in which object can be created using Remoting:

  • SAO (Server Activated Objects) is also called a well-known call mode.
  • CAO (Client Activated Objects)

SAO has two modes “Single Call” and “Singleton”. With Single Call object, the object is created with every method call thus making the object stateless. With Singleton, the object is created only once and the object is shared with all clients.
CAO is stateful as compared to SAO. In CAO, the creation request is sent from the client side. The client holds a proxy to the server object created on the server.

Question 5.
What are the basic steps to implement remoting?
Answer:
Enabling remoting is a four-step process:

  • Create the interface which will act as a proxy between server and client. ;
public interface Mylnterface
{
       string SayHello(string strName);
}
  • Implement the interface and inherit the class from ‘MarshalByRefObjecf.
public class ClsHello: MarshalByRefObject, Mylnterface
{
       public string SayHello(string strName)
       {
           return "Hello from Remoting " + strName;
       }
}
  • Create the server and host the object on a specific channel and formatter. In the below code snippet we have hosted ‘cIsHello’ on the HTTP channel and binary formatter.
static void Main(string[] args)
{
       HTTPChannel objHTTPChannel = new HTTPChannel(1234);
       Console.WriteLine("Channel initialized");
       ChannelServices.RegisterChannel(objHTTPChannel, false);
       Console.WriteLine{"Channel Registered");
       RemotingConfiguration.RegisterWellKnownServiceType
       (typeof(ClsHello), "MySite", WellKnownObjectMode.Singleton);
       Console.WriteLine("Remoting Service Activated");
       Console.ReadLine( );
}
  • Create a client who can call the object via an interface and start making method calls.
static void Main(string[ ] args)
{
      HTTPChannel objChannel = new HTTPChannel();
      ChannelServices.RegisterChannel(objChannel, false);
      Mylnterface iobj = (Mylnterface)
      Activator . GetObj ect (typeof (Mylnterface)., "HTTP: //localhost:
      1234/MySit e");
      Console.WriteLine(iobj.SayHello("Shiv"));
      Console.ReadLine();
}

Question 6.
What are the drawbacks of remoting and how can we overcome the same?
Answer:
The biggest drawback of remoting is that at both the ends, i.e., client and server it should be. NET. In other words, clients which are not .NET like Java cannot call the server methods and functions.
It can be overcome by using Web services.

Question 7.
What is a Web Service?
Answer:
Web Services are business logic components, which provide functionality via the Internet using standard protocols, such as HTTP.

Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business functionality.
SOAP defines a standardized format in XML, which can be exchanged between two entities over standard protocols such as HTTP.

SOAP is platform independent so the consumer of a Web Service is therefore completely shielded from any implementation details about the platform exposing the Web Service. For the consumer, it is simply a black box of send and receives XML over HTTP. So any Web service hosted on windows can also be consumed by UNIX and Linux platforms.

Question 8.
What’s the difference between Web services and remoting?
Answer:
Remoting works only when both the ends, i.e., server and client are in .NET technologies. Web services are useful when the client is not .NET like Java, etc.

Question 9.
What is UDDI?
Answer:
The full form of UDDI is Universal Description, Discovery, and Integration. It is a directory that helps to publish and discover Web services.

Question 10.
What is DISCO?
Answer:
It is a Microsoft technology for publishing/discovering Web services. DISCO can define a document format along with an interrogation algorithm, making it possible to discover the Web Services exposed on a server. DISCO makes it possible to discover the capabilities of each Web Service (via documentation) and how to interact with it. To publish a deployed Web Service using DISCO, you simply need to create a .disco file and place it in the root along with the other service-related configuration.

Question 11.
What Is WSDL?
Answer:
Web Service Description Language (WSDL) is a W3C (World Wide Web Consortium) specification that defines an XML grammar for describing Web Services.XML grammar describes details, such as:

  • Where we can find the Web Service (its URI or Universal Resource Identifier)?
  • What are the methods and properties that service supports?
  • Data type support.
  • Supported protocols

In short, it is a Bible of what the Web service can do. Clients can consume this WSDL and build proxy objects that clients use to communicate with the Web Services. Full WSDL specification is available at HTTP: //www.w3.org/TR/wsdl.

Question 12.
What are the steps to create a Web service and consume it?
Answer:

  • Create a new project by selecting the template “ASP.NET Web Service Application”.
  • Expose the function which needs to be consumed by clients using the ‘ WebMethod’ attribute.
[WebMethod]
public string HelloWorldf)
{
return "Hello World";
}
  • Create a client like Windows application, right-click on the client and add Web reference. This creates a simple proxy at the client side.
  • Create the object of the proxy and invoke the function and methods of the Web service.

Question 13.
How do we secure a Web service?
Answer:
Web services follow the same ASP.NET authentication methodologies, i.e., windows, forms, and passports.
In the Web service Web. config file you can specify the authentication methodology and provide the credentials from the client using the below code snippet.

ServiceReferencel.ServicelSoapClient obj = new
ServiceReferencel.ServicelSoapClient( );
obj.ClientCredentials.UserName.UserName = "shiv";
obj.ClientCredentials.UserName.Password = "shiv@123";

Question 14.
Does Web service have a state?
Answer:
You can use session variables to maintain the state in Web service.

Question 15.
What is SOA?
Answer:
SOA is an architectural style for building business applications using loosely coupled services that communicate using standard messages like XML.

Question 16.
What are WS-* specifications?
Answer:
In order to standardize SOA Microsoft, IBM, SUN and many other big companies came together and laid down a specification called WS-* which will bring SOA to a common platform.
Some of the below specifications are defined below:

• Messaging (WS-Addressing): SOAP is the fundamental protocol for Web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML Optimized Packaging (XOP). Because the data will be sent in a binary and optimized format, it will give us huge performance gain.

• Security (WS-Security, WS-Trust, and WS-Secure Conversation): All the three WS-define authentication, security, data integrity and privacy features for a service.

• Reliability (WS-Reliable Messaging): This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.

• Transactions (WS-Coordination and WS-Atomic Transaction): These two specifications enable transactions with SOAP messages.

• Metadata (WS-Policy and WS-Metadata exchange): WSDL is an implementation of WS- Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.

Question 17.
How does Microsoft implement SOA and the above WS-* specifications?
Answer:
By WCF, Windows communication foundation.

Question 18.
What is WCF?
Answer:
WCF helps to implement SOA and WS-* specifications. WCF is a combination of:

  • NET remoting
  • MSMQ (Microsoft Message Queue)
  • Web services
  • COM+.

Question 19.
What’s the difference between WCF and Web services?
Answer:

  • WCF services can be hosted in multiple protocols like HTTP, TCP, etc. Web services can only be hosted on HTTP protocol.
  • WCF has COM+ so you can call two different WCF services in a transaction, we cannot call two different Web services in one transaction.
  • WCF integrates with MSMQ, for Web services we will need to write code.

In simple words below equation shows the difference with the simple equation.

WCF = Web services + Remoting + MSMQ + COM+
Web service = WCF - (Remoting + MSMQ + COM+ )

Question 20.
What are endpoint, contract, address, and bindings?
Answer:
When we want to host any WCF service we need to provide where to host it, how to host it, and what
to host.
• Contract (What): Contract is an agreement between two or more parties. It defines the protocol of how clients should communicate with your service. Technically, it describes parameters and returns values for a method.

• Address (Where): An Address indicates where we can find this service. The address is a URL, which points to the location of the service.

• Binding (How): Bindings determine how this end can be accessed. It determines how communications are done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications mediums, two bindings will be created.

• Endpoint: It is the combination of contract, address, and binding. In WCF Web. config file we can specify an endpoint, address, binding, and contract as shown in the below code snippet.

<endpoint address=”HTTP: //www. questpond. com” binding-”wsHTTPBinding” contract=”WcfService3.1Service 1 ">
Note: You can also remember endpoint by ABC where A stands for Address, B for Bindings, and C for Contract.

Question 21.
What are the main components of WCF?
Answer:
We need to define three main components in WCF:

  • Service class
  • Hosting environment
  • Endpoint

Question 22.
What are a service contract, operation contract, and data contract?
Answer:
Other than address, binding, and contract we also need to specify the service name, function/methods of the service and data types exposed by the service.
A service contract defines the service name, while an operation contract defines functions/methods associated with the service. Below is a simple sample of the service contract and operation contract.

[ServiceContract]
public interface InvoiceService
{
[OperationContract]
bool Pay(Invoice Obj);
}

Data Contract defines complex data types. Simple data types like int, Boolean, etc., can be recognized but for custom class data types like a customer, supplier, etc., we need to define them by using data contract. Below is a simple sample of a custom data type invoice class.

[DataContract]
public class Invoice
{
      string __InvNumber = true;
      DateTime _InvDate ;

      [DataMember]
      public stringlnvNumber
      {
           get { return _InvNumber; }
           set { _InvNumber = value; }
      }
      [DataMember]
      public DateTimelnvDate
      {
           get { return _InvDate; }
           set { _InvDate = value; }
      }
}

Question 23.
What are the various ways of hosting a WCF service?
Answer:
There are three major ways to host a WCF service:

• Self-hosting: In this user hosts the WCF service in his/her own app domain.
• II hosting: In this, the WCF service is hosted on IIS (Internet Information Service) server.
• WAS: You can also host WCF service on special server software called WAS (Windows Activation Server).

Question 24.
How do we host a WCF service in IIS?
Answer:
In order to host a WCF service in IIS, we need to create a . SVC file and the.SVC file will have the behind code of the WCF service.
By default when you create a WCF service the SVC file is created which the IIS reads to understand how to run the WCF service in IIS.

IIS hosting Self-hosting
As WCF service is hosted inside the shell of IIS we get all benefits of IIS like process recycling, automatic activation, the security feature of IIS, etc. IIS only works for HTTP protocol. In self-hosting, we need to take care of all these things ourselves. That means a lot of coding. We can use any protocol for self-hosting.
In other words, if its HTTP IIS is the best hoster if its other protocols self-hosting is the only option left.

Automatic activation

IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in the case of self-hosting, the service should always be running.

Process recycling

If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok, let us try to understand what is recycling in the IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, the process stops and you lose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle By restarting the worker process ensures any bad code or memory leak does not cause the issue to the whole system.

Question 25.
What are different bindings supported by WCF?
Answer:
WCF includes predefined bindings. They cover most of the bindings widely needed in day-to-day applications.

BasicHTTPBinding: It is simple SOAP over HTTP with no encryption.

wsHTTPBinding: It is the same as BasicHTTPBinding but encrypted.

NetTcpBinding: This binding sends binary-encoded SOAP, including support for reliable message _ transfer, security, and transactions, directly over TCP.

NetNamedPipesBinding: This binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.

NetMsmqBinding: This binding sends binary-encoded SOAP over MSMQ. This binding can only be/used for WCF-to-WCF communication.

Question 26.
What is the difference between BasicHTTPBinding and WsHTTPBinding?
BasicHTTPBinding is a plain SOAP message while wsHTTPBiding is an encrypted SOAP message.

WsHTTPBinding = BasicHTTPBinding + Encryption

Question 27.
Can we overload WCF service methods and functions?
Answer:
You can overload on the server-side but at the client-side, they have to be referred by different names. You can see in the below code snippet add is an overloaded method but the client will identify them with different names i.e. ‘Addintegers’and’AddDoubie’.

[ServiceContract]
interface Icalculator
{
     [OperationContract(Name="Addintegers")]
     int Add(int a, int b)

     [OperationContract(Name="AddDouble")]
     double Add(double a, double b)
}

Question 28.
What is a one-way operation?
Answer:
Many times we have WCF service methods and functions that have a long-running routine. We would like the WCF client to make calls to these functions asynchronously. In other words, the WCF client calls the functions and goes ahead doing their work and the WCF service completed its work at his own leisure.
This is achieved by marking isOneWay=true on the operation contract as shown in the below code snippet.
When you mark is One way as true the function should not return anything. In a one-way operation, the WCF service does not intimate the client when done. It is like fire and forgets.

[ServiceContract]
public interface IServicel
{
[OperationContract(IsOneWay=true)]
void CallMe( );
}

In the implementation, we have made a sleep of 15 seconds.

public class Servicel: IServicel
{
      public void CallMe( )
     {
             Thread.Sleep(15000);
     }
}

Question 29.
In one way contract we do not get calls back, how can we solve the same?
Answer:
By using a duplex contract.
In duplex contracts when the client initiates an operation the server service provides a reference call back URI (Universal Resource Identifier) back to the client. So the client initiates a call using the proxy class and when the server finishes its work it notifies the client using the callback channel. This is called duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.

Question 30.
How can we host a service on two different protocols on a single server?
You can host WCF sen/ice in two different bindings by providing two different end points as shown in the below code snippet.

<endpoint address="" binding="wsHTTPBinding"
contract="WcfService3.IServicel”/>
<endpoint address="" -binding="BasicHTTPBinding"
contract="Wcf Service3 . IServicel11 />

Question 31.
How can we integrate WCF services with MSMQ?
Answer:
By hosting your “NetMsMqBinding”.

Question 32.
How can we do security in WCF services?
Answer:
There are two ways of doing WCF security Transport security and message security.
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level.

WCF uses transport protocols like TCP, HTTP, MSMQ, etc., and every one of these protocols has its own security mechanisms. One of the common implementations of transport-level securities is HTTPS (HyperText Transfer Protocol Secure). HTTPS is implemented over HTTP protocols with SSL (Source Socket Layer) providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message level security is implemented with message data itself. Due to this, it is independent of the protocol. Some of the common ways of implementing message-level security are by encrypting data using some standard encryption algorithm.

Question 33.
In what scenarios will you use message security and transport security?
Answer:

Transport Message
Scenarios when we should be using one of them When there are no intermediate systems in between this is the best methodology. If it is an intranet type of solution this is the most recommended methodology. When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.
Advantages • Does not need any extra coding as protocol inherent security is used.

•Performance is better as we can use hardware accelerators to enhance performance.

• There is a lot of interoperability support and communicating clients do not need to understand WS security as it is built in the protocol itself.

•Provides end-to-end security as it’s not dependent on the protocol. Any intermediate hop in-network does not affect the application.

• Supports a wide set of security options as it is not dependent on the protocol. We can also implement custom security.

• Needs application refactoring to implement security.

Disadvantages • As it’s a protocol implemented security so it works only point to point.

• As security is dependent on the protocol it has limited security support and is bounded to the protocol security limitations.

• As every message is encrypted and signed there are performance issues.

• Does not support interoperability with old ASMX (Active Server Methods (Microsoft filename extensions)) Web services/

Question 34.
Where do we specify security options in WCF services?
Answer:
There is a security tag in the Web. config file where we can specify if we want to use transport security or message security. Below is a simple code snippet for the same.

<bindings>
<wsHTTPBinding>
<binding name="TransportSecurity"> ..
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHTTPBinding>
</bindings>

Question 35.
What are the different ways of doing WCF concurrency?
Answer:
There are three ways of configuring WCF concurrency.

Single: A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is not completed.

Multiple: In this scenario, multiple requests can be handled by the WCF service object at any given
moment of time. In other words, requests are processed at the same time by spawning multiple threads on the WCF server object.

So you have great throughput here but you need to ensure concurrency issues related to WCF server objects.

Reentrant: A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call the WCF client through callback and reenter without deadlock.
WCF concurrency is configured by using the concurrency mode attribute as shown in Figure 11.3.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 3

Question 36.
What are different ways of doing WCF instancing?
Answer:
Per Call: New instances of WCF service are created for every call made by the client.
Per session: One instance of WCF service is created for a session.
Single instance: Only one instance of WCF service is created for all clients.
To configure WCF instancing we need to use the instance context mode attribute on the service as shown below.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)]
public class Service: IService
{
}

Question 37.
What is REST?
Answer:
REST stands for REpresentational State Transfer. REST is an architectural style where our services can communicate using simple HTTP GET, POST methods rather than using the complicated SOAP format.

Question 38.
How can we make WCF rest enabled?
Answer:
To enable a WCF service with REST principles we need to specify the binding as ‘ WebHttpBinding’ in our endpoint.

<endpoint address=”" binding="WebHTTPBinding” contract=”IService”
behaviorConfiguration=”WebBehavior1 ">

We also need to specify which HTTP method will invoke the function i.e. GET or POST by using the ‘ webinvoke’ attribute as shown in the below code snippet.

[OperationContract]
[Webinvoke.(Method = "GET", ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetData/{value}")]
string GetData(string value

Question 39.
Can we call two WCF services in one transaction?
Answer:
Yes, we can call two WCF services in one transaction using the transaction flow attribute. So if you have two WCF services called in one transaction either both of the commits or none of the commits.
In order to enable transactions in the WCF service, we need to use the transaction flow attribute as shown in the below code snippet.

[ServiceContract]
     public interface IServicel
     {
           [OperationContract]
           [TransactionFlow(TransactionFlowOption.Allowed)]
           void UpdateData( );
     }

You also need to define transaction flow as true for wsHttpBinding and this binding you need to specify in the end point.

<bindings>
<wsHTTPBinding>
<binding name="TransactionalBind" transactionFlow="true"/>
</wsHTTPBinding>
</bindings>

<endpoint address="" binding=''wsHTTPBinding"
bindingConfiguration="TransactionalBind"
contract="WcfServicel.IServicel”>

Finally, you can call both the WCF services in one transaction using the transaction scope object as shown in the below code snippet.

using (TransactionScope ts = new
TransactionScope(TransactionScopeOption.RequiresNew))
{
     try
     {
           ServiceRef erenc'el. ServicelClient obj = new
           ServiceReferencel.ServicelClient();
           obj.UpdateData( );
           ServiceReference2.ServicelClient obj1 = new
           ServiceReference2.ServicelClient( );
           obj1.UpdateData() ;
           ts . Complete ( );
     }
     catch (Exception ex)
     {
           ts.Dispose( );
     }
}

Question 40.
How can we enable debugging and tracing on WCF services?
Answer:
WCF has ready-made trace objects as shown in the below table.

Assembly Name Description
System.ServiceModel Logs the following:

•             Message process

•             Reading of configuration information

•             Transport-level action

•             Security requests

System.ServiceModel.MessageLogging Generates tracing information for every message that flows through the system.
System.ServiceModel.IdentityModel Generate trace data for authentication and authorization.
System.ServiceModel.Activation Emits information regarding activation of the service.
System.Runtime.Serialization Emits information when objects are serialized or deserialized. WCF always serializes and deserializes information during request so it’s a good event to see the content of the request.
System.10.Log Emits messages with respect to Common Log File System (CLFS).
CardSpace Emits trace messages related to any CardSpace identity processing that occurs within WCF context.

We can then enable tracing using the <system, diagnostics tag as shown in the below code snippet. Depending on your needs you can make an entry of the trace objects in the Web.config file.

<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing">
<listeners>
<add name="log"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c: \Traces.svclog" />
</listeriers>
</source>
</sources>
</system.diagnostics>

Now if you run the WCF service you can see a XML file created as shown below.

#<E2ETraceEvent xmlns="HTTP: //schemas.microsoft.com/2004/06/E2ETraceEvent"> 
<System xmlns = "HTTP: //schemas.microsoft.com/2 0 04/0 6/windows/eventlog/
system">
<EventID>0</EventID>
<Type>3</Type>
<SubType Name="Transfer">0</SubType>
<Level>2 55</Level>
<TimeCreated SystemTime="2009-04-30T03: 21: 09.5625000Z" />
<Source Name="System.ServiceModel" />
Correlation ActivitylD-"{00000000-0000-0000-0000-000000000000}" 
RelatedActivityID="{dll829b7-d2db-46d5-a4ac-49a37a56376e}" />
<Execution ProcessName= "WebDev.Webserver" ProcessID=''2660 11 ThreadID="8" / >
Channel />
<Computer>COMPAQ-JZP37MD0</Computer>
</System>
<ApplicationData></ApplicationData>
</E2ETraceEvent>

Question 41.
How are exceptions thrown in WCF?
Answer:
If you want to inform the WCF client that there is an error we need to throw a “FaultException” as shown in the below code snippet.

throw new FaultException(Error.Message. ToStringQ);
Note: A cross-question after this question can be, why can’t we raise a normal .NET exception.
 In other words, he will try to compare normal exceptions with fault exceptions. The next question answers
 the same in detail.

Question 42.
What is the difference between WCF fault exceptions and .NET exceptions?
Answer:
If you throw a normal .NET exception from a WCF service as shown in the below code snippet.

throw new Exception(“Divide by zero”);

Your WCF client will get a very generic error with a message as shown in Figure 11.4. Now this kind of message can be very confusing as it does not pinpoint what exactly the error is.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 4

If you use a raise a fault exception as shown in the below code, your WCF clients will see the complete clear error rather than a generic error as shown previously.

throw new FaultException(“Divide by zero”);

your WCF client will now see a better error description as shown in figure 11.5.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 5

Question 43.
What is the difference between Service endpoint and Client endpoint?
Answer:
The endpoint in WCF service is the combination of three things address, binding and contract. Service endpoint is for the server, where your WCF service is hosted (See Figure 11.6). Service endpoint defines where the service is hosted, what are the bindings and the contract, i.e., methods and interfaces.

Remoting, Web Services and WCF Interview Questions in .NET chapter 11 img 6

While client endpoint is for the client. Client endpoint specifies which service to connect, where it is located, etc.
Code of WCF Server endpoint looks something as shown below.

<service name="WcfService3.Service1”
behaviorConfiguration="WcfService3.ServicelBehavior">
<endpoint address="" binding="wsHTTPBinding"
contract="WcfService3.IServicel">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>

WCF Client end point code looks something as shown below. This is generated when you add service reference using add service reference.

<client>
<endpoint address="HTTP: //localhost: 9201/ServiCel.svc"
binding="wsHTTPBinding"
bindingConfiguration="WSHTTPBinding_IServicel"
contract="ServiceReferencel.IServicel"
name="WSHTTPBinding_IServicel">
<identity>
<dns value="localhost" />
</identity>
</endpoint></client>

Servlet jsp interview question – Servlets & Jsp Interview Questions in Java

Servlet jsp interview question: We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on Servlets & Jsp

Question 1.
What are servlets? And, what purpose do they serve?
Answer:

SERVLETS & JSP Interview Questions in Java chapter 6 img 1

Servlets are Java programs run on Web or application servers, acting as the middle layer between requests coming from web browsers or other HTTP clients and databases or applications on the HTTP server. As illustrated in Figure 6, their job is to perform the following tasks:-

(1) Read the explicit data sent by the client: The end-user normally enters this data in an HTML form on a Web page. However, the data could also come from an applet or a custom HTTP client program.

(2) Read the implicit HTTP request data sent by the browser: The HTTP information includes cookies, information about media types, and compression schemes the browser understands, and so on.

(3) Generate the results: This process may require talking to a database, executing an RMI or EJB call, invoking a Web service, or computing the response directly.

(4) Send the explicit data (i.e. the document): This document can be sent in a variety of formats such as text (HTML or XML), binary (GIF images), or even a compressed format like gzip that is layered on top of some other underlying format.

(5) Send the implicit HTTP response data: Sending the implicit HTTP response data (besides the explicit document itself) involves telling the browser or other client what type of document is being returned (e.g. HTML), setting cookies, and caching parameters, and other such tasks.

Question 2.
What is the underlying need to build web pages dynamically?
Answer:
Servlets and JSP technology has become the technology of choice for developing online stores, interactive Web applications, and other dynamic Web sites. There are a number of reasons why Web pages need to be built on the fly:-

(1) The Web page is based on data sent by the client: For instance, the results page from search engines and order confirmation pages at online stores are specific to particular user requests. You never know what to display until you read the data that the user submits.

(2) The Web page is derived from data that changes frequently: If the page changes for every request, then you certainly need to build the response at request time, e.g. a weather report or a news headlines site might build the pages dynamically, perhaps returning a previously built page if that page is still up to date.

(3) The Web page uses information from corporate databases or other server-side sources: If the information is in a database, you need server-side processing even if the client is using dynamic Web content such as an applet. Going from the client to the Web tier to the database (a three-tier approach) instead of from an applet directly to the database (a two-tier approach) provides increased flexibility and security with little or no performance penalty. In fact, a three-tier approach is often faster because the middle tier can perform caching and connection pooling.

Question 3.
Give a sample servlet code and point out its main features.
Answer:
A sample servlet code that results in displaying – WELCOME – is the following:-

import java.io.*;
import javax.servlet. *;
import javax.servlet.http. *;
public class WELCOMEServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, lOExccption
{
     response.setContentTypeC'text/html");
     PrintWriter out = response.get Writerf);
     String docType = "<!DOCTYPE HTML PUBLIC \"
                 - // W3C // DTD HTML 4.0 “ +
                 "Transitional // EN\ ">\n”;
         out.princln!docType +
         “<HTML>\n" +
        " /<HEAD><TITLE>WELCOME</TITLEx/HEAD>\n'' +
        "<BODY BGCOLOR= \ "FDF5E6\ "In" +
        "<H1>WELC0ME< lHl>\n” +
        “ </BODYx/HTML>");
     }
  }

There are essentially four points to note in the above servlet code:-

  1. It is regular java code: There are new API’s but no new syntax.
  2. It has unfamiliar import statements: The servlet and JSP API’s are not part of the Java 2 Platform, Standard Edition (J2SE); they are a separate specifications and are also a part erf the Java 2 Platform, Enterprise Edition (J2EE).
  3. It extends a standard class (HttpServlet): Servlets provide a rich infrastructure for dealing with HTTP.
  4. It overrides the doGet method: Servlets have different methods to respond to different types of HTTP commands.

Question 4.
What are the advantages of servlets over traditional CGI?
Answer:
Java servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies.

Question 5.
Why is HTTP referred to as a stateless protocol?
Answer:
HTTP is called a stateless protocol since every request is independent of the previous request. The server doesn’t keep track of whether the same user is making repeated requests.

Question 6.
What is the order in which the life cycle methods are called in a Servlet/HttpServlet and which are the ones that can be overridden?
Answer:
The order of the life cycle methods in a Servlet/HttpServlet is enumerated as under:-

(1) init( ): Called only once during the initialization of the Servlet.

(2) destroy( ): Called only once when a Servlet instance is about to be destroyed.

(3) service( ): Do not override this method.

(4) doGet( ), doPostO, doPutO, doDeleteO, doOptionsO, do trace!): These methods are called according to the type of HTTP request received. Override them to generate your own response.

(5) log( ): Writes messages to the Servlet’s log files.

(6) get the last modified( ): Override this method to return your Servlet’s last modified date.

(7) getServletlnfo( ): Override this method to provide a String of general information about your Servlet such as author, version, copyright, etc.

(8) getServletName( ): Override this method to return name of the Servlet.

(9) getlnitParameter( ), getlnitParameterNames( ): The first one returns the value of the given initialization parameter, the second one returns an Enumeration object containing the names of all initialization parameters provided.

Question 7.
Bring out the difference between GET and POST requests.
Answer:
The HTML specifications technically define the difference between “GET” and “POST” so that the former means that form data is encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. Thus, we can say that “GET is basically for just getting/retrieving data while “POST” may involve anything such as storing/ updating data, ordering a product or sending an E-mail, etc.

Question 8.
Bring out the difference between ServletContext and HttpSession.
Answer:
The interface ServletContext defines a set of methods that a servlet uses to communicate with its servlet container, e.g. to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per “web application” per JVM that can be used as a location to share global information.

The interface HttpSession provides a way to identify a user across more than one-page requests or visit a website and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. This interface alloivs servlets to:-

  1. View and manipulate information about a session such as the session identifier, creation time and last accessed time, etc.
  2. Bind objects to sessions, allowing user information to persist across multiple user connections.

Question 9.
Bring out the difference between forward!) and sendRedirect( ) methods.
Answer:
forward( ): It finds the Servlet on the local server, and calls its service (request, response) method, passing the same request and response that was used by the current page. The parameters stored in the request object are available to the called request when we forward a request, and the URL in the address bar will not change.

sendRedirect( ): It sends a response to the client with a meta-refresh that makes the client send a new request to the page specified. We can also make requests to pages other than those on the local server as well. The parameters stored in the request object are lost when we redirect . and the url in the address bar will change.

Question 10.
Are variables declared at the class level in a servlet thread-safe? Explain in brief.
Answer:
There is only one copy of the instance variables per instance of the servlet and all of the threads share this copy. In case of the multithreaded model, multiple threads may access an instance variable simultaneously, which makes it unsafe. In the case of a single-threaded model, only one thread executes the methods of a servlet instance at a tiirie. Whence, an instance variable is thread-safe in this case.

By wrapping non-thread-safe code in a synchronized block, you can force the requesting thread to acquire the instance lock in order to gain access to the code block, thus making it safe, e.g.

synchronized this)
   {
   ctr++;
   }

Question 11.
How many instances of a servlet are created?
Answer:
Only one instance of a servlet gets created. And, this instance is accessed by all the requests hitting the server.

Question 12.
How can you make a servlet Single-threaded and how many instances are created in this case?
Answer:
A servlet can be made thread-safe by implementing the SingleThreadedModel interface. The number of instances created depends upon what the Servlet container decides to do. It may just create one instance; it might create more.

Question 13.
What is the argument of the init( ) method? What is ServIetConfig and what does it contain? Elaborate.
Answer:
An object of type ServIetConfig is passed. ServIetConfig is an interface. A servlet configuration object is used by a servlet container to pass information to a servlet during initialization. Two of the methods available are:-

  1. getServletName( )
  2. getServletContext( )

Question 14.
What are the exceptions thrown by the service method?
Answer:
The exceptions thrown are:-
ServletException and lOException.
ServletException is thrown to report any problems encountered in the servlet engine trying to service the HTTP request while an lOException can be thrown when using the PrintWriter object to stream web resources back to the client browser.

Question 15.
What will happen if the service method in HttpServlet is overridden?
Answer:
If we override the service method in an HttpServlet, we have to take care of calling the default service method. In some cases, it does make sound sense to override the service method, e.g. when you have a lot of Servlets that need to perform the same checks (like, is the session authenticated?) before processing the request.

Rather than having to copy the logic into each Servlet you write, you can develop a common base class which extends HttpServlet. The logic inside the method is effectively as follows:-

service(...)
{
common processing logic ....
super.service(...);
}

Another option is to write the logic in a helper method and call it at the beginning of both the doGet and doPost methods. . .

Question 16.
How can you keep track of the sessions created in a servlet container? Elaborate.
Answer:
The session can be kept track of using the following two objects:-

(1) HttpSessionListener: Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.

(2) HttpSessionEvent: This is the class representing event notifications for changes to sessions within a web application.

Question 17.
How does an object know when it is put in session?
Answer:
An object can know when it is put in session by means of the following two events:-

(1) HttpSessionBindingListener: This causes an object to be notified when it is bound to or unbound from a session. The object is notified by an HttpSessionBindingEvent object:
(a) The method valueBound(HttpSes$ionBindingEvent event) – notifies the object that is being bound to a session and identifies the session.
(b) The method valueUnbound(ElttpSessionBindingEvent event) – notifies the object that is being unbound from a session and identifies the session.

(2) HttpSessionBindingEvent: It has methods like getName which returns the name with which the object is bound to or unbound from the session.getSession which returns the session to or from which the object is bound/unbound.

Question 18.
How do you set the session time out for a session? Can you make it infinite; if yes, how?
Answer:
The method setMaxInactivelnterval in HttpSession can be used to set the timeout.

public void setMaxInactivelntervaldnt interval)

where interval specifies the time in seconds between client requests before the servlet container will invalidate this session. A negative time indicates that the session should never timeout (infinite timeout).

Question 19.
What are the methods available in HttpSessionListener?
Answer:
sessions created and session destroyed are the two methods available in HttpSessionListener. An HttpSessionEvent object is passed to these methods by the container when a new session is created or when an existing session is destroyed.

Question 20.
How do you carry out session management?
Answer:
Since HTTP is a stateless protocol, we use a variety of methods to maintain information on the history of actions performed during a session. There are four ways in which we can do session management, enumerated as under:-

(1) Cookies: A cookie is a piece of information stored on the client machine by the browser. Cookies are widely used by various server-side programming techniques for the purpose of implementing session tracking. The cookie is a text file that is stored on the client machine. These cookies are sent to the server whenever a user makes a request to the same server from which the cookies were created. The Java API provides us various classes and methods designed to allow us to use cookies in servlets. Some of the places where a cookie can be used are storing user preferences, shopping cart applications, etc.

(2) URL Rewriting: In this method, the data is appended to the URL over successive requests. In addition to the current data, the values of the previous data with which the user invoked the servlet are retrieved from the incoming URL and appended to the new URL. In other words, the parameter values for each successive URL that is generated match those of the previous URL. In addition, new parameter values are added which represent the current data.

(3) Hidden Fields: IN HTML, we have a type of field called HIDDEN. This type of field is not visible on the browser but gets passed to the application server. Every time the client makes a request to the server, an HTML form is created and sent back to the client. Hidden fields are added to the form each time it is created. The hidden fields contain the data from the previous request that would be required in the future. requests. Using this approach, the historical data is saved by embedding it in the new
HTML database or in the server’s file system.

(4) HttpSessiomThe HttpSession object is created and maintained by the application server. We can get hold of the session object using request.getSession(true) where the request is of type HttpServletRequest. Once we have a handle on this object, we can store data in this object, and this data is shared between the various requests coming from the same user in one session, i.e. from one browser window. Sessions are used to maintain state i and user identity across multiple page requests. The session persists for a specified time period. We can add and retrieve objects from a session using the following two methods:

  • void setAttribute(java.lang.String name, java. lang.Object value);
  • java.lang.Object getAttribute!java.lang.String name);

Question 21.
Give a sample JSP code and point out its main features.
Answer:
A sample JSP code that uses a request parameter to display the title of a book is the following:-

<!DOCTYPE HTML PUBLIC “ - // W3C // DTD HTML 4.0 Transitional // EN">
<HTML>
<HEAD>
<TITLE>WELCOME</TITLE>
<LINK REL=STYLESHEET
HREF-"JSP-Styles.css"
TYPE-"text / css">
</HEAD>
<BODY>
<H2>Order Confirmation</ H2>
Thank you for the order <lx%=request.getParameter("title") %>< /!>!
</BODYx/HTML>

There are essentially two points to note in the above JSP code:-

  1. It is mostly standard HTML.
  2. The dynamic code consists entirely of the half-line depicted in bold in the code.

Question 22.
Compare and contrast the role of JSP vis-a-vis servlets.
Answer:
A somewhat oversimplified view of servlets is that they are Java programs with HTML embedded inside of them. A somewhat oversimplified view of JSP documents is that they are HTML pages with Java code embedded inside of them. Thus, servlets look mostly like a regular Java class whereas a JSP document looks mostly like a normal HTML page. Despite the huge differences, the interesting thing is that behind the scenes, both are the same. In fact, a JSP document is just another way of writing a servlet. JSP pages get translated into servlets, the servlets get compiled and it is the servlets that run at request time.

So, the question is, if JSP technology and servlet technology are essentially equivalent in power, docs u matter, which you use? Of course, yes! The issue is not power, but convenience, ease of use, and maintainability. JSP is focused on simplifying the creation and maintenance of HTML whereas servlets are best at invoking business logic and performing complicated operations. A quick rule of the thumb is that servlets are best for tasks oriented towards processing while JSP is best for tasks oriented towards presentation. For some requests, servlets are the right choice; for other requests, JSP is a better option; for still others, neither JSP nor servlets alone are best and a combination of the two is best (as in MVC – Model View Controller architecture).

But, the point is that you need both JSP and servlets in your project. Almost no project mill consists entirely of servlets or entirely of JSP; you want both!

Question 23.
What are the benefits and needs of JSP? Elucidate.
Answer:
As we have already pointed out, although JSP and servlets are equivalent behind the scenes, servlets are not so good when it comes to presentation; they excel in tasks related to programming or data processing. Servlets suffer from the following deficiencies when it comes to generating the output:-

  1. It is hard to write and maintain the HTML;
  2. You cannot use standard HTML tools;
  3. The HTML is inaccessible to non-Java developers.

JSP technology offers the following benefits in this context:-

  1. It is easier to write and maintain the HTML;
  2. You can use standard website development tools;
  3. You can divide up your development team so that the Java programmers can Work on the dynamic code while the Web developers can concentrate and focus on the presentation layer/aspect.

Question 24.
What are the common misconceptions about JSP?
Answer:
Some of the common misunderstandings involving JSP are the following:-

  1. Forgetting that JSP is server-side technology;
  2. Confusing translation time with request time;
  3. Thinking JSP alone is sufficient;
  4. Thinking servlets alone is sufficient.

Question 25.
Explain in brief how a JSP is processed.
Answer:
A JSP is converted into a Servlet by the application server and then the request is serviced. Once compiled, the Servlet object created from the JSP remains in memory just like any other Servlet. When a change is made to the JSP then the servlet object gets re-created. This could very well vary depending upon the server.

Question 26.
What is an ‘include’? Enumerate the types of ‘includes’.
Answer:
We can use the <jsp: include an element to include either a static or dynamic resource in a JSP page. If the resource is static, its content is included in the calling JSP page as it is. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing of the remainder of the JSP page. If the included resource is dynamic, we can use a <jsp: param> clause to pass the name and value of the parameter to the resource, e.g. we can pass the user and a value to a login form that is coded in a JSP page.

Question 27.
Can you use Tag Libraries in a JSP; if yes, how?
Answer:
A tag library is a set of actions that encapsulate functionality. These tags are then used within JSP pages. This helps us to reuse common functionality like connecting to a database.

<%@ taglib prefix=”sql” url=http://java.sun.com/jstl/sql %>

For JSP pages that do not have a default database, <sql:setDataSource> can prepare a database for use.

The code snippet below shows how to create a data source.

<sql:setDataSource
var="example"
driver="oracle.jdbc.driver. OracleDriver "
url=''jdbc:oracle:thin:@<OracleServerName>:1521:OraclelnstanceName>”
user=" scott”
Password^” tiger”
/>

Question 28.
Can you explain how exception handling is done in JSP?
Answer:
You can specify the error page in the ‘page’ directive. Then, if an exception is thrown, the control will be transferred to that error page where you can display a useful message to the user about what happened and also inform your sysadmin about this exception depending, of course, on how important it is.

<%@ page errorPage=”ExceptionHandler.jsp”         %>
<%@ page isErrorPage= “true” import=”java.io.*”   %>

Question 29.
Enumerate the implicit objects in JSP.
Answer:
There are nine implicit objects that are available in a JSP enumerated as under:-

(1) Application is the broadcast context state available. It is equivalent to ServletContext. It allows the JSP page’s servlet and any Web components contained in the same application to share information.

(2) Config allows initialization data to be passed to a JSP page’s servlet. This is equivalent to the ServletConfig object passed to the init method in the Servlet.

(3) Exception houses exception data to be accessed only by designated JSP “error pages”.

(4) Out provides access to the servlet’s output stream.

(5) Page is the instance of the JSP page’s servlet processing the current request. Not typically used by JSP page authors.

(6) PageContext is the context for the JSP page itself. It provides a single API to manage the various scoped attributes. This API is used extensively when implementing JSP custom tag handlers.

(7) Request provides access to HTTP request data, as well as providing a context for associating request-specific data.

(8) Response enables direct access to the HTTPServletResponse object and is very rarely used by JSP authors.

(9) Session is perhaps the most commonly used of the state management contexts. It is useful in starting a user’s information when he accesses the web application over several requests.

Question 30.
Can you prevent caching of the page; if yes, how?
Answer:
You can use Microsoft Internet Information Server (IIS) to easily mark highly volatile or sensitive pages using the following script at the extreme beginning of the specific Active Server Pages (ASP) pages:-

<% Response.CacheControl = “no-cache” %>
<% Response.AddHeader “Pragma”, “no-cache” %>
<% Response.Expires = -1 %>

Question 31.
Why should we use beans?
Answer:
Although it is true that beans are merely Java classes that are written in a standard format, there are several advantages to their use. With beans in general, visual manipulation tools and other programs can automatically discover information about classes that follow this format and can create and manipulate the classes without the user having to explicitly write any code. In JSP in particular, the use of JavaBeans components provides three advantages over scriptlets and JSP expressions that refer to normal Java classes:-

(1) No Java syntax: By using beans, page authors can manipulate Java objects using only XML-compatible syntax, that is to say, no parentheses, semicolons, or curly braces.

(2) Simpler Object Sharing: When you use the JSP bean constructs, you can much more easily share objects among multiple pages or between requests than if you use the equivalent explicit Java code.

(3) Convenient correspondence between request parameters and object properties: The JSP bean constructs greatly simplify the process of reading request parameters, converting from strings, and putting the results inside objects.

Question 32.
Enumerate the various ‘scopes’ in a JSP.
Answer:
The various scopes in a JSP are enumerated below for your reference:-

(1) PageScope (<jsp:useBean … scope=”page” />: This is the default value, i.e., you get the same behavior even if you omit the scope attribute entirely. This default scope implies that in addition to being bound to a local variable, the bean object should be placed in the PageContext object for the duration of the current request. Storing the object like this ensures that the servlet code can access it by calling the getAttribute method on the predefined pageContext variable. Since every page and every request has a different PageContext object, using scope=”page” or omitting scope implies that the bean is not shared and thus a new bean will be created for each request.

(2) RequestScope (<jsp:useBean … scope=” request” />): This value implies that in addition to being bound to a local variable, the bean object should be placed in the HttpServletRequest object for the duration of the current request where it is retrievable through the getAttribute method.

(3) SessionScope (<jsp:useBean … scopes” session” />): This value implies that in addition to being bound to a local variable, the bean will be stored in the HttpSession object associated with the current request where it can be retrieved through the getAttribute method. Thus, this scope lets JSP pages easily perform session tracking.

(4) ApplicationScope (<jsp:useBean … scope-”application” />): This value implies that in addition to being bound to a local variable, the bean will be stored in the ServletContext available through the predefined application variable or by a call to getServletContext. The ServletContext is shared by all servlets and JSP pages in the Web application. Values in the ServletContext. can be retrieved through the getAttribute method.

Question 33.
Bring out the need for the MVC (Model View Controller) architecture.
Answer:
Servlets are great when your application requires a lot of real programming to accomplish its task. Servlets can manipulate HTTP status codes and headers, use cookies, track sessions, save information between requests, compress pages, access databases, generate JPEG images on the fly, and perform many other tasks efficiently and flexibly. But, generating HTML with servlets can be tedious and can yield a result that is hard to modify. That’s where JSP comes in. It allows you to write the HTML code in the normal manner, even using HTML-specific tools and putting your Web content developers to work on your JSP documents. JSP expressions, scriptlets, and declarations let you insert simple Java code into the servlet that results from the

JSP page and directives let you control the overall layout of the page. For more complex requirements, you can wrap Java code inside beans or even define your own JSP tags.

This all looks great. We seem to have everything. But, still, something is amiss. The assumption behind a JSP document is that it provides a single overall presentation. What if you want to give totally different results depending on the data that you receive? Scripting expressions, beans, and custom tags, although extremely powerful and flexible, do not overcome the limitation that the JSP page defines a relatively fixed, top-level page appearance. Similarly, what if you need complex reasoning just to find out the type of data that applies to the current situation? JSP is poor at this type of business logic.

The solution is to use both servlets and JSP. In this approach, known as the Model view controller (MVC) or Model 2 architecture, you let each technology concentrate on what it excels at. The original request is handled by a servlet. The servlet invokes the business logic and data access code and creates beans to represent the results (that is to say, the model). Then, the servlet decides what JavaServer Page is appropriate to present the particular results and forwards the request there (the JavaServer Page is the view). The servlet decides what business logic code applies and which JSP page should present the results (the servlet is the controller).

Question 34.
Elucidate the MVC (Model View Controller) Frameworks.
Answer:
The key desire behind the MVC approach is the desire to separate the code that creates and manipulates the data from the code that presents the data. The basic tools needed to implement this presentation-layer separation are standard in the servlet API. However, in very complex applications, a more elaborate MVC framework is sometimes beneficial. The most popular of these frameworks is Apache Struts discussed at length in one of the following chapters.

Although Struts is useful and widely used, you should not feel that you must use Struts in order to apply the MVC approach. For simple and moderately complex applications, implementing MVC from scratch with RequestDispatcher is straightforward and flexible. There is no need to get intimidated; in many situations, the basic approach is the best for the entire lifetime of your application. Even if you decide to use Struts or another MVC framework later, you will recoup much of your investment since most of your work will also apply to the elaborate frameworks.

Question 35.
How do you go about implementing MVC with RequestDispatcher?
Answer:
The most important point about MVC is the idea of separating the business logic and data access layers from the presentation layer. The syntax is quite simple and the steps required to implement MVC with RequestDispatcher are brought out succinctly below for your reference:-

(1) Define beans to represent the data: Beans are just Java objects that follow a few simple
conventions. The first step is to define beans to represent the results that will be presented to the user.

(2) Use a servlet to handle requests: In most cases, the servlet reads request parameters.

(3) Populate the beans: The servlet invokes business logic (application-specific code) or data-access code to obtain the results. These results are placed in the beans defined in step 1.

(4) Store the bean in the request, session, or servlet context: The servlet calls setAttribute on the request, session, or servlet context objects to store a reference to the beans that represent the results of the request.

(5) Forward the request to a JSP page: The servlet determines which JSP page is appropriate ” to the situation and uses the forward method of RequestDispatcher to transfer control to that JSP page.

(6) Extract the data from the beans: The JSP page accesses beans with jspniseBean and a scope matching the location of step 4. The page then uses jsp:getProperty to output the bean properties. The JSP page doesn’t create/modify the bean. It just extracts and displays data that the servlet created.

Question 36.
How do you go about securing Web applications?
Answer:
There are two major aspects to securing Web applications:-

(1) Preventing unauthorized users from accessing sensitive data: This process involves ‘act ess restriction’, that is, identifying which resources need protection and who should have access to them, and ‘authentication’, that is, identifying users to determine if they are one of the authorized ones. Simple authentication involves the user entering a username and password in an HTML form or dialog box while stronger authentication involves the use of X.509 certificates sent by the client to the server. This first aspect of Web security applies to virtually all secure applications. Even intranets at locations with physical access control usually require some sort of user authentication.

(2) Preventing attackers from stealing network data while it is in transit: This process involves the use of Secure Sockets Layer (SSL) to encrypt the traffic between the browser and the server. This capability is generally reserved for particularly sensitive applications or for particularly sensitive pages within a larger application. After all, unless the attackers are on your local subnet, it is exceedingly difficult for them to gain access to your network traffic.

These two security aspects are mostly independent. The approaches to access restriction are the same regardless of whether or not you use SSL. With the exception of client certificates (which apply only to SSL), the approaches to authentication are also identical whether or not you use SSL.

Within the Web application framework, there are two general approaches to this type of security:-

(1) Declarative Security. With declarative security, none of the individual servlets or JSP pages need any security-aware code. Instead, both of the major security aspects are handled by the server.

To prevent unauthorized access, you use the Web application deployment descriptor ‘ (web.xml) to declare that certain URLs need protection, and which categories of users should have access to them. You also designate the authentication method that the server should use to identify users. At request time, the server automatically prompts users for usernames and passwords when they try to access restricted resources,

automatically checks the results against a predefined set of usernames and passwords, and automatically keeps track of which users have been authenticated previously.

This process is completely transparent to the servlets and JSP pages. To safeguard network data, you use the deployment descriptor to stipulate that certain URLs should only be accessible with SSL. If users try to use a regular HTTP connection ‘
1 to access one of these URLs, the server automatically redirects them to the HTTPS (SSL) equivalent.

(2) Programmatic Security: With programmatic security, protected servlets and JSP pages ^ at least partially manage their own security. To prevent unauthorized access, each servlet or JSP page must either authenticate the user or verify that the user has been authenticated previously. To safeguard network data, each servlet or JSP page has to check the network protocol used to access it. If users try to use a regular HTTP connection to access some of these URLs, the servlet or JSP page must manually redirect them to the HTTPS (SSL) equivalent.

Question 37.
Outline the steps involved in Form-based authentication.
Answer:
Eight basic steps are involved in Form-based authentication:-
(1) Set up usernames, passwords, and roles: In this step, you designate a list of users and associate each with a password and one or more abstract roles (e.g., the normal user or ‘ administrator). This is a completely server-specific process. ;

(2) Tell the server that you are using form-based authentication; designate the locations of the login and login-failure page: This process uses the web.xml login-config element with an auth-method subelement of FORM and a form -login-config subelement that gives the location of the two pages. :

(3) Create a login page: This page must have a form with an ACTION of j_security_check, a ‘ METHOD of POST, a text field named j_username, and a password field named; j_password. ;

(4) Create a page to report failed login attempts: This page can simply say something like: “username and password not found” and perhaps give a link back to the login page.

(5) Specify which URLs should be password protected: For this step, you use the security constraint element of web.xml. This element, in turn, uses web-resource-collection and auth-constraint subelements. The first of these (web-resource-collection) designates the  URL patterns to which access should be restricted, and the second (auth-constraint) specifies the abstract roles that should have access to the resources at the given URLs.

(6) List all possible abstract roles (types of users) that will be granted access to any resource: Each abstract role is declared using the security-role element. The security-role element contains the required role-name element, which contains the name of the abstract role.

(7) Specify which URLs Should be available only with SSL: If your server supports SSL, you can stipulate that certain resources are available only through encrypted LITTPS (SSL)  connections. You use the user-data-constraint subelement of security-constraint for this j purpose.

(8) Turn off the invoker servlet: Security settings are based on URLs; so, you protect servlets by listing their URLs within web-resource-collection element. The servlet URLs, in turn, are normally defined with the url-pattern element of servlet-mapping. However, many servers also have a default servlet URL of the form http://host/webAppPrefix/ servIet/ServletName. If you have this capability enabled, there are now two URLs that can invoke each servlet: the URL registered in servlet-mapping and the default (invoker servlet) URL. Remembering to protect both addresses is too hard. Instead, disable the invoker servlet, either globally for your server, or by mapping the / servlet/ * pattern within your Web application.

Question 38.
Giv$ a brief description of the steps involved in creating servlet and JSP filters.
Answer:
Creating a basic servlet and JSP filter involves five steps:-

(1) Create a class that implements the Filter interface: Your class will need three methods: doFilter, init, and destroy. The doFilter method contains the main filtering code (step 2), the init method performs setup operations, and the destroy method does the cleanup operations.

(2) Put the filtering behavior in the doFilter method: The first argument to the doFilter method is a ServletRequest object. This object gives your filter full access to the incoming information, including form data, cookies, and HTTP request headers. The second argument is a ServletResponse-, it is mostly ignored in simple filters. The final argument is a FilterChain; it is used to invoke the servlet, JSP page, or the next filter in the chain as described in the next step.

(3) Call the doFilter method of the FilterChain object: The doFilter method of the Filter interface takes a FilterChain object as one of its arguments. When you call the doFilter method of that object, the next associated filter is invoked. If no other filter is associated with the servlet or JSP page, then the servlet or JSP page itself is invoked.

(4) Register the filter with the appropriate servlets and JSP pages: Use the filter and filter-mapping elements in the deployment descriptor (web.xml).

(5) Disable the invoker servlet: Prevent users from bypassing filter settings by using default servlet URLs.

Question 39.
List the event listeners that respond to Web application life-cycle events.
Answer:
There are eight kinds of event listeners that respond to Web application life-cycle events:-

(1) Servlet context listeners: These listeners are notified when the servlet context (i.e., the Web Application) is initialized and destroyed.

(2) Servlet context attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in the servlet context.

(3) Session listeners: These listeners are notified when session objects are created, invalidated, or timed out.

(4) Session attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in any session.

(5) Session migration listeners: These listeners are notified when the session objects are serialized and deserialized by the container. Usually, the serialization and deserialization of session objects occur when the container migrates the session objects from one machine to another.

(6) Session object binding listeners: These listeners are notified when the implementing object is added or removed from the session object.

(7) Request listeners: These listeners are notified when request objects are initialized and destroyed.

(8) Request attribute listeners: These listeners are notified when attributes are added to, removed from, or replaced in any request.

Question 40.
Give the full form of EL as related to JSP.
Answer:
Expression Language.

Question 41.
What do you understand by JSTL. Describe it briefly.
Answer:
JSTL is the JSP Standard Tag Library. It provides many useful tag libraries and has been universally accepted by the Java community. The most commonly used JSTL tag library is the core library, which contains the following tags: out, if,forEach,foretokens, choose, when, otherwise, set, remove, import, url, param, redirect, and catch.

Question 42.
Discuss any one of the JSTL tags briefly.
Answer:
Although any of the aforementioned tags can be discussed, here we shall only elucidate the c:set tag.
The c:set tag is used either for setting a scoped attribute or updating and creating bean properties and map values. The following are some of the common forms in which the c:set tag is used:-

<c:set var= “attributeName” valuer “someValue” />
<c:set target= “map” property= “clementKey” value= “elementValue” />
<c:set target= “bean” property= “name”>Arunesh Goyal</ c:set>
You may note that the c:set tag doesn’t specify the value attribute.

Question 43.
What areas does the JSTL cover?
ANS.
A particular set of tags has been collected into the JSP Standard Tag Library (JSTL) which is distributed along with the JSP framework. It covers the following areas:-

  1. Assigning to variables;
  2. Writing to the output stream;
  3. Catching exceptions;
  4. Conditionals;
  5. Iterations;
  6. URL construction;
  7. String formatting;
  8. SQL queries; and,
  9. XML manipulation.

UML interview questions – Unified Modelling Language (UML) Interview Questions in Java

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

Unified Modelling Language (UML) Interview Questions in Java

Question 1.
What is UML and how is it useful in designing large systems?
Answer:
Unified Modeling Language (UML) is a notational language that comprises several tools and techniques to support object-oriented development. UML captures scenarios (use case diagram), object interactions (sequence diagram), class interactions (class diagrams) and object states (state diagrams). UML helps in designing large and complex systems. It starts with an analysis of business requirement and coming up with basic business flow chart and static diagrams i.e. use case diagrams which gives a pictorial view of business requirements and captures scenarios.

The next step is Interaction diagrams, which mainly consist of Sequence diagrams. A Sequence diagram tells how objects interact with each other through message passing in most importantly in what sequence. Then classes are identified of the system with various class identification approaches like ‘Noun Phrase Approach’, ‘CRC Approach’, this exercise results in UML class diagrams.
A modular approach helps in breaking down the complex system where each module can further be divided into components like classes and objects. Once the whole system is defined in terms of reusability of objects, omitting unnecessary objects and classes. The building of skeleton code on best practices of coding, like the pattern-based approach, helps in the foundation of efficient code.

Question 2.
Is UML useful for procedural programming?
Answer:
Procedural programming is an unstructured way of programming that consists of a set of procedures/method calls/instructions to be executed sequentially in such a way to attain the objective of a program.UML can help here in a very basic way in laying out the sequence of executions of instructions.

Question 3.
What are different notations used in UML?
Answer:
UML predominantly includes static and dynamic model diagrams and each diagram has its own set of notations. In brief, the classification of these diagrams
is given as below: #
Structure Diagrams include the Class Diagram, Object Diagram, Component Diagram, Composite Structure Diagram, Package Diagram, and Deployment Diagram.

Behavior Diagrams include the Use Case Diagram (used by some methodologies during requirements gathering); Activity Diagram, and State Machine Diagram.

Interaction Diagrams, all derived from the more general Behavior Diagram, include the Sequence Diagram, Communication Diagram, Timing Diagram, and Interaction Overview Diagram.

Question 4.
What is a Use case and an Actor?
Answer:
A Use case represents a particular scenario that corresponds to the functional requirement (s) of a system to be designed and developed. An Actor is a user/external program or a system (anyone or anything), which interacts with a system. An Actor may input/receive or both (input and receive) information from the system.
In the diagram shown below, a scenario of buying a bus/train/tram ticket from a vending machine is captured through a use case diagram. Here actor is a ‘Customer’ as shown by a stickman and in ovals, all use cases have been documented.

Question 5.
How to identify an Actor?
Answer:
An Actor can be identified by finding an answer for the following points: Who is:

  • interacting
  • benefited
  • maintaining
  • supplying information
  • using information
  • removing information does the system use an external resource?

A good/refined set of actors of the system will arrive iteratively.

Question 6.
What is Generalization?
Answer:
In UML, a generalization relationship is a relationship in which one model element (the child) is based on another model element (the parent). Generalization relationships are used in class, component, deployment, and use case diagrams. Generalization corresponds to inheritance implementation amongst classes.

Question 7.
What is Association and how it maps into a Java class?
Answer:
An association specifies how objects are related to one another. To identify associations, look for verb and prepositional phrases like ‘part of, ‘next to’, ‘works for’ or ‘contained in’. While identifying implicit associations, a lot of common sense and general knowledge is required. It is very important to eliminate redundant

associations while designing a system. The most important aspects of associations are: Cardinality – a cardinality of one on a given relationship end generates a Java reference, for example, public class Customer

{
Purchase Purchase; ...
}

A cardinality of many (depicted as a number or *) generates a Java container:

public class Customer
{
List purchases; ...
}

Navigability – Forgiven an instance of an object on one side of an association you can access an instance on the other side. If an association can only be traversed in one direction then this will be indicated with arrows. If there are no arrows then the association is bi-directional.

Association end – A given class only sees the association through the attributes set on the association end. In other words that simple line actually represents two independent sets of data, one for each of the two classes involved. Besides cardinality and navigability, the most important attribute is the association end name. This name is used to generate the getter and setter methods and in persistent classes database column names.

The different types of associations can be Aggregation and Composition. I will describe them in more detail in the next blogs to come.

Question 8.
What is Aggregation and how it maps into a Java class?
Answer:
An Aggregation is an Association that denotes an “is part of the relationship. Take a ‘Car’, for example, it consists of an engine, a steering wheel, four tires, seats, gearbox, fuel tank, engine oil tank, air filters, etc. So all constituents of a car are parts of it.
If a car is destroyed/smashed, its parts can still be used separately as spares in other cars, so these parts have individual use even when their container entity is destroyed.
In a Java class, aggregation can be represented from the above example as class Car

{
List getTires( );
List getseats( ); 
List getAl1 parts( ); 
}

Question 9.
What is Composition and how it maps into a Java class?
Answer:
A Composition is a tight Association and denotes a “whole-part” relationship. So when an object is destroyed then all its constituents are also destroyed, these ‘parts’ have no meaning/sense in their lone existence from their ‘whole’.
The best example of Composition is a ‘Human body’ which is composed of two legs, two hands, two eyes, two ears, and so on. During the lifetime of a human being, all organs make sense being part of the whole, but once a human being is dead most of these parts are also dead unless some of his body parts are not medically reused.

Now come to map composition to Java world, the best example is the garbage collection feature of the language. While garbage collecting objects, the whole has the responsibility of preventing all its parts from being garbage collected by holding some references to them.

It is the responsibility of the whole to protect references to its parts not being exposed to the outside world. The only way to have a true composition in Java is to never let references to internal objects escape their parent’s scope.
An example of Inner class as shown in the following code snippet may give you an idea of how to implement Composition in Java.

public class Human
{
public Human( )
{
Brain brain = new Brain( );
}
private class Brain
{
. . . 
. . .
}
}

Question 10.
What is Dependency and how it maps into a Java class
Answer:
A Dependency relationship means when a class consumes/uses methods or variables from another class (supplier). So a change to supplier class affects the consumer class as well. Here supplier is independent of any changes being made to the consumer class. In UML class diagrams, a dependency relationship connector appears as a dashed line with an open arrow that points from the consumer class to the supplier class. A dependency relationship means an “import” statement.

Question 11.
What is the purpose of State machine diagrams?
Answer:
Objects have both attributes and behaviors. The attribute is also known as the state. When objects are incredibly complicated then to have a better understanding during different state changes one should develop one or more state machine
diagrams, tormer/y called state chart diagrams in UML I.x, describing how then- instances work.

Question 12.
What are different kinds of Structure diagrams?
Answer:
Structure Diagrams as part of UML2.1:

  • Class diagrams
  • Object diagrams
  • Composite structure diagrams
  • Component diagrams
  • Deployment diagrams
  • Package diagrams

Question 13.
What are different kinds of Interaction diagrams?
Answer:
The Interaction diagrams represent how objects interact with one another through message passing.
There are two kinds of Interaction Diagrams:

  1. Sequence Diagram
  2. Collaboration Diagram

Question 14.
What are different kinds of Behavior diagrams?
Answer:
Behavior Diagrams include:

  • Use Case Diagram (used by some methodologies during requirements gathering)
  • Activity Diagram
  • State Machine Diagram.

Wpf interview questions and answers for experienced pdf – WPF Interview Questions in .NET

Wpf interview questions and answers for experienced pdf: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on WPF

Question 1.
What is WPF?
Answer:
WPF (Windows Presentation Foundation) is a graphical subsystem for displaying user interfaces, documents, images, movies, etc., in windows applications.

Question 2.
What is the need for WPF when we had Windows forms?
Answer:

Remember: ABCDEFG

A – Anywhere execution (Windows or Web)
B – Bindings (less coding)
C – Common look and feel (resource and styles)
D – Declarative programming (XAMLor Extensible Application Markup Language) E – Expression blend animation (Animation ease)
F – Fast execution ( Hardware acceleration)
G – Graphic hardware-independent (resolution independent)

Question 3.
What is XAML in WPF and why do we need it?
Answer:
XAML is an XML file that represents your WPF Ul. The whole point of creating the Ul representation in XML was to write once and run it anywhere. So the same XAML Ul can be rendered as a windows application with WPF and the same Ul can be displayed on the browser using the WPF browser or Silverlight application.

WPF Interview Questions in .NET chapter 12 img 1

Question 4.
What is xmlns in XAML file?
Answer:
“xmlns” stands for XML namespaces. It helps us to avoid name conflicts and confusion in XML documents. For example, consider the below two XML which have table elements, one table is a HTML table and the other represents a restaurant table. Now if both these elements name conflicts and confusion.

<table>
<trxtd>Rowl</tdx/tr> 
<tr><td>Row2</td></tr>
</table>
<table>
<cloth>red</cloth>
<serve>Tea</serve>
</table>

So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the HTML table with “<h: table>” and the restaurant table element qualified with “<r: table>”.

<h: tablexmlns : h="HTTP: //www.w-3 . org/TR/html4/">
<tr><td>Rowl</td></tr>
<trxtd>Row2</tdx/tr>
</h: table>

<r: tablexmlns: h="HTTP: //www.questpond.com/restaurant/table/def"> <cloth>red</cloth>
<serve>Tea</serve>
</r: table>

Question 5.
What is the difference between xmlns and xmlns: x in WPF?
Answer:
Bothe namespaces help to define/resolved XAML Ul elements.
The first namespace is the default namespace and helps to resolve overall WPF elements.

xmlns="HTTP: //schemas, microsoft. com/winfx/2006/xaml/presentation ”

The second namespace is prefixed by “x: ” and helps to resolve XAML language definition.

xmlns: x=”HTTP: //schemas.microsoft.com/winfx/2006/xam!”

For instance for the below XAML snippet, we have two things one is the “StackPanel” and the other is “x: name”. “StackPanel” is resolved by the default namespace and the “x: name” is resolved by using “xmlns: x” namespace. ,

<StackPanelx: Name-’myStack”/>

Question 6.
Provide some instances where you have “xmlns: x” namespace in XAML?
Answer:
There are two common scenarios where we use “xmlns: x” namespace:
To define behind code for the XAML file using “x: class” attribute.

<Page
          xmlns="HTTP: //schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns: x="HTTP: //schemas.microsoft.com/winfx/2006/xaml" 
          x: Class="MyNamespace.MyCanvasCodelnline"
>

Second to provide name to an element.

<StackPanel x: Name=”myStack” />

Question 7.
When should we use “x: name” and “name”?
Answer:
There is no difference between “x: name” and “name”, “name” is shorthand of “x: name”. But in classes where you do not find “name” property (this is a rare situation), we need to use “x: name” property.

Question 8.
What are the different kinds of controls in WPF?
Answer:
WPF controls can be categorized into four categories:

• Control: This is the basic control with which you will work most of the time. For example textbox, buttons, etc. Now controls that are standalone control like buttons, text box, labels, etc., are termed as content control. Now there are other controls that can hold other controls, for instance, items controls. Itemscontroi can have multiple textbox controls, label controls, etc.

• Shape: These controls help us to create simple graphic controls like Ellipse, Line, rectangle, etc.

• Panel: These controls help to align and position the controls. For instance, the grid helps us to align in a table manner, stack panel helps for horizontal and vertical alignment.

• Content presenter: This control helps to place any XAML content inside it. Used when we want to add dynamic controls on a WPF screen.

All the above four types of WPF controls finally inherit from the framework element class of WPF as shown in Figure 12.2.

WPF Interview Questions in .NET chapter 12 img 2

Can you explain the complete WPF object hierarchy?

WPF Interview Questions in .NET chapter 12 img 3

Figure 12.3 shows the hierarchy of WPF objects as shown in Figure 12.3.

Object: As WPF is created using .NET so the first class from which WPF Ul classes inherits is the .NET object class.

Dispatcher: This class ensures that all WPF Ul objects can be accessed directly only by the thread who owns him. Other threads who do not own him have to go via the dispatcher object.

Dependency: WPF Ul elements are represented by using XAML which is XML format. At any given moment of time a WPF element is surrounded by other WPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For example, if a textbox is surrounded by a panel, it’s very much possible that the panel background color can be inherited by the textbox.

Visual: This is the class that helps WPF Ul to have their visual representation.

Ul Element: This class helps to implement features like events, input, layouting, etc.

Framework element: This class supports templating, styles, binding, resources, etc.
And finally, all WPF controls textbox, buttons, grids, and whatever you can think about from the WPF toolbox inherits from the framework element class.

Question 9.
Does that mean WPF has replaced DirectX?
Answer:
No, WPF does not replace DirectX. DirectX will still be needed to make cutting-edge games. The video performance of directX is still many times higher than WPF API (Application Programming Interface). So when it comes to game development the preference will be always DirectX and not WPF. WPF is not an optimum solution to make games, oh yes you can make a TIC-TAC-TOE game but not high-action animation games.

One point to remember WPF is a replacement for Windows form and not directX.

Question 10.
So is XAML meant only for WPF?
Answer:
No, XAML is not meant only for WPF. XAML is an XML-based language and it had various variants.

WPF XAML is used to describe WPF content, such as WPF objects, controls, and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents.

Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross¬platform browser plug-in that helps us to create rich Web content with 2-dimensional graphics, animation, and audio and video.

WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.

Question 11.
Can you explain the overall architecture of WPF?
Answer:

WPF Interview Questions in .NET chapter 12 img 4

Figure 12.4 shows the overall architecture of WPF. It has three major sections presentation core, presentation framework, and mallcore. In the same diagram, we have shown how other sections like direct and operating systems interact with the system. So let’s go section by section to understand how every section works.

User32: It decides which goes where on the screen.

DirectX: As said previously WPF uses DirectX internally. DirectX talks with drivers and renders the content.

MILcore: MIL stands for media Integration library. This section is an unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API.

Presentation core: This is a low-level API exposed by WPF providing features for 2D (two-dimensional), 3D (three-dimensional), geometry, etc.

Presentation framework: This section has high-level features like application controls, layouts. Content, etc., helps you to build up your application.

Question 12.
What is App.xaml in the WPF project?
Answer:
App.xaml is the start-up file or a bootstrapper file that triggers your first XAML page from your WPF project.

Question 14.
What are various ways of doing alignment in WPF?
Answer:
There are five ways of doing alignment in WPF as shown in Figure 12.5:
Grid: In Grid alignment we divide the screen in to static rows and columns like HTML tables and position elements in those rows and column area.

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0" Background="Red">lst column 1st row </Label>
<Label Grid.Column="l" Grid.Row="0" Background="LightGreen">2nd Column 2nd row</Label>
<Label Grid.Column="0" Grid.Row="1" Background="Red">lst column 2nd row</ Label>
<Label Grid.Column=''l" Grid.Row="l" Background= "LightGreen">2nd Column 2nd row</Label> 
</Grid>

Stack panel: Arranges control in vertical or horizontal format as shown in Figure 12.6.

<StackPanel Orientation="Vertical">
<Label Background="Red">Red </Label>
<Label Background="LightGreen">Green </Label>
<Label Background="LightBlue">Blue </Label>
<Label Background="Yellow">Yellow </Label>
</StackPanel>

WPF Interview Questions in .NET chapter 12 img 5

Wrap panel: Aligns elements in a line until the border is hit, then wraps into the next line as shown in Figure 12.7.

<WrapPanel Orientation="Horizontal">
<Label Width="125" Background="Red">Red 1</Label>
cLabel Width="100" Background="LightGreen">Green 1</Label>
<Label Width="125" Background="LightBlue">Blue 1</Label>
<Label Width="50" Background="Yellow">Yellow 1</Label>
<Label Width="150" Background="Orange">Orange 1</Label>
<LabeI Width="100" Background="Red">Red 2</Label>
<Label Width="150" Background="LightGreen">Green 2</Label>
<Label Width="75" Background="LightBlue">Blue 2</Label>
</WrapPanel>

WPF Interview Questions in .NET chapter 12 img 6

Dock Pane1:Aligns controls in five different regions: top, bottom, left, right and center as shown in Figure 12,8.

<DockPanel>
<Label DockPanel.Dock="Top" Height="100" Background="Red">Top 1</Label> 
<Label DockPanel. Dock=''Lef t" Background^"LightGreen">Lef t</Label>
<Label DockPanel.Dock="Right" Background="LightCyan">Right</Label>
<Label DockPanel.Dock="Bottom" Background="LightBlue">Bottom</Label> 
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Demo of Dock panel</TextBlock>
</DockPanel>

WPF Interview Questions in .NET chapter 12 img 7

Canvas: Positions elements absolutely use co-ordinates as shown in Figures 12,9,

<Canvas Margin="273, 130, 144, 99">
<TextBlock> Canvas position </TextBlock>
</Canvas>

Question 15.
What are resources in WPF?
Answer:
Resources are objects referred to in WPF XAML, In the C# code when we create an object, we do the following three steps as shown in Figure 12,10.

WPF Interview Questions in .NET chapter 12 img 8

using CustomerNameSpace; // import the namespace.
Customer obj = new Customer( ); // Create object of the class
Textboxl. text = obj . CustomerCode; // Bind the object with UI elements

So even in WPF XAML to define resources that are nothing but objects we need to the above 3 steps:

  • Import namespace where the class resides: To define namespace we need to use the “xmlns” attribute as shown in the below XAML code.
<Window x: Class="LearnWpfResources.MainWindow"
xmlns = "HTTP: //schemas.microsoft.com/winfx/2 006/xaml/presentation
xmlns: x="HTTP: //schemas.microsoft.com/winfx/2006/xaml"
xmlns: custns="clr-namespace: LearnWpfResources"
Title="MainWindow" Height="350" Width="525">
  • Create an object of the class: To create an object of the class in XAML we need to create a resource by using the resource tag as the below code. You can the object name is ‘ custobj “.
<Window.Resources>
<custns: Customer x: Key="custobj"/>
</Window.Resources>

The above code you can map to something like this in C#.

Customer custobj = new Customer( );
  • Bind the object with Ul objects: Once the object is created we can then bind them using bindings like one way, two way as explained in “Explain one way, two way, one time and one way to the source?” question explained above.
<TextBox Text=”{Binding CustomerCode, Mode=TwoWay, Source={StaticResource custobj}}”/>

Question 16.
Explain the difference between static and dynamic resources.
Answer:
Resources can be referred statically or dynamically. Static referred resources evaluate the resource only once and after that if the resources change those changes are not reflected in the binding. While dynamic referred resources are evaluated every time the resource is needed.

Consider the below “SolidColorBrush” resource which is set to “LightBlue” color.

<Window. Resources>
<SolidColorBrush Color="LightBlue" x: Key="buttonBackground" />
</Window.Resources>

The above resource is bound with the below two textboxes statically and dynamically, respectively.

<TextBox Background=”{DynamicResource buttonBackground}”/> 
<TextBox Background=”{StaticResource buttonBackground}”/>

Now if we modify the resource, you see the first text box changes the background and the other textbox color stays as it is.

private void Button_Click(object sender, RoutedEventArgs e)
{
     Resources["buttonBackground" ] = Brushes.Black;
}

WPF Interview Questions in .NET chapter 12 img 9

Figure 12.11 shows the output of the same.

Question 17.
When should we use static resources over dynamic resources?
Answer:
Dynamic resources reduce application performance because they are evaluated every time the resource is needed. So the best practice is to use Static resources until there is a specific reason to use dynamic resources. If you want resources to be evaluated again and again then only use dynamic resources.

Question 18.
Explain the need for binding and commands.
Answer:
WPF bindings helps to send/receive data between WPF objects while command helps to send and receive actions as shown in Figure 12.12. The object that emits data or action is termed as the source and the object who wants to receive data or action is termed as a target.

WPF Interview Questions in .NET chapter 12 img 10

Question 19.
Explain one way, two way, one time, and one way to the source.
Answer:
All the above four things define how data will flow between target and source objects when WPF binding is applied as shown in 12.13.

WPF Interview Questions in .NET chapter 12 img 11

Two ways: Data can flow from both source to target and from target to source.
One way: Data flows only from source to target.
One way to source: Data flows only from target to source.
One time: Data flows only for the first time from source to target and after that, no communication happens.
The table below shows is an easy tabular representation to memorize the same.

Bindings

Data flow

Target to Source Source to target
Two way Yes Yes
One way to source Yes No
One way No Yes
One time No For first Yes

Question 20.
Can you explain the WPF command with an example?
Answer:
When end users interact with the application they send actions like button click, right-click, Ctrl + C, Ctrl + V, etc. A command class in WPF wraps these end-user actions into a class so that they can be reused again and again.
WPF Command class idea is an implementation of a command pattern from a gang of four design patterns.
To create a command class we need to implement the “command” interface. For example below is a simple command class that increments a counter class by calling the “increment” method.

WPF Interview Questions in .NET chapter 12 img 12

public class IncrementCounter:
System.Windows.Input.ICommand
{
      private clsCounter obj;
      public IncrementCounter
      (clsCounter o)
      {
            obj = o;
      }
      public bool CanExecute
      (object parameter)
      {
           return true;
      }
      public event EventHandler
      CanExecuteChanged;
      public void Execute(object parameter)
      {
         obj.Increment( );
      }
}

The command class needs two implement methods as shown in the above code:

What to Execute (Execute) – Command class is all about wrapping actions of end-users so that we can reuse them. At the end of Figure 12.14: Binding Direction day Action invokes methods. Mean for instance a “btnmaths_click” action will invoke the “Add” method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the “increment” method of “counter” class.

When to execute (CanExecute) – The second thing we need to specify is when the command can execute, which means validations. This validation logic is specified in the “CanExecute” function. If the validation returns true then “Execute” fires or else the action has no effect. You can see the code of “CanExecute” and “Execute” in the above code snippet.

Once you have created the “Command” class you can bind this with the button using the “Command” property as shown in the below XAML code.”CounterObj” is a resource object.

<Button Command=”{Binding IncrementClick, Source={StaticResource Counterobj}}”/>

So now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we just need to bind the command object with the WPF Ul controls wherever necessary.

Question 21.
How does “UpdateSourceTrigger” affect bindings?
Answer:
“UpdateSourceTrigger” decides when the data should get updated between WPF objects that are binded. In other words should data get updated in lost focus event, in data change event, etc

There are four modes by which “UpdateSourceTrigger” can be defined:

  • Default: If it is a text property then data is updated during lost focus and for normal properties data updates in property change event.
  • PropertyChanged: In this setting, data is updated as soon as the value is changed.
  • LostFocus: In this setting, data is updated as soon as the lost focus event occurs.
  • Explicit: In this setting, the data is updated manually. In other words, to update data between two WPF objects, you need to call the below code.
BindingExpression binding =txt1.GetBindingExpression(TextBox. TextProperty); binding. UpdateSource( );

To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in the bindings properties as shown in Figure 12.15.

WPF Interview Questions in .NET chapter 12 img 13

Question 22.
Explain the need for the “INotifyPropertyChanged” interface.
Answer:
When we bind two WPF objects the target data is updated depending on the “UpdateSourceTrigger” events. Please refer to the previous question for “UpdateSourceTrigger” basics.

The “UpdateSourceTrigger” has events like lost focus, property change, etc. In other words, when lost focus or property change event happens on the target it makes a PULL to the source to get the latest data as shown in Figure 12.16.

WPF Interview Questions in .NET chapter 12 img 14

So it’s very much possible that the WPF source data has changed and because the WPF target “UpdateSourceTrigger” event did not fire it did not make a pull and the data of the source is not in sync with the target as shown in Figure 12.17. This is where the “INotifyPropertyChanged” interface comes to use.

WPF Interview Questions in .NET chapter 12 img 15

Below is a simple “clsCounter” class that has a “Counter” property and this property is incremented by the “Increment” method.

Now if we bind WPF label or textbox to the “Counter” property and call the “increment” method the new “Counter” value will not be propagated to the target. Because invoking a method does not trigger any “UpdateSourceTrigger” event.

So after calling the “increment” method the “Counter” value of the source and the target is out of synch.
To create a push event from the source you need to first implement the “iNotifyPropertyChanged” interface as shown in Figure 12.18. Now when someone calls the “increment” method you can raise an event saying that the “Counter” property has changed by calling the “PropertyChanged” function as shown in the below code.

In simple words, the source sends a notification to the target WPF object that data has changed in the source and if should refresh itself with the fresh data.

PropertyChanged(this, new PropertyChangedEventArgs(“Counter”));

Below is full “clsCounter” class code with “INotifyPropertyChanged” implemented.

public class clsCounter: INotifyPropertyChanged
{
     private int _Counter=0;
     public int Counter
     {
          get { return _Counter; }
     }
     public void Increment( )
     { 
         _Counter++;
         PropertyChanged(this, new PropertyChangedEventArgs("Counter"));
     }
public event PropertyChangedEventHandler PropertyChanged;
}

Question 23.
How are WPF observable collections different from simple .NET collections?
Answer:
Simple .NET collections do not notify the Ul automatically when elements are added or removed from them. So when we update simple .NET collection’s we need to send refresh events back to the WPF Ul for rebinding the collection.

“ObservableCollection” is a specialized collection that updates the Ul automatically and immediately when new elements are added and removed from the collection.

“ObservableCollection” implement’s “iNotifyCollectionChanged” interface. This interface exposes the “CollectionChanged” event which gets raised when elements are added or removed to the collection.

Below is a simple code which creates the “ObservableCollection” collection which is binded with a list.

ObservableCollection<Person> person = new ObservableCollection<Person>( ); 
IstNames.ltemsSource = person;

Question 24.
What are value converters in WPF?
Answer:
Binding is one of the big features in WPF which helps us to facilitate data flow between WPF Ul and Object (See Figure 12.18). But when data flows from source to Ul or vice-versa using these bindings we need to convert data from one format to another format. For instance, let’s say we have a “Person” object with a married string property.

WPF Interview Questions in .NET chapter 12 img 16

Let’s assume that this “Married” property is binded with a check box. So if the text is “Married” it should return true so that the option check box look’s checked. If the text is “UnMarried” it should return false so that the option check box looks unchecked.

In simple words, we need to do data transformation. This is possible by using “Value Converters”. In order to implement value converters we need to inherit from the “value converter” interface and implement two methods “Convert” and “ConvertBack”.

public class MaritalConverter: IValueConverter
{
        public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
        {
             string married = (string)value;
             if (married == "Married")
        {
             return true;
        }
        else
        {
            return false;
        }
}
public object ConvertBack(object value. Type targetType, object
parameter, System.Globalization.Culturelnfo culture)
{
        bool married = (bool)value;
         if (married)
        {
            return "Married";
        }
        else
        {
            return "UnMarried" ;
        }
    }
}

You can see in the “Convert” function we have written logic to transform “Married” to true and from “UnMarried” to false. In the “ConvertBack” function we have implemented the reverse logic.

Question 25.
Explain multi-binding and multivalue converters in WPF?
Answer:
“MultiBinding” helps you bind multiple sources to a target while multi-converters act like bridge – if the source and targets have different data formats or need some conversion as shown in Figure 12.19.

WPF Interview Questions in .NET chapter 12 img 17

For example, let’s say you have two textboxes that have “FirstName” and “LastName”. You want ~ that as soon as users type on .these two text boxes, the other text box should get updated with ‘ “FirstName LastName” as shown in Figure 12.20. s

Also vice-versa if we type in the third text box “FirstName LastName” it should display “FirstName” … and “LastName’ in the other two textboxes, respectively.

So the first thing is to create a multivalue converter class that will join “FirstName” and “LastName” into source and split “FirstName LastName” back to the target. For the same we need to implement “multivalue converter” and implement “Convert” and “ConvertBack” methods.

“Convert” helps to do the conversion from “Target” to “Source” and “ConvertBack” helps to ^ convert from “Source” to “Target”.

public class NameMultiConverter: IMultiValueConverter
{
public object Convert(object[ ] values. Type targetType, object
parameter, System.Globalization.Culturelnfo^ culture)
{
        // Conversion logic from Target to Source
}
}
public object[ ] ConvertBack(object value, Type[] targetTypes, object
parameter, System.Globalization.Culturelnfo culture)
{
       // Conversion logic from Source to Target.
}
}

Below is the “Convert” ( Target to Source) implementation where we get the “textbox” value in a array and we have concatenated the array values and returned the same in a single string. This single string will be displayed in the third textbox.

public object Convert(object[] values. Type targetType, object
parameter, System.Globalization.Culturelnfo culture)
{
      string x = " ";
      foreach (object y in values)
     {
            x = x + " " + y.ToString( );
     }
     return x;
}

“ConvertBack” helps to implement conversion logic from “Source” to “Target”. So when someone types “Shiv Koirala” in the third text box we would like to split “Shiv” in one string and “Koirala” in another string.

So you can see in the below code we have used the “Split” function to create a string array. So the first array index (array[0]) will go to the first textbox and the second array index (array[1]) will go to the second text box.

public object[ ] ConvertBack(object value, Type[ ] target types, object
parameter, System.Globalization.Culturelnfo culture)
{
      string str = (string)value;
      string[] val = str.Split(' ');
      return val;
}

Now once we are done with the converter next thing is to apply multi-binding. Below is the XAML code where we have the three text boxes ” txtFirstName”, ” txtLastName ” and “txtFirstAndLast”.

You can see how the “txtFirstAndLast” textbox “Text” is binded using multibinding element which binds to “txtFirstName” and “txtLastName” textbox . So now if you make changes to multiple target the single source gets updated and if you update the source multiple target gets updates.

<TextBox x: Name="txtFirstName" HorizontalAlignment="Left" Height="26"
Margin="42, 67, 0, 0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="152"/>
<TextBox x: Name="txtLastName" HorizontalAlignment="Lef t" Height="26"
Margin="41, 135, 0, 0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="153”/>
<TextBox x: Name="txtFirstAndLast"- Height="28" HorizontalAlignment="Left" Margin="239, 103, 0, 0" 
Name="label1" VerticalAlignment="Top" Width="117"> <TextBox.Text>
<MultiBinding Converter=”{StaticResource NameMultiConverter}">
<Binding ElementName="txtFirstName" Path="Text" />
<Binding ElementName="txtLastName" Path="Text" />
</MultiBinding>
</TextBox.Text>
</TextBox>

Question 26.
Explain WPF relative binding/relative resource.
Answer:
When we define bindings we need at least two elements target and source. But many times rather than defining binding between two elements we would like to define binding with reference to the current element, i.e., relatively.

For instance, let’s say we have a WPF border and we would like the height and width of the border to be same. So for this scenario, the target and source are the same, the WPF border itself. So we can define the binding using “RelativeSource” as shown in the below code. You can see it uses the “Self” binding mode to bind the element to itself.

<Border BorderBrush="Black" BorderThickness = "l11 Height="139"
Width="{Binding Height, RelativeSource={RelativeSource Self}}"/>
What are the different ways of binding using relative sources?

There are four ways of binding relatively in WPF:

  • Self
  • Ancestor
  • Previous data
  • Templated parent

Question 27.
Can you explain self relative source binding in WPF?
Answer:
This relative binding helps to bind one property of an element to the other property of the same element. For example, in the below XAML the border width is binded to a height of the same border element.

<Border BorderBrush-’Black” BorderThickness=”1" Height=”139"
Width=”{Binding Height, RelativeSource={RelativeSource Self}}”/>

Question 28.
Explain Ancestor relative source binding in WPF.
Answer:
This relative binding helps to bind properties to the parent element properties. For example, in the below XAML code we have a textbox that has two borders as a parent. One border is having dark green and the other border is having dark red color as the border color.

WPF Interview Questions in .NET chapter 12 img 18

The dark green color border is the parent element followed by dark red and the textbox the child element at the end of the hierarchy.

<Border BorderBrush="DarkGreen"> 
<Border BorderBrush="DarkRed"> 
<TextBox />
</Border>
</Border>

Below is how the WPF application looks like when it runs.

Now we want the background color of the text box to be binded to one of the parent border colors. To achieve the same we can use ancestor relative binding.
Table below shows some important properties in Ancestor type binding we need to know before we writing the binding code.

Tablw

So the relative binding code with ancestor level 1, i.e., red looks as shown below. In case you are confused with any of the properties please refer to the previous table for more information.

<TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel = l, 
AncestorType={x: Type Border}}}"/>

So now the complete XAML with parent border element looks as shown in the below code.

WPF Interview Questions in .NET chapter 12 img 19

<Border BorderBrush="DarkGreen"><! —
Level 2 ->
<Border BorderBrush="DarkRed" >< i —
Level 1 ->
<TextBox Background^' {Binding BorderBrush,
RelativeSource={RelativeSource FindAncestor, AncestorLevel=l,
AncestorType=(x: Type Border}}}"/>
</Border>
</Border>

Now if you run the above XAML code the textbox is binded with the background color of the first border. If you change the ancestor level to 2 textbox background color will change to green.

WPF Interview Questions in .NET chapter 12 img 20

Question 29.
Explain the difference between the visual and logical trees in WPF.
Answer:
WPF Ul is represented in XAML which is an XML format. In XML elements are arranged in a hierarchal fashion. For example, if you look at the below XAML (it has been downsized for simplicity) we have a Window element, the window element has a Grid control and the grid control has a button inside it.

<Window>
             <Grid>
                      <Button..>
            </Grid>
</Window>

So if you visualize the above XAML logically you can think that the button control is a child element of the Grid and the grid is the child element of the Window. This relationship between the elements which looks logical looking at the XAML is termed as “Logical Tree” as shown in Figure 12.24.

WPF Interview Questions in .NET chapter 12 img 21

But now to display this Logical tree on to your screen you need lot of visual elements. Like border, text etc. So when you add these visual elements to the logical tree that complete structure is termed as “Visual Tree”.

Putting in simple words there is only tree in WPF but depending on how you view it these two trees are the outcome. If you use the WPF visualizer the above XAML tree looks something as shown in the below Figure 12.25 which is actually a complete visual tree.

WPF Interview Questions in .NET chapter 12 img 22

In simple words whatever you see in your XAML is a logical tree and to make it display it uses the visual tree. Figure 12.26 shows the logical and visual tree of the above XAML. Logical tree is without the shades and with shades is the visual tree.

Question 30.
Why do we need to have this perspective of visual and logical tree in WPF?
Answer:
Visual tree and Logical tree are important when you work with WPF routed events.

Question 31.
Explain routed events in WPF.
Answer:
Routed events are those events that travel up or down the visual tree hierarchy. WPF events can be classified into three types:

WPF Interview Questions in .NET chapter 12 img 23

Direct events: In this case event is raised at the source and handled at the source itself like “Mous enter” events.
Bubbling events: They travel up the visual tree hierarchy. For example, “MouseDown” is a bubbling event.
Tunneling events: These events travel down the visual tree hierarchy. “PreviewKeyDown” is a tunneling event.

Question 31.
Explain WPF styles.
Answer:
Let’s say you have WPF Ul which has a lot of buttons and you want to set the background to “Aqua” color (See Figure 12.28).

So the quick way of doing this is to set the background of all the buttons to “Aqua” color as shown in the below XAML code. But now let’s say some days down the line customer wants to change the background color to “Red”. So you need to modify the background property for all buttons.

WPF Interview Questions in .NET chapter 12 img 24

<Button Backgrounds"Aqua"/>
<Button Background="Aqua"/>
<Button Background="Aqua"/>

Won’t it be great if we can define the background color as a style from some commonplace and when we want to change the background color we just change from that central commonplace That’s what WPF style helps us to achieve
WPF style helps to define look and feel (color, fonts, alignments, etc.) from a central location so that we can have ease of maintenance.
To define a style we need to use the “Style” tag of XAML. It needs three things at least:

  • X: Key: Name of Key of the style.
  • TargetType: WPF Ul object on which you want to apply the style. For example, in the below code we are applying this style on the button.
  • Setter: This element defines the property for which the value has to be set. For example, in our case, we are setting the “Background” color property to “Aqua”.
<Style x: Key="myStyle" TargetType="Button">
           <Setter Property="Background" Value="Aqua" />
</Style>

Once the style is defined we can attach the style resource to the style property of the button element as shown in the below code.

<Button Style="{StaticResource myStyle}"/> 
<Button Style="{StaticResource myStyle}"/> 
<Button Style="{StaticResource myStyle}"/>

Question 32.
What are style triggers?
Answer:
Many times we would want a style property to execute under certain conditions. Trigger’s help you to define conditions under which the style values will be set.

For example, we want to create a dynamic style where we focus on the button it should change to red color or else should be set to Aqua color as shown in Figure 12.29.

WPF Interview Questions in .NET chapter 12 img 25

To achieve the same we can use style trigger as shown in the below XAML code.

<Style x: Key="myStyle" TargetType="Button">
           <Style.Triggers>
                     <Trigger Property="IsFocused" 
                      Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
             </Style.Triggers>
             <Setter Property="Background" 
             Value="Aqua" />
</Style>

Question 33.
Explain the Multitrigger concept in WPF.
Answer:
Many times we want style triggers to be executed when multiple conditions are true. For example, let’s say we have a button we want the button background to be set to “RED” when there is focus on the button and when somebody moves the mouse on the button.

WPF Interview Questions in .NET chapter 12 img 26

In other situations, the background color should be set to “Aqua”.

So to achieve such multiple AND conditions we can use the “MultiTrigger” XAML element as shown in the below XAML code. Multiple AND conditions need to be defined in the “MultiTrigger .Conditions” tag and the property which needs to be modified in the “MultiTrigger. Setters” tag.

<Style x: Key="myStyle" TargetType="Button"> 
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="True" />
<Condition Property="IsMouseOver" Value="True" />
</MultiTrigger.Conditions>
<MultiTrigger.Setters>
<Setter Property="Background" Value="Red" />
</MultiTrigger.Setters>
</MultiTrigger>
</Style.Triggers>
<Setter Property="Background" Value="Aqua" /> 
</Style>

Question 34.
What is the difference between control templates and data templates?
Answer:

WPF Interview Questions in .NET chapter 12 img 27

Control templates change the structure of a WPF element while data templates change the way data is displayed but maintain the structure of the WPF element.
A visual example of a control template where a rectangle-shaped button changes into an ellipse shape.
For that, we need to create a style using the “<ControlTemplate>” element. In this “<ControlTemplate>” WPF element we can define the structure which we want to apply to the element. Below is the XAML code for the same.

<Style TargetType="Button">
<!—Override all default style —>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Ellipse Fill=" (TemplateBinding Background-} "/>
cContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/ >
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Later this style can be applied to the button using the style property as shown the below code.

<Button Style="{StaticResource mystyle}"/>

Data templates have no effect on the structure but they affect data. For example, Figure 12.32 shows the is list box on which data templates have been applied. You can see the structure of the list box does not change but the number of fields and the way they are placed is changed.

WPF Interview Questions in .NET chapter 12 img 28

To use data templates we need to use ‘ item template” tag and within the “item template” tag we can define how we want the data to be structured.

<ListBox Margin="26, 27, 165, 51" x: Name= "lstb">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions> 
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition> 
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text = " {Binding Name}" FontSize="12" Height="18"/>
<TextBlock Grid.Column="l" Text="{Binding City}" FontSize="12" Height = "18"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Question 35.
What is MWM?
Answer:
MVVM (Model-View-View Model) is an architecture pattern where we divide the project into three logical layers and every layer has its own responsibility (See Figure 12.33).

WPF Interview Questions in .NET chapter 12 img 29

Below are the three logical layers with an explanation of what they do:

• View: This layer handles the responsibility of taking inputs from the end-user, positioning of controls, look and feel, design, visuals, colors, etc.

• Model: This layer represents your middle layer objects like a customer, supplier, etc. It handles business logic and interaction with the data access layer.

• View Model: View model as it says View plus Model represents your user interface. You can also visualize this class as the behind code. This class is the bridge between model and view. It handles connection logic, data transformation logic, and action mapping between model and view. For example, it will have the following types of logic as shown below.

  • Replicating and propagating data between views and models. When someone enters data into Ul or the model gets updated this layer will ensure that the propagation of data happens between these entities.
  • Handling data transformation from view to model and vice-versa. For example, you have a model which has gender property with data as “M” for males and “F” for females. But on the View or Ul, you would like to display as a check box with true and false. This transformation logic is written in the view model class.
  • View model also maps Ul’s actions to methods. For example, you have “btn_Add” click event and when anyone clicks on this button you would like to invoke
    “Customer. Add ( )” method from the customer class. This connection code is again a part of the view model.

Question 36.
What are the benefits of MWM?
Answer:
Below are the benefits of the MWM pattern as shown in Figure 12.34:

Separation of concern: As the project is divided into layers, every layer handles its own responsibility. This leads to better maintenance because when we change one layer the other layer does not get affected.

Increased Ul Reusability: The whole point of MWM is to remove behind, code, i.e., XAML.CS code. The problem with behind code is that it is tied up with Ul technology, for example, ASPX.CS code is tied up with the ASP page class, XAML.CS file is tied with WPF Ul technology and so on. So we cannotuseASPX.CS behind code with WPF XAML UI.

By moving the behind code to the view model class we can now use this with any Ul technology.

WPF Interview Questions in .NET chapter 12 img 30

Automated Ul Unit testing: View model class represents your Ul. The properties of the class represent Ul textboxes, combo boxes and the methods of the class represent action. Now as the Ul is represented by the view model class, we can do automated Ul testing using unit testing by creating the objects of view model class and doing the necessary assets.

Question 37.
What is the importance of command and bindings in the MWM pattern?
Answer:
MWM is the most used architecture because of the command and bindings facility provided by WPF) (See Figure 12.35). WPF MWM is incomplete without command and bindings.

WPF Interview Questions in .NET chapter 12 img 31

Command and bindings help you to connect view (WPF Ul) with view model class without writing a lot of behind code. Binding connects the Ul input elements (textbox, combo box, etc.) with the view model class properties, and the Ul actions like button click, right-click are connected to the methods of the class by commands.

Note: Please refer to previous questions to understand commands and bindings.

Question 38.
What is the difference between MWM and 3-layer architecture?
Answer:
MVVM has an extra layer as compared to 3 layer architecture. In 3 layer architecture, we have Ul (view), business logic (model), and Data Access Layer (DAL) as shown in Figure 12.36. In MWM we have an extra layer in between view and model, i.e., the view model class. 3 layer architecture complements MVVM architecture.

WPF Interview Questions in .NET chapter 12 img 32

Question 39.
Explain delegate command.
Answer:
First, let us answer in short: “Delegate command makes an MVVM command class independent of the view mode!’. Now let’s understand the long way.
In MVVM architecture view talks with the view model and the view model talks with the model. When actions are sent from the view they are sent to WPF commands for handling the events as shown in Figure 12.37. WPF commands invoked methods of view model internally.
In other words, the command needs a reference of the view model class.

WPF Interview Questions in .NET chapter 12 img 33

If you see a typical WPF MVVM command it looks as shown below. You can see the “CustomerViewModel” class referenced inside the ‘btnCommand” class. If you think with your eyes closed this reference of the “CustomerViewModel” class inside the command is a problem. This will lead to tight coupling between command classes and the view model.
If you visualize the command it is nothing but clicks, double click, left mouse click, drag and drop, etc. It is an ACTION created by the user. Now wouldn’t be great if we can just attach this command with any view model. So like click event gets connected with ” Cus tomervi ewMode 1″ or “SupplierViewMode1”.
This is achieved by using the delegate command.

public class btnCommand: ICommand
{
Private CustomerViewModel Viewobj = new CustomerViewModel();
public btnCommand(CustomerViewModel obj)
{
Viewobj = obj;
}
public bool CanExecute(object parameter) // When he should execute
{
return Viewobj.IsValid( );
}
public void Execute(object parameter) // What to execute
{
ViewObj.Add();
}
}

To decouple the view model class from command we can use delegates, i.e., “Action” and “Func”.lf you see the command class we need only two things “WhattoExecute” and “WhentoExecute”. So how about passing these methods as generic delegates. You can see the constructor of “btnCommand” takes two delegates one what to execute and one when to execute.

You can see in the below code the “btnCommand” class has no reference of the view model class but has references to delegates which are just abstract pointers to functions/methods. So this command class can now be attached with any view model class. This approach is termed as “Delegate command”.

public class btnCommand: ICommand // Step 1: Create command
{
      private Action WhattoExecute;
      private Func<bool> WhentoExecute;
      public btnCommand(Action What, Func<bool> When)
      {
             WhattoExecute = What;
             WhentoExecute = When;
     }
     public bool CanExecute(object parameter) // When he should execute
     {
            return WhentoExecute( );
     } 
     public void Execute(object parameter) // What to execute
     {
           WhattoExecute( );
     }
}

Question 40.
What is PRISM?
Answer:
PRISM (Personal Record Information System Methodology) is a framework to develop a composite applications in WPF and Silverlight as shown in Figure 12.38. Composite applications are built using composition. In other words rather than building applications from scratch, we take prebuilt components, assemble them together and create the application.

WPF Interview Questions in .NET chapter 12 img 34

Take the example of simple WPF Ul (See Figure 12.39). You can see it has lots of sections. Now rather than building the whole Ul as one big unit, we can develop all these sections as an independent unit. Later by using PRISM we can compose WPF Ul by taking all these independent units (See Figure 12.39).

Question 41.
What are the benefits of PRISM?
Answer:
Modular development: As we are developing components as independent units we can assign these units to different developers and do modular parallel development. With parallel development projects will be delivered faster.

High reusability: As the components are developed in individual units we can plug them using PRISM and create composed Ul in an easy way.

Question 42.
How are individual units combined into a single unit?
Answer:
PRISM uses dependency injection for the same, please see the design pattern section to read about Dl (Dependency Injection). We can do Dl in two ways by using unity application block or MEF (Managed Extensibility Framework).

Question 43.
Does PRISM do MWM?
Answer:
The prime focus of PRISM (Personal Record Information System Methodology) is modular development and not MWM. But it does have ready-made classes like delegate command which can help us reduce MWM code. But please note the main goal of PRISM was not MWM.

Question 44.
Is PRISM a part of WPF?
Answer:
No, PRISM an acronym for (Personal Record information System Methodology) is a separate installation.

Question 45.
What is expression blend?
Answer:
Expression blend is a designing tool for WPF and Silverlight applications.

Question 46.
What is Silverlight?
Answer:
Silverlight is 16. Windows Presentation Framework (Vista Series) is a Web browser plug-in by which we can enable animations, graphics, and audio/video. You can compare Silverlight with Flash. We can view animations with Flash and it’s installed as a plug-in in the browser.

Question 47.
Can Silverlight run on platforms other than a window?
Answer:
Yes, animations made in Silverlight can run on platforms other than window. In whatever platform you want to be run you just need the Silverlight plug-in.

Question 48.
Come on, even WPF runs under the browser why Silverlight?
Answer:
Yes, there is something called a WPF browser application that can run WPF in the browser. For the WPF browser application, you need the .NET framework to be installed in the client location while for Silverlight you need only the plug-in. So in other words WPF browser applications are OS (Operating System) dependent while Silverlight is not. Silverlight plug-in can run in other OS other than windows while we all know .NET framework only runs in windows.

 

Question 49.
What is the relationship between Silverlight, WPF, and XAML?
Answer:
As explained previously XAML is an XML file that defines the Ul elements. This XML file can be read by WPF framework or Silverlight framework for rendering. Microsoft first developed WPF and they used XAML files to describe the Ul elements to the WPF framework. Microsoft then extended WPF and made WPF/e (Windows Presentation Foundation/Everywhere) which helped to render the Ul in the browser. WPF/e was the code name for Silverlight. Later Microsoft launched Silverlight officially.

So the XAML just defines the XML structure to represent the Ul elements. Both the frameworks, i.e., WPF and Silverlight then read the Ul elements and renders the Ul elements in the respective platform as shown in Figure 12.40.

WPF Interview Questions in .NET chap

Question 50.
What is the XAP file in Silverlight?
Answer:
XAP (Cross-Platform Audio Creation Tool Audio Projects) file is a compressed file that downloads all the necessary DLLs (Dynamic Link Library), code at the browser client so that the Silverlight application can run inside the browser.

Question 51.
Can you explain Silverlight architecture?
Answer:
Before we talk about Silverlight architecture let’s discuss what is Silverlight is really made of technically. Silverlight has borrowed a lot of things from existing Microsoft technologies. We can think of Silverlight plug-in as a combination of some technologies from the core .NET framework, vector animations, media, and JavaScript as shown in Figure 12.41.

So we can visualize the Silverlight architecture as a combination of some functionalities from the core .NET framework, Ajax, and some functionalities like animation, media, etc., provided by the core Silverlight framework.

WPF Interview Questions in .NET chapter 12 img 36

We can think of Silverlight architecture as a combination of four important blocks:

• Some .NET framework components: Silverlight uses some components from the .NET framework. One of the main components is WPF. Many of the Ul components (check box, buttons, text boxes, etc.), XAML parsing, etc., are taken from the core WPF system. It also has taken components like WCF to simplify data access, it also has CLR (Common Language Runtime) for memory management, safety checking, and garbage collection. The base class libraries of NET are used for string manipulations, algorithms, expressions, collections, and globalization.

• Presentation core: The core presentation framework has functionalities to display vector 2d animations, images, media, DRM (Digital Rights Management), and handle inputs like mouse and keyboard.

• Other technologies: Silverlight interacts with other technologies like Ajax and JavaScript. So it also borrows some functionalities from their technologies.

• Hosting: Silverlight animations finally run under the browser environment. So it has a hosting functionality that helps to host the application the browser, expose a DOM (Document Object Model) by which JavaScript can manipulate the Silverlight components and it also has an installer functionality which helps to install Silverlight application and plug-in in the browser environment.
One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. The XAML is a component that is a part of the .NET framework and the rendering part is done by the presentation core (See Figure 12.42).

WPF Interview Questions in .NET chapter 12 img 37

The application is a typical HTML that runs under the browser. There are markups that instantiate the Silverlight plug-in. Now when the user interacts with the Silverlight application it sends an event to the JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript or .NET can make calls to the Silverlight run-time and achieve the necessary functionalities (See Figure 12.43). XAML will be read and parsed by the Silverlight runtime and then rendered accordingly to the browser.

WPF Interview Questions in .NET chapter 12 img 38

Question 51.
What are the various basic steps to make a simple Silverlight application?
Answer:
This sample we are making using VS 2008 Web express edition and .NET 3.5. It’s a six-step procedure to run our first Silverlight application. So let’s go through it step by step.

Step1: The first thing we need to do is install Siiveriight SDK (Software Development Kit) from HTTP: //www. microsoft.com/downloads/details.aspx7fami I vid = FB7900DB-4380-4B0F-BB95- 0BAEC714EE17&displavlanq=en

Step 2: Once you install the Silverlight SDK you should be able to use the Silverlight template. So when you go to create a new project you will see a ‘Siiveriight application’ template.

Step 3: Once you click ok you will see a dialog box as shown below with three options.

Add an ASP.NET Web project to the solution to host Silverlight: This option is the default option, and it will create a new Web application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application then this is the option to go.

Automatically generate Test Page To Host Siiveriight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application then this option is worth looking at.

Link This Siiveriight Control Into An Existing Website: If you have an existing Silverlight application then this option helps to link the Silverlight application with the existing Web application project. You will not see this option enabled for new projects, you need to have an existing Web application.

For this example, we have selected the first option. Once you click ok you should see the full IDE (Integrated Development Environment) environment for Silverlight

So let’s run through some basic points regarding the IDE view what we see. You will see there are two projects one is your Web application and the other is the Silverlight application. In the Silverlight application, we have two XAML files one is App.XAML and the other is Page.XAML.

App.XAML has global-level information.

Step 4: Now for simplicity’s sake, we just use the TextBlock tag to display a text. You can see as we type on the Page.XAML is displayed in the viewer.

Step 5: Now we need to consume the Silverlight application on an ASPX page. So in the HTML / ASPX page, we need to first refer to the Siiveriight namespace using the ‘Register’ attribute.

<%@Register Assembly=”System. Web. Siiveriight” Namespace-’System.Web.Ul.SilverlightControls” TagPrefix=’’asp” %>

We also need to refer the script manager from the Silverlight namespace. The script manager control is the functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.

<asp: ScriptManager ID=”ScriptManager1" runat-”server”></asp: ScriptManager>

Finally, we need to refer to the Silverlight application. You can see that in the source we have referred to the XAP file. XAP file is nothing but a compiled Silverlight application that is compressed and ZIP. It basically has all the files that are needed for the application in a compressed format. If you rename the file to ZIP extension you can open the same using WINZIP.

<asp: Siiveriight ID="Xainll" runat=" server" Source="~/ClientBin/ MyFirstSilverLightApplication.xap" 
MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

So your final ASPX / HTML code consuming the Silverlight application looks something as shown below.

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight"
Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "HTTP: //
www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd">
<html xmlns="HTTP: //www.w3.org/1999/xhtml" style="height: 100%;">
<head runat="server">
<title>MyFirstSilverLightApplication</title>
</head>
<body style="height: 100%,-margin: 0;">
<form id="forml" runat="server" style="height: 100%; ">
<asp: ScriptManager lD="ScriptManagerl" runat="server"x/asp: ScriptManager> <div style="height: 100%;">
<asp: Silverlight ID="Xamll" runat=”server" Source="~/ClientBin/MyFirstSilverLightApplication.xap"
MinimumVersion="2,0.31005.0" Width="100%" Height="100%" />
</div>
</form>
</body>
</html>

Step 6: So finally set the Web application as start-up and also set this page as start-up and run it. You should be pleased to see your first Silverlight application running as shown in Figure 12.44.

WPF Interview Questions in .NET chapter 12 img 39

Question 52.
What are the different kinds of bindings in Silverlight?
Answer:
There is three kinds of bindings one-way, two-way, and one time-binding.

  • One-way binding: data flows from object to Ul and not vice-versa.
  • Two-way bindings: data flows from object to Ul and also vice-versa.
  • In one time binding data flows from the object to the Ul only once. There is no tracking mechanism to update data on either side. One-time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.

In order to specify bindings, we need to use the binding path attribute on the Ul elements as shown in the below code snippet.

<TextBox x: Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" 
VerticalAlignment="Center"
HorizontalAlignment="Center"></TextBox>

Question 53.
How does Silverlight connect with databases?
Answer:
If you remember the Silverlight architecture, it does not contain ADO.NET. In order to make insert, update, and deletes via Silverlight, we need to call WCF services, and WCF services in turn will do insert updates and deletes on SQL Server.

Question 54.
What are the two important points we noted when we call WCF service from Silverlight?
Answer:

  • We can only WCF services asynchronously from Silverlight.
  • We need to create a cross-domain and client access policy XML (extensible Markup Language) file where the WCF service is hosted.

Question 55.
What are the different ways of doing alignment in Silverlight and WPF?
Answer:
There are three ways provided by Silverlight for layout management Canvas, Grid, and Stack panel.

WPF Interview Questions in .NET chapter 12 img 40

Canvas is the simplest methodology for layout management. It supports absolute positioning using ‘X’- and ‘Y’-coordinates. ‘Canvas. Left’ helps to specify the X-coordinate while ‘Canvas. Top’ helps to provide the ‘Y’-coordinates.

Below is a simple code snippet which shows how Rectangle objects are positioned using ‘ Canvas ‘ on coordinates (50, 150).

<Canvas x: Name="MyCanvas">
<Rectangle Fill = "Blue" Widt.h="100" 
          Height="100"
         Canvas.Left="50"
         Canvas.Top="150"/>
</Canvas>

Grid layout helps you position your controls using rows and columns as shown in Figure 12.45. It’s very similar to table defined in HTML.
As the name so the behavior. Stack allows you to arrange your Ul elements vertically or horizontally.

WPF Interview Questions in .NET chapter 12 img 41

Question 56.
What is expression blend?
Answer:
Expression blend is a graphic design tool that can design the look-and-feel using expression blend and give the XAML file to the developers who can write the behind code for the same.

Question 57.
How can we do multi-threading in WPF / Silverlight?
Answer:
In order to implement proper multi-threading, we need to use the dispatcher object.

Question 58.
Can’t we just use threads, why do we need the dispatcher object?
Answer:
In WPF / Silverlight objects have thread affinity. In other words, the objects can be modified only by the thread that has created the object. Now when any WPF/Silverlight applications run they run on the main thread as shown in Figure 12.47. So that main thread only has the permission to modify the same.

WPF Interview Questions in .NET chapter 12 img 42

Question 59.
But what if try to modify it?
Answer:
If other threads who have not created the Ul object try to modify the same it will throw an exception “invalid cross-thread access”.
For example in the below code we have a simple function called as “Set value”, this function modifies a textbox. This function is called directly by creating a “Thread” object in a button click event.

private void buttonl_Click(object sender, RoutedEventArgs e)
{
       Thread obj = new Thread(new ThreadStart(SetValue));
       obj.Start( );
}
public void Setvalue( )
{
        for (int i = 0; i < 10; i++)
        {
              textBoxl.Text = "test";
        }
}

Now the Ul object “textbox1” is not created by thread “obj”. It’s created by the main thread which runs the WPF/Silverlight Ul. So when you run the application you should get an exception as shown in the below “invalid cross-thread access” as shown in Figure 12.48.

WPF Interview Questions in .NET chapter 12 img 43

Question 60.
So how do we make the code working?
Answer:
To make threading working in WPF and Silverlight we need to use the “Dispatcher” object. So rather than making calls directly to the Ul object, we need to route the calls via dispatcher object. The dispatcher object then prioritizes and executes the calls on the thread’s behalf to the Ul control (See Figure 12.49).

WPF Interview Questions in .NET chapter 12 img 44

So to make the above code working we need to call the code from within the dispatcher object. We need to pass a delegate to the “Begininvoke” function (which is done by using a lambda expression ” ()=>”) of the “Dispatcher” object.

public void SetValue( )
{
       for (int i = 0; i < 10; i++)
       {
           this.Dispatcher.Beginlnvoke(( ) => {textBoxl.Text = "Test";});
       }
}

Question 61.
What is a background worker thread?
Answer:
Background worker is a simple thread that runs in the background and helps us execute processes in the background. In order to use background worker class we need to provide two things:

  • The first thing we need to provide is the heavy processing method that we want to invoke in a multi-threading fashion. For instance, the below method “_bWorker_DoWork” has a heavy processing logic. This method is provided to the “DoWork” property of the “BackGroundWorker” class.
readonly BackgroundWorker _bWorker = new BackgroundWorker( );
_bWorker.DoWork += new DoWorkEventHandler(_bWorker_DoWork);
void _bWorker_DoWork(object sender, DoWorkEventArgs e)
{
    //Heavy processing logic
}
  • The second thing is you need to invoke the method ” RunWorkerAsync” so that the “_bWorker_DoWork” method will be executed in the background.
_bWorker.RunWorkerAsync( );

Question 62.
Question 6: What is the difference between a background worker and a dispatcher?
Answer:
Dispatcher only queues and executes the multi-threaded request. The dispatcher does not create threads. While background worker actually spawns and executes methods in a multi-threaded manner.

 

 

 

 

 

 

Collection framework interview question – Collection Framework Interview Questions in Java

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

Collection Framework Interview Questions in Java

Question 1.
What are Collection related features in Java 8?
Answer:
Java 8 has brought major changes in the Collection API. Some of the [ changes are:

  • Java Stream API for collection classes for supporting sequential as well as parallel processing
  • The iterable interface is extended with forEach( 0 default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because its argument Consumer is a functional interface.
  • MiscellaneousCollectionAPIimprovementssuchasforEachRemaining(Consumer action) method inlterator interface, Map replaceAll( ), compute( ), merge( ) methods.

Question 2.
what is Java Collections Framework? List out some benefits of the Collections framework?
Answer:
Collections are used in every programming language and the initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework 1 that groups all the collections interfaces, implementations, and algorithms.

Java Collections have come a long way with the usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in the java concurrent package. Some of the benefits of the collections framework are;

  • Reduced development effort by using core collection classes rather than implementing our own collection classes.
  • Code quality is enhanced with the use of well-tested collections framework classes.
  • Reduced effort for code maintenance by using collection classes shipped with JDK.
  • Reusability and Interoperability

Question 3.
What is the benefit of Generics in Collections Framework?
Answer:
Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add an element of another type it throws a compile-time error.

This avoids ClassCastException at Runtime because you will get the error at compilation. Also, Generics make code clean since we don’t need to use casting and instance of operator. I would highly recommend going through Java Generic Tutorial to understand generics in a better way.

Question 4.
What are the basic interfaces of the Java Collections Framework?
Answer:
The collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface. Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards. The list is an ordered collection and can contain duplicate elements.

You can access any element from its index. The list is more like an array with dynamic length. A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap, and Listlterator.

Question 5.
Why Collection doesn’t extend Cloneable and Serializable interfaces?
Answer:
The collection interface specifies a group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t. A lot of the Collection implementations have a public clone method. However, it doesn’t really make sense to include it in all implementations of Collection. This is because the Collection is an abstract representation.

Question 6.
What matters is the implementation.
Answer:
The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.

So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.

Question 7.
Why Map interface doesn’t extend the Collection interface?
Answer:
Although Map interfaces and their implementations are part of the Collections Framework, Map is not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa. If Map extends the Collection interface, then where are the elements? The map contains key-value pairs and it provides methods to retrieve a list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

Question 8.
What is an Iterator?
Answer:
Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using the iterator( ) method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

Question 9.
How do you traverse through a collection using its Iterator?
Answer:
To use an iterator to traverse through the contents of a collection, follow these steps:

  • Obtain an iterator to the start of the collection by calling the collections iterator( ) method.
  • Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  • Within the loop, obtain each element by calling next( ).

Question 10.
How do you remove elements during Iteration?
Answer:
Iterator also has a method remove( ) when remove is called, the current element in the iteration is deleted.

Question 11.
What is the difference between the Enumeration and Iterator interface?
Answer:
Enumeration is twice as fast as Iterator and uses very little memory. Enumeration is very basic and fits basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make its functionality clear.

Question 12.
Why there is no method like Iterator. add( ) to add elements to the collection?
Answer:
The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that Listlterator does provide an add operation, as it does guarantee the order of the iteration.

Question 13.
Why Iterator doesn’t have a method to get the next element directly without moving the cursor?
Answer:
It can be implemented on top of the current Iterator interface but since its use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

Question 14. What is different between Iterator and Listlterator?
Answer:

  • We can use Iterator to traverse Set and List collections whereas Listlterator can be used with Lists only.
  • Iterator can traverse in forwarding direction only whereas Listlterator can be used to traverse in both directions.
  • Listlterator inherits from the Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.

Question 15.
What are different ways to iterate over a list?
Answer:
We can iterate over a list in two different ways – using iterator and using for-each loop.

List&lt;String&gt; strList = new ArrayList&lt;&gt;( );
//using for-each loop
for(String obj : strList){
System.out.println(obj);
}
//using iterator
lterator&lt;String&gt; it = strList.iterator( );
while (it. hasNext ( )) {
     String obj = it.next( );
     System.out.println(obj);
}

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException

Question 16.
What do you understand by iterator fail-fast property?
Answer:
Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throwsConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the . concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

Question 17.
What is difference between fail-fast and fail-safe?
Answer:
Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java, util.concurrent are fail-safe.
Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.

Question 18.
How to avoid ConcurrentModificationException while iterating a collection?
Answer:
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of Array List.

Question 19.
Why there are no concrete implementations of Iterator interface?
Answer:
Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.

Question 20.
What is UnsupportedOperationException?
Answer:
UnsupportedOperationException is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework java.util.Collections.UnmodifiableCollectionthrows this exception for all add and remove operations.

Question 21.
How HashMap works in Java?
Answer:
HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode( ) and equals( ) method input and get methods. When we call the put method by passing key-value pair, HashMap uses Key hashCode( ) with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entries, it uses the equals( ) method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and stores this key-value Entry.

When we call get method by passing Key, again it uses the hashCode( ) to find the index in the array and then use the equals( 0 methods to find the correct Entry and return it’s value. Below image will explain these details clearly.

Collection Framework Interview Questions in Java chapter 13 img 1

The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 32 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.

Question 22.
What is the importance of hashCode( ) and equals( ) methods?
Answer:
HashMap uses the Key object hashCode( ) and equals( ) method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce the same hashCode( ) and equals( ) output and in that case, rather than storing it at different location, HashMap will consider the same and overwrite them.

Similarly all the collection classes that doesn’t store duplicate data use hashCode( ) and equals( ) to find duplicates, so it’s very important to implement them correctly. The implementation of equals( ) and hashCode( ) should follow these rules.

Collection values( ): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator, remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

  • If ol.equals(o2), then ol.hashCode( ) == o2.hashCode0should always be true.
  • If ol.hashCode( ) = = o2.hashCode is true, it doesn’t mean that ol.equals(o2) will be true.

Question 23.
Can we use any class as Map key?
Answer:
We can use any class as Map Key, however following points should be considered before using them.

  • If the class overrides equals( ) method, it should also override hashCode( ) method.
  • The class should follow the rules associated with equals( ) and hashCode( ) for all instances. Please refer earlier question for these rules.
  • If a class field is not used in equals( ), you should not use it in the hashCode( ) method.
  • The best practice for user defined key class is to make it immutable, so that hashCode( ) value can be cached for fast performance. Also immutable classes make sure that hashCode( ) and equals( ) will not change in future that will solve any issue with mutability.

For example, let’s say I have a class MyKey that I am using for HashMap key.

//MyKey name argument passed is used for equals( ) and hashCode( ) 
MyKey key = new MyKey(“Pankaj”); //assume hashcode=1234 
myHashMap.putfkey, “value”);
// Below code will change the key hashCode( ) and equals( )
// but it’s location is not changed.
key.setName(“Amit”); //assume new hashcode=7890
//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null. 
myHashMap.getCnew MyKey(“Pankaj”));
  • This is the reason why String and Integer are mostly used as HashMap keys.

Question 24.
What are different Collection views provided by Map interface?
Answer:
Map interface provides three collection views:
• Set keySet( ): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

• Collection values( ): Returns a collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator. remove, collection. remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

• Set<Map.Entry<K, V» entrySet( ): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator. remove, Set. remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Question 25.
What is the Dictionary class?
Answer:
The Dictionary class is an abstract class. The class maps keys to values. The classes such as HashTable are the subclasses of the abstract class Dictionary. The key and values are objects. The key and value are non-null objects.

Question 26.
What is the ResourceBundle class?
Answer:
A ResourceBundle is a group of related subclasses which are sharing the same base name. For example, ButtonLabel is the base name. All the characters following the base name indicates the following elements respectively.

Question 27.
What is the Vector class?
Answer:
The Vector class implements an incremental array of objects.
The vector components can be accessed using an integer index.
The size of a Vector increases or decreases as needed to accommodate the items.

Question 28.
What is the SimpleTimeZone class?
Answer:
SimpleTimeZone is a concrete subclass of TimeZone class. The TimeZone class represents a time zone that is to be used with Gregorian calendar.

Question 29.
What is Locale?
Answer:
A Locale object represents a specific geographical, political, dr cultural region.

Question 30.
How will you load a specific locale?
Answer:
By ResourceBundle.getBundle(?) method.

Question 31.
What is the difference between Comparable and Comparator?
Answer:

NO Comparable Comparator
1 Comparable provides only one sort of sequence. The comparator provides multiple sorts of sequences.
2 It provides one method named compareTo( ) It provides one method named compare( )
3 It is found in java.lang package. It is found in java. util package.
4 If we implement a Comparable interface, the actual class is modified. The actual class is not modified.

Question 32.
What is the advantage of Properties file?
Answer:
If you change the value in properties file, you don’t need to recompile the java class. So, it makes the application easy to manage.

Question 33.
What does the hashCode( ) method?
Answer: The hashCode( ) method returns a hash code value (an integer number). The hashCode( ) method returns the same integer number if two keys (by calling equals( ) method) are the same. But, it is possible that two hash code numbers can have different or same keys.

Question 34.
Why do we override the equals( ) method?
Answer:
The equals( ) method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals( ) method.

Question 35.
How to synchronize List, Set and Map elements?
Answer:
Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List 1)§
public static Set synchronizedSet(Set s)0
public static SortedSet synchronizedSortedSet(SortedSet s){ }
public static Map synchronizedMap(Map m){ }
public static SortedMap synchronizedSortedMap(SortedMap m){ }

Question 36.
What is the advantage of generic collection?
Answer:
If we use generic class, we don’t need typecasting. It is typesafe and checked at compile time.

Question 37.
What is hash-collision in Hashtable and how it is handled in Java?
Answer:
Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

Question 38.
What is the Dictionary class?
Answer:
The Dictionary class provides the capability to store key-value pairs.

Question 39.
What is the default size of the load factor in the hashing-based collection?
Answer:
The default size of the load factor is 0.75. The default capacity is computed as the initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Question 40.
Which package is used for pattern matching with regular expressions?
Answer:
java.util.regex package is used for this purpose.

Question 41.
java.util.regex consists of which classes?
Answer:
java.util.regex consists of three classes: Pattern class, Matcher class and PatternSyntaxException class.

Question 42.
What is the use of the ‘SimpleDateFormat’ and how can you use it to display the current system date in ‘yyyy/MM/DD HH:mm:ss’ format?
Answer:
SimpleDateFormat is one such concrete class which is widely used by Java developers for parsing and formatting of dates. This is also used to convert Dates to String and vice-versa.

Literally every Enterprise level Java Application invariably uses the SimpleDateFormat for handling user dates. We of course aren’t expecting Java interviewees to be absolutely spectacular with the syntaxes. But a basic know-how of this class is mandatory.

public class CurrentsystemDate {
public static void main(string[ ] args) {
     SimpleDateFormat sysForm = new SimpleDateFormat(“yyyy/MM/DD HH:mm:ss”);
     Date curdate= new Date( );
     System.out.println(sysForm.format(curdate));
}
}

Question 43.
What is difference between ArrayList and vector?
Answer:
1) Synchronization: ArrayList is not thread-safe whereas Vector is thread- safe. In Vector class each method like addO, get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth: Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Question 44.
How can Arraylist be synchronized without using Vector?
Answer:
Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection. synchronizedCollection(Collection c)

Question 45.
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeelD of Employee class. What are the steps?
Answer:

  1. Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeelD
  2. Now call Collections. sort( ) method and pass list as an argument.

Now consider that Employee class is a jar file.

  1. Since the Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object objl) method.
  2. Call Collections. sort( ) on the list and pass comparator as an argument.

Question 46.
What is difference between HashMap and HashTable?
Answer:
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
Fail-safe – if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterators own remove method, the iterator will throw a ConcurrentModificationException?
3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Question 47.
What are the classes implementing List interface?
Answer:
There are three classes that implement List interface:

1) ArrayList: It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It, also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: The LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Question 48.
Which all classes implement Set interface?
Answer:
A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements el and e2 such that el.equals(e2), and at most one null element. HashSet, SortedSet and TreeSet are the commonly used class which implements Set interface.

SortedSet – It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.

TreeSet – It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.

HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Question 49.
What is difference between List and a Set?
Answer:

  1. The list can contain duplicate values but Set doesn’t allow it. The set allows only to unique elements.
  2. The list allows retrieval of data to be in the same order in the way it is inserted but Set doesn’t ensures the sequence in which data can be retrieved. (Except HashSet)

Question 50.
What is the difference between Arrays and ArrayList?
Answer:
Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :

  • int [ ] intArray= new int[6];
  • intArray[7] // will give ArraysOutOfBoundException.
  • Also, the size of the array cannot be incremented or decremented. But with ArrayList the size is variable.

Once the array is created elements cannot be added or deleted from it. But with ArrayList, the elements can be added and deleted at runtime.

List list = new ArrayList( ); 
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
•       ArrayList is one dimensional but array can be multidimensional.
        int[ ][ ][ ] intArray= new int[3][2][1]; // 3 dimensional array

• To create an array the size should be known or initialized to some value. If not initialized carefully there could be memory wastage. But ArrayList is all about dynamic creation and there is no wastage of memory.

Question 51.
When to use ArrayList or LinkedList?
Answer:
Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using “get” is fast, but for LinkedList, it’s slow. It’s slow because there’s no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you’re doing random access on the list, and a LinkedList works better if you’re doing a lot of editing in the middle of the list.

Question 52.
Consider a scenario. If an ArrayList has to be iterating to read data only, what are the possible ways, and which is the fastest?
Answer:
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using the iterator. Because the value stored in ArrayList is indexed access. So while accessing the value is accessed directly as per the index.

Question 53.
Now another question with respect to the above question is if accessing through iterator is slow then why do we need it and when to use it.
Answer:
For loop does not allow the updating in the array (add or remove operation) inside the loop whereas Iterator does. Also, an Iterator can be used where there is no clue what type of collections will be used because all collections have an iterator.

Question 54.
Which design pattern Iterator follows?
Answer:
It follows the Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway it’s easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about the underlying implementation.

Example of Iteration design pattern – Enumeration The class java. util. Enumeration is an example of the Iterator pattern. It represents an abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Question 55.
Is it better to have a HashMap with a large number of records or n number of small hashMaps?
Answer:
It depends on the different scenarios one is working on:

  1. If the objects in the hashMap are the same then there is no point in having a different hashmap as they traverse time in a hashmap is invariant to the size of the Map.
  2. If the objects are of different types like one of Person class, other of Animal class, etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Question 56.
Why is it preferred to declare: List<String> list = new ArrayList<String> 0> instead of ArrayList<String> = new ArrayList<String>0;
Answer:
It is preferred because:

  1. If later on, the code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes a list. E.g. void showDetails(List list); When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector, LinkedList making the function more flexible.

Question 57.
What is the difference between iterator access and index access?
Answer:
Index-based access allows access of the element directly on the basis of the index. The cursor of the data structure can directly go to the ‘n’ location and get the element. It does not traverse through n-1 elements.
In Iterator-based access, the cursor has to traverse through each element to get the desired element. So to reach the ‘n’th element it needs to traverse through n-1 elements.
Insertion, updation, or deletion will be faster for iterator-based access if the operations are performed on elements present in between the data structure.
Insertion,updating, or deletion will be faster for index-based access if the operations are performed on elements present at the last of the data structure.
Traversal or search in index-based data structure is faster.
ArrayList is index access and LinkedList is iterator access.

Question 58.
How to sort the list in reverse order?
Answer:
To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverse order( ). Then, pass the reverse Comparator to the sort( ) method.
List list = new ArrayList( );
Comparator comp = Collections.reverseOrder( );
Collections.sort(list, comp)

Question 59.
Can a null element add to a Treeset or HashSet?
Answer:
A null element can be added only if the set contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException. HashSet is based on hashMap and can contain the null elements.

Question 60.
How to sort the list of strings – case insensitive?
Answer:
Using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Question 61.
How to Make a List (ArrayList, Vector, LinkedList) read-only?
Answer:
A list implementation can be made read-only using Collections. unmodifiable list(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Question 62.
What is ConcurrentHashMap?
Answer:
A ConcurrentHashMap is the thread-safe implementation of the Map interface. In this class put and remove methods are synchronized but not the get method. This class is different from Hashtable in terms of locking; it means that hashtable use object-level lock but this class uses bucket-level lock thus having better performance.

Question 63.
Which is faster to iterate LinkedHashSet or LinkedList?
Answer:
LinkedList.

Question 64.
Which data structure HashSet implements
Answer:
HashSet implements hashmap internally to store the data. The data passed to HashSet is stored as a key in a hashmap with null as a value.

Question 65.
Arrange in the order of speed – HashMap, HashTable, Collections. synchronized map, concurrent hashmap
Answer:
HashMap is fastest, ConcurrentHashMap, Collections.synchronizedMap, HashTable.

Question 66.
What is an identity hash map?
Answer:
The IdentityHashMap uses == for equality checking instead of equals( ). This can be used for both performance reasons if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Question 67.
What is WeakHashMap?
Answer:
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

Question 68.
Why Collection interface does not extend the Cloneable and Serializable interface?
Answer:
There is no need to do it because, extending an interface simply means that you are creating a subtype of the interface, in other words, a more specialized behavior and Collection interface are not expected to do what is Cloneable and Serializable interfaces do.
Another reason is that not everybody will have a reason to have a Cloneable collection because if it has very large data, then every unnecessary clone operation will consume a big memory. Beginners might use it without knowing the consequences. Another reason is that Cloneable and Serializable are very specialized behavior and so should be implemented only when required. For example, many concrete classes in collection implement these interfaces. So if you want this feature. Use these collection classes otherwise use their alternative classes.

Question 69.
Why insertion and deletion in ArrayList are slow compared to LinkedList?
Answer:
• ArrayList internally uses an array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of the old array is copied to the new array.

• During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node and updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked Mst is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

Question 70.
Difference between String, StringBuffer, and StringBuilder?
Answer:

String StringBuffer StringBuilder
The string is an immutable class StringBuffer is a mutable class StringBuilder is a mutable class
The new object is created every time when modified No new object is created, modification is done in the existing one No new object is created, modification is done in the existing one
Syntax – String sl-’hello”; Syntax –

StringBuffer sf=new StringBuffer(“hello”);

Syntax –

StringBuilder sb=new StringBuilder(“hello”);

StringBuffer methods are synchronized. StringBuilder methods are non-synchronized and added in jdk 5.
Use String if you require immutability use StringBuffer in java if you need mutable + thread- safety use StringBuilder in Java if you require mutable + without thread-safety..

Question71.
How will you sort a collection of String in case-sensitive order?
Answer:
Use Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Example –

public class stringsortExample{
public static void main(string[ ] args){
           List list = new ArrayList( );
           list.add(“shalabh”);
           list.add(“amit”);
           list.add("Lalit”);
           display(list);
           Col1ections.sort (list);
           display(lsit);
           Col1ections.sort(list, String.CASE_INSENSITIVE_ORDER);
           display(list);
     }
     Public static void display(List list)
     {
for (string str : list){
                      System.out.print(str + “ “);
           }
     }
}

Question 72.
What is the difference between poll( ) and remove( ) method of Queue interface?
Answer:
Though both poll( ) and remove( ) method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty 0 then a call to remove 0 methods will throw Exception, while a call to poll( ) method returns null. By the way, exactly which element is removed from the queue depends upon the queue’s ordering policy and varies between different implementations, for example, PriorityQueuekeepslowestelementasperComparatoror Comparable ahead position.

Question 73.
How do you remove an entry from a Collection? and subsequently what is the difference between the remove( ) method of Collection and remove( ) method of Iterator, which one you will use while removing elements during iteration?
Answer:
Collection interface defines remove(Object obj) method to remove objects from Collection. List interface adds another method remove(int index), which is used to remove objects at a specific index. You can use any of these methods to remove an entry from Collection, while not iterating. Things change when you iterate. Suppose you are traversing a List and removing only certain elements based on logic, then you need to use Iterator’s remove( ) method. This method removes the current element from Iterator’s perspective. If you use Collection’s or List’s remove( ) method during iteration then your code will throw Concurrent ModificationException. That’s why it’s advised to use the Iterator remove( ) method to remove objects from Collection.

Question 74.
What is the difference between Synchronized Collection and Concurrent Collection?
Answer:
Java 5 has added several new Concurrent Collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, etc, which has made Interview questions on Java Collection even trickier. Java Also provided a way to get Synchronized copies of the collection e.g. ArrayList, HashMap by using Collections. synchronizedMapO Utility function.One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.

Question 75.
What do you need to do to use a custom object as a key in Collection classes like Map or Set?
Answer:
If you are using any custom object in Map as a key, you need to override the equals( ) and hashcode( ) method and make sure they follow their contract. On the other hand, if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals( ) method is consistent with the compareTo( ) method, otherwise, that collection will not follow their contacts e.g. Set may allow duplicates.

Question 76,
What is NavigableMap in Java? What is the benefit of Map?
Answer:
NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowqrKey( ) to get keys which is less than the specified key, floor key( ) to return keys that are less than or equal to the specified key, ceilingKey( ) to get keys that is greater than or equal to specified key and, higher key( ) to return keys which are greater specified key from a Map.

It also provides similar methods to get entries e.g. lower entry( ), floor entry( ), ceiling entry( ), and higher entry( )- Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an existing Map like trail map, heatmap, and subMap. heatmap ( ) method returns a NavigableMap whose keys are less than specified, tailMapO returns a NavigableMap whose keys are greater than the specified, and subMap( ) gives a NavigableMap between a range, specified by toKey to fromKey.

Question 77.
Which one you will prefer between Array and ArrayList for Storing objects and why?
Answer:
Though ArrayList is also backed up by array, it offers some usability advantage over array in Java. The array is a fixed-length data structure, once created you cannot change its length. On the other hand, ArrayList is dynamic, it automatically allocates a new array and copies the content of the old array, when it resizes. Another reason for using ArrayList over Array is the support of Generics. Array doesn’t support Generics, and if you store an Integer object on a String array, you will only going to know | about it at runtime, when it throws ArrayStoreException. On the other hand, if you use ArrayList, the compiler and IDE will catch that error on the spot. So if you know the size in advance and you don’t need re-sizing then use an array, otherwise use ArrayList.

Question 78.
Can we replace Hashtable with ConcurrentHashMap?
Answer:
Yes, we can replace Hashtable with ConcurrentHashMap and that’s what is suggested in the Java documentation of ConcurrentHashMap. but you need to be careful with code that relies on the locking behavior of Hashtable. Since Hashtable locks whole, Map instead of a portion of Map, compound operations like if(Hashtable. get(key) = null) put(key, value) works in Hashtable but not in ConcurrentHashMap. Instead of .this use putlfAbsent( ) method of ConcurrentHashMap

Question 79.
What is CopyOnWriteArrayList, how it is different than ArrayList and Vector?
Answer:
CopyOnWriteArrayList is a new List implementation introduced in Java 1.5 which provides better concurrent access than Synchronized List. Better concurrency is achieved by Copying ArrayList over each write and replace with original instead
of locking. Also CopyOnWriteArrayList doesn’t throw any ConcurrentModification Exception. It’s different than ArrayList because it’s thread-safe and ArrayList is not thread-safe and it’s different than Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.

Question 80.
Why Listlterator has added ( ) method but Iterator doesn’t or Why add() method is declared in Listlterator and not on Iterator.
Answer:
Listlterator has added the ( ) method because of its ability to traverse or iterate in both directions of the collection, it maintains two pointers in terms of previous and next call and is in a position to add a new element without affecting the current iteration.

Question 81.
When does ConcurrentModificationException occur on iteration?
Answer:
When you remove an object using Collection’s or List’s remove method e.g. remove(Object element) or remove(int index), instead of Iterator’s removed) method than ConcurrentModificationException occurs. As per Iterator’s contract, if it detects any structural change in Collection e.g. adding or removing of element, once Iterator begins, it can throw ConcurrentModificationException.

Question 82.
Difference between Set, List, and Map Collection classes?
Answer:
java.util.Set, java.util.List and java. util. Map defines three of the most popular data structure support in Java. Set provides a uniqueness guarantee i.e.g you cannot store duplicate elements on it, but it’s not ordered. On the other hand, List is an ordered Collection and also allows duplicates. The map is based on hashing and stores keys and values in an Object called entry. It provides 0(1) performance to get the object if you know keys if there is no collision.

A popular implementation of Set is HashSet, of List are ArrayList and LinkedList, and of Map are HashMap, Hashtable, and ConcurrentHashMap. Another key difference between Set, List, and Map is that Map doesn’t implement a Collection interface, while the other two do. For a more detailed answer, see Set vs List vs Map in Java.

Question 83.
What is BlockingQueue, how it is different than other collection classes?
Answer:
BlockingQueue is a Queue implementation available in java. util.concurrent package. It’s one of the concurrent Collection classes added on Java 1.5, main difference between BlockingQueue and other collection classes is that apart from storage, it also provides flow control. It can be used in inter-thread communication and also provides built-in thread safety by using a happens-before guarantee. You can use BlockingQueue to solve the Producer-Consumer problem, which is what is needed in most concurrent applications.