Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Object: It is a basic unit of OPP and represents the real life entities.

A typical program creates many


objects, which as you know, interact by invoking methods. An object consists of State, Behavior,
Identity
OOPS:
Abstraction: It is for hiding unwanted data and giving only relevant data. It mainly focus on the
object “what it does” instead of “how it works”. Ex: Outer look of phone
Abstraction means putting all the variables and methods in a class which are necessary.
Encapsulation: It binds the data members and functions into single unit to prevent data from
outsiders. It means hiding internal details or mechanics of how an object does something.
Public class laptop
{ private string brand, model;
public string Brand
{ Get { return brand;}
Set { brand = value;}
}
public string Model
{ Get { return brand;}
Set { brand = value;}
}

Public void laptopdetails()


{ Console.Writeline(“Brand:” +brand+ “Model:” +model); }
Public void laptopkeyboard()
{ Console.Writeline(“type using keyboard”); }
Public void Motherboardinfo()
{ Console.Writeline(“Motherboard Info”); }
}
//To implement abstraction i.e. Encapsulation code
Class Program
{ public static void main(String args[])
{ Laptop l=new Laptop();
l.Brand=”Dell”; l.Model=”Inspilon 14B”;
l.laptopdetails();
Console.Writeline(“Press enter key”);
Console.Readline();
}
}
Polymorphism: It is the concept which allows us to redefine the way something works, by either
changing how it is done or by changing the parts used to get it done. This can be done in two ways.
Overloading: Creating more than one method or function that has same name but different
parameters in the same class. It is also called Early binding or compile time polymorphism or static
binding. We can achieve method overloading by changing the number of parameters used or by using
different types of parameters or by changing the order of parameters.
Ex: Class Calculate
{ public int Add(int a, int b)
{ int sum=a+b ; return sum;}
Public double Add(int a, int b, int c)
{ double sum=a+b+c; return sum;}
Public static void main(String args[])
{ Calculate cal= new Calculate();
Int sum1=cal.Add(1,2);
Int sum2=cal.Add(1,2,3);
Console.Writeline(“sum1” +”sum2”);
}
}
Overriding: Having two methods with same name and same parameters, one method in base class
and other method in derived class. It is also called late binding or runtime polymorphism or dynamic
polymorphism. We can override a method in base class by creating similar function in derived class.
This can be achieved by using inheritance and using virtual and override. It is possible only in derived
class.
Ex: public class Baseclass
{ public virtual void Myfucntion()
{ Console.Writeline(“Base class”); }
}
Public class Derivedclass : Base class
{ public override void Myfunction()
{ Console.Writeline(“Derived class”); }
}
Class Program
{ public static void main(String args[])
{ Baseclass base= new Baseclass(); base.Myfunction();
Baseclass derived= new Derivedclass(); derived.Myfunction();
}
}
Inheritance: It is the class that allows to inherit the features of another class. We use inheritance for
method overriding and for code reusability (so runtime polymorphism is achieved).
Types: Single inheritance, Multi level inheritance, Multiple inheritance (not supported but achieved
by using interface) , Hierarchical inheritance (tree structure), Hybrid inheritance (it is comination of
hierarchical and multiple)
Public class Employee
{ public float salary=40000;}
Public class Programmer:Employee
{ public float bonus=10000; }
Class Program
{ public static void main(String args[])
{ Programmer p1=new Programmer();
p1.Salary();
p1.bonus();
Console.Writeline(“Salary” +p1.salary+”Bonus”+p1.bonus);
}
}
Interface: It can have methods, properties, events. It contains only declaration of members. Interface
specify what a class must do and not how. It used to provide total abstraction. All methods declare in
interface must be implemented in the class. Interface can’t have private members. By default all the
members of interface are public and abstract.
Interface Vehicle()
{ void speedup(int a); void changegear(int a); }
Class Bicycle: Vehicle
{ int speed, gear;
Public void changegear(int newgear)
{ gear=newgear; }
Public void speedup(int increment)
{ speed=speed+increment; }
Public void printstates()
{ Console.Writeline(“Speed”+speed+”Gear”+gear); }
}
Class Bike: Vehicle
{ int speed, gear;
Public void changegear(int newgear)
{ gear=newgear; }
Public void speedup(int increment)
{ speed=speed+increment; }
Public void printstates()
{ Console.Writeline(“Speed”+speed+”Gear”+gear); }
}
Class Program
{ public static void main(String args[])
{ Bicycle bicycle=new Bicycle();
bicycle.changegear(2); bicycle.speedup(3); Console.Writeline(“Bicycle present state”);
bicycle.Printstates();
Bike bike=new Bike();
bike.changegear(2); bike.speedup(3); Console.Writeline(“Bike present state”);
bike.Printstates();
}
}
Abstract class: We use abstract class at the time of inheritance. We should use override keyword
before the method which is declared as abstract in child class. It can have abstract and non- abstract
methods. Abstract class is used to inherit in child class.
Public class A
{ public abstract void function(); }
Public class B:A
{ public override void function()
{ Console.Writeline(“Class B”); }
}
Public class C:A
{ public override void function()
{ Console.Writeline(“Class C”); }
}
Public class Program
{public static void main(String args[])
{ A a=new B(); a.function(); //instantiate class B
A c=new C(); c.function();
}
}
Managed code: Managed code is the code which is managed by the CLR(Common Language
Runtime) in .NET Framework. source code is complied into IL or MSIL.
Unmanaged code: It is the code which is directly executed by the operating system. Source code is
complied to native language.
Ref and out differences: Both ref and out are treated differently at run time and they are treated the
same at compile time. By default parameters are passed to a method by value.
'ref' is used to state that the parameter passed may be modified by the method.
'in' is used to state that the parameter passed cannot be modified by the method.
'out' is used to state that the parameter passed must be modified by the method.
Ref provides a reference to the source value and changes made in the method will be made by the
source object. Arguments passed as ref must be initialized before they are passed.
Out also cause the argument to be passed as reference. Changes made to the parameters are also
changed in the source. Arguments passed out do not have to be initialized first. The called method
must assign a value prior to the method return.
Delegate: A delegate is an object which refers to a method or you can say it is a reference
type variable that can hold a reference to the methods. 
Syntax: [modifier] delegate [return type] [delegate_name] ([parameter_list]);
Association : Represents relation b/w objects. 1-many; many-1 ; many-many. Can be both
unidirectional & bi directional.
Aggregation : Entity reference. To achieve Association. 1 object has other as a part of its state.
Represents weak relationship between objects. Has-a relationship – to reuse objects.
Composition :To achieve Association. 1 object has other as a part of its state. Represents strong
relationship between containing object and dependent object. Containing object cannot live without
dependent object. Has no independent existence.
Constructors : Block of code similar to methods. Called when an instance of class is created. When
calling memory is allocated. Every time an object is called using new() at least 1 constructor is called.
There is always a default constructor. Same as class name. no explicit return type. Cannot be abstract,
static, final & synchronised.
Types of constructors :
Default Constructor : No parameters. If a program has no constructor then compiler creates a
default one on its own. Provides default values to objects like 0, null depending on the data-type.
Parameterized Constructor : Has parameters. Provides different values/ same to distinct objects.
Constructor Overloading : Having more constructors with the same name and diff parameters which
r used to perform several tasks. Differentiated by compiler depending on the no of parameters.
Difference between Constructor and method :

Constructor Method
To initialise the state of an object. To expose behaviour of a object.
No return type. Return type must

Called implicitly. Called explicitly.

Compiler provides default constructor. No default.


Name must be same as class name. Need not be same as class name.

Static Variable, keyword, Method explanation.

Static keyword Static variable Static method


Mainly used for To refer to the common property of all Belongs to class rather than the
memory management. objects. object of a class.

Can be variable, Gets memory allocated only once at the Can be invoked without the
method, blocks, nested time of class loading. need for creating an instance of
class a class.
Memory efficient. Can access static data member
an can change value of it.

Static Keyword Static variable Static method


Java static property is shared to all This and super keyowrds
objects. should not be used.

Cannot use non-static data


member or call non-static
member directly.

Difference between Virtual and abstract functions:

Virtual function Abstract function


Virtual Method can reside in abstract and non- Abstract Method resides in abstract class and it
abstract class. has no body.
It is not necessary to override virtual method in Abstract Method must be overridden in non-
derived but it can be. abstract child class.
Virtual methods must have the method An abstract method should contain only method
body/implementation along with the definition. definition, should not Contain the method
body/implementation.
If an abstract method is defined in a class, then
the class should declare as an abstract class.

Difference between abstract and interface:

Abstract class Interface


It contains both declaration and definition part. It contains only a declaration part.
It can contain different types of access modifiers It only contains public access modifier because
like public, private, protected etc. everything in the interface is public.
It contain constructor and static members It won’t contain constructor and static members
The performance of an abstract class is fast. The performance of interface is slow because it
requires time to search actual method in the
corresponding class.
Can have final, non-final, static, non-static Only static and final variables.
variables.
It can be fully, partially or not implemented. It should be fully implemented.

Difference between new and override keyword:

New Override
when base class has not declared method as used with virtual/abstract/override type of
virtual/abstract/override. method in base class
New hides the method of base class Override extend the method of base class with
new definition.

Difference between string, string buffer and string builder

String String buffer String builder


Storage String pool Heap heap
Modifiable No (immutable) Yes (mutable) Yes (mutable)
Thread safe Yes Yes No
Synchronized Yes Yes No
Performance Fast Slow Fast
Program:
public class Test 
{
    public static void main(String[] args)
    {
        String str1 = new String("Hello");           
        StringBuffer sbr = new StringBuffer(“Hello”);
StringBuilder sbl = new StringBuilder(“Hello”);
str1.concat(“Hi”);         
        sbr.append("Hi");
sbl.append("Hi");
        Console.Writeline(str); // output will be hello
Console.Writeline(sbr); // output will be hello hi
Console.Writeline(sbl); // output will be hello hi
In order to get hello hi for str you need to store into new object.
String newstr= str.concat(“Hi”);
    }
}
Difference between final, finally and finalize:
Final Finally Finalise
Used to apply restrictions on Is used to place important To perform clean up
class, method, variable. code. processing just before object is
garbage collected.
Final variable value can’t be It will be executed whether This is a method.
changed. exception is handled or not.
Final class can’t be inherited This is a block

Final method can’t be overridden

This is a keyword
Access modifiers:

PUBLI PROTECTED PRIVATE

C PROTECTED INTERNAL INTERNAL PRIVATE PROTECTED

Entire program Yes No No No No No

Containing class Yes Yes Yes Yes Yes Yes

Current assembly Yes No Yes Yes No No

Derived types Yes Yes No Yes No No

Derived types within

current assembly Yes Yes No Yes No Yes

Non- Access Modifiers : Static, final, abstract, synchronised, native, volatile, transient etc
Static: Used for creating class methods and variables. Variables will exist independently of any instances of
classes created. Only 1 copy exists. Also known as class variables. Local variables can’t be static.

Final : for finalizing the implementations of class, methods, variables. Variables can be initialized
only once. A ref variable declared final can never be reassigned to refer to diff object. State and data
of the object can be changed but not the reference. Final methods cannot be overridden. Content of the
method should never be changed by outsider.
Abstract: to create abstract class and methods. Abstract class can never be instantiated. Abstract class
can only be extended. Cannot be both abstract and final. If a class has abstract methods then class
should be abstract if not compile time error. Abstract methods are declared without any
implementations. Abstract methods can never be strict or final
Synchronized : Indicates that a method can be accessed by only 1 thread at a time. Can be applied
with any four of the access modifiers.
Transient :To indicate the JVM to skip particular variable when serialising the object containing it.
Volatile: used for threads.
Difference between constant, read only and static read only:

Constant Readonly Static Readonly


A const field can only be A readonly field can be A static readonly type
initialized at the declaration of initialized either at the variable’s value can be
the field declaration or in an instance assigned at runtime or assigned
constructor. at compile time and changed at
runtime.

A const field is a compile time A readonly field can be used as A static readonly field can be
constant a run-time constant used as a runtime constant
Once a value is assigned to a We can change the readonly Static readonly values can only
constant, it can’t be initialized variable values any number of be changed inside static
again it will throw error. time provided that we are contructors only. It can be
Left hand side of an changing it inside the instance changed only once at runtime.
assignment must be a variable, constructors
property or indexer.
It can be accessed using It can be accessed using It can be accessed using
classname.constname interfaces classname.constname
Difference between var and dynamic keyword

Var Dynamic
The variables are declared using var keyword The variables are declared using dynamic
are statically typed. keyword are dynamically typed.
The type of the variable is decided by the The type of the variable is decided by the
compiler at compile time. compiler at run time.
The variable of this type should be initialized at The variable of this type need not be initialized
the time of declaration. So that the compiler will at the time of declaration. Because the compiler
decide the type of the variable according to the does not know the type of the variable at
value it initialized. compile time.
If the variable does not initialized it throw an If the variable does not initialized it will not
error. throw an error.

Difference between is and as operator.

The is operator is used to check if the run-time as operator is used to perform conversion


type of an object is compatible with the given between compatible reference types or Nullable
type or not types.
The is operator is of boolean type as operator is not of boolean type.
The is operator returns true if the given object is as operator returns the object when they are
of the same type and false if it is of not same compatible with the given type. Returns null if
type the conversions fails.
The is operator is used for only reference, as operator is used only for nullable, reference
boxing, and unboxing conversions and boxing conversions

Boxing and unboxing in c#

Boxing Unboxing
The process of Converting a Value Type (char, The process of converting reference type into
int etc.) to a Reference Type(object) is the value type is known as Unboxing.
called Boxing.
Boxing is implicit conversion process in which It is explicit conversion process.
object type (super type) is used.
The Value type is always stored in Stack. The Referenced Type is stored in Heap.
int num = 23; int num = 23;
Object Obj = num; // Boxing Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing

Difference between stored procedure and function:

Function Stored procedure


The function always returns a value. Stored Procedure will not return a value, but the
procedure can return “0” or n values.
Functions have only input parameters for it. Whereas, Procedures can have output or input
parameters.
A function cannot call a stored procedure A stored procedure can call a function.
Allows only select statement Allows select as well as DML statements
IQueryable and IEnumerable in c#
Both have some intended usability scenarios for which they are made. While querying data from
database, IEnumerable executes select query on server side, load data in-memory on client side and
then filter data. ... While querying data from database, IQueryable executes select query on server
side with all filters.
Localization and Globalization: Globalization is a process of designing applications intended for
users of different languages across the Globe while Localization is a process of designing the
application so that it can display contents in the language of the user.
Difference between Executereader, ExecuteNonquery and Executescalar:

ExecuteNonquery Executereader ExecuteScalar


will work with Action Queries will work with Action and Non- will work with Non-Action
only (Create, Alter, Drop, Action Queries (Select) Queries that contain
Insert, Update, Delete). aggregate functions.
Returns the count of rows Returns the collection of rows Return the first row and
effected by the Query. selected by the Query. first column value of the
query result.
Return type is int Return type is DataReader. Return type is object.
Return value is optional and Return value is compulsory and Return value is compulsory
can be assigned to an integer should be assigned to an another and should be assigned to a
variable. object DataReader. variable of required type.

Linq query: var result = from s in stringList


where s.Contains("Tutorials")
select s;
Lambda expression: input-parameters) => { <sequence-of-statements> } Ex: x => (x % 2) == 0)
Difference between sealed and private class:
A Private class can only be accessed by the class it is defined and contain within - it is completely
inaccessible to outside classes.
A Sealed class can be accessed by any class, but can not be derived from.
Difference between == and equals():

== Equals()
== compares object references. .Equals compares object content.
public class Test {
    public static void main(String[] args)
    {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1 == s2); //false
        System.out.println(s1.equals(s2)); //true
    }
}
Stored procedure in sql server:
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;
EXEC SelectAllCustomers @City = "London", @PostalCode = "WA1 1DP";
Second max salary:
Select top 1 salary select max(salary)
From ( select distinct top N salary from employee
From employee where salary< (select max(salary)
Order by salary DESC ) As temp from employee);
Order by salary; //where N=1,2,3,…
Difference between clustered and non clustered index

Clustered index Non clustered index


Cluster index is a type of index which sorts the
A Non-clustered index stores the data at one
data rows in the table on their key values location and indices at another location. The
index contains pointers to the location of that
data
There is only one clustered index per table. A single table can have many non-clustered
indexes as an index in the non-clustered index is
stored in different places.
Data accessing is faster Data accessing is slower
Additional disk space is not required Additional space is required for storing indices
The main feature is, the clustered index  can The main feature is, It should be created on
improve the performance of data retrieval. columns which are used in joins.
CREATE CLUSTERED INDEX ix_parts_id ON production.parts (part_id);
CREATE [NONCLUSTERED] INDEX index_name ON table_name(column_list);
SQL Injection: It is a code injection technique that might destroy yourdatabase. It is one of the most
common web hacking techniques. It is the placement of malicious code in SQL statements, via web
page input.
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and passwords in a database, by simply inserting 105
OR 1=1 into the input field.
The correct order for a proper SQL query:
Select , from, where, group by, having, order by
Difference between collection and collections:

Collection Collections
Collection is an interface Collections is a class
Collection is base interface for list, set and Collections is a class and it is called utility
queue. class.
Difference between array and arraylist:

Array ArrayList
A data structure consisting of a collection of A class that supports dynamic arrays which can
elements each identified by array index grow as needed
Using = operator for storing elements Add() method for storing elements
Helps to implement fixed size data structure Helps to implement dynamic size arrays
Can contain primitive or objects Can only store objects

Difference between Arraylist and Linkedlist

Arraylist Linkedlist
It is index based data structure where each Uses doubly linkedlist i.e previous element,
element is associated with index value and next element referencing
Occcupies less memory Occupies more memory because of nodes
holding the reference elements
It is used when application requires more It is used when application requires more
retrivals than insertions insertions than retrivals
Better for storing and accessing data Better for manipulating data
Difference between hashmap and hashset

Hashmap Hashset

Hash table based implementation of Map It is a set. Uses hash table for storage
interface

Implements Map, cloneable, Serializable Implements Set, Cloneable, Serializable,


interfaces Iterable, Collections.

Stores key-value pairs It stores as objects.

Dose not allow duplicated keys but No duplicate values


duplicate values

Can have single null key and multiple No duplicate values


null values
Put() to add elements Add() to add elements

Faster than hashset because it has uniq Slower than HashMap because member obj is
values used for calculating hashcode which can be
same 2 objects.

Only 1 object is created during the add Two objects created when add() operation is
operation done. 1 for key 2 value

Uses hashing to store objects Uses hash map to store objects

Always prefer when we do not maintain Prefer when uniqueness is required


uniqueness

Difference between HashMap and Hashtable

HashMap Hashtable

Non Synchrionised. Not Thread Safe Synchronized. Thread Safe

One null key , multiple null values Does not allow any null key/value

Fast Slow

MVC life cycle: MVC has two life cycles – 1)The application life cycle 2)The request life cycle
The Application Life Cycle:
The application life cycle refers to the time at which the application process actually begins running
IIS until the time it stops. This is marked by the application start and end events in the startup file of
your application.

The Request Life Cycle:

Creating the request object: -The request object creation has four major steps. Below is the
detail explanation of the same.

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller
and action to be invoked. So if the request is the first request the first thing is to fill the route table
with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to
create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext”
object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create
the controller class instance. Once the controller class object is created it calls the “Execute” method
of the controller class.
Creating Response object: - This phase has two steps executing the action and finally sending the
response as a result to the view.

Routing in MVC: Routing helps you to define a URL structure and map the URL with the controller.
The route mapping code is written in "RouteConfig.cs" file and registered using "global.asax"
application start event.

Advantage of defining route structures in the code :


Most of the time developers code in the action methods. Developers can see the URL structure right
upfront rather than going to the “routeconfig.cs” and see the lengthy codes.

public class RouteConfig

{ public static void RegisterRoutes(RouteCollection routes)

{ routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new{ controller = "Home", action = "Index",


id=UrlParameter.Optional});

Route table consists of Routename, RouteURL, Physicalfile name

Bundling : It helps us improve request load times of a page thus increasing performance.Web
projects always need CSS and script files. Bundling helps us combine multiple JavaScript and
CSS files in to a single entity thus minimizing multiple requests in to a single request.

Minification reduces the size of script and CSS files by removing blank spaces , comments etc.
For example below is a simple javascript code with comments.

Sessions in MVC: Sessions can be maintained in MVC by three ways: tempdata, viewdata, and
viewbag.

Maintain data Viewdata/viewbag Temp data Hidden fields Session


between

Controller to No Yes NO Yes


Controller

Controller to View Yes No NO Yes

View to controller No No Yes (Helps to Yes (By using


maintain data from session variables
UI to controller we can maintain
only. So you can data from any
send data from entity to any
HTML controls or entity.)
hidden fields to the
controller using
POST or GET
HTTP methods.)

“TempData” maintains data for the complete request while “ViewData” maintains data only from
Controller to the view.

Partial view: Partial view is a reusable view (like a user control) which can be embedded inside other
view. For example let’s say all your pages of your site have a standard structure with left menu,
header, and footer.

Razor in MVC: It’s a light weight view engine. Till MVC we had only one view type, i.e.,
ASPX. Razor is clean, lightweight, and syntaxes are easy as compared to ASPX. For example, in
ASPX to display simple time, we need to write:

In aspx <%=DateTime.Now%> In razor @DateTime.Now

Return types of action result MVC: ActionResult is an abstract class. Below are derived class

ViewResult, PartialViewResult, ContentResult, RedirectResult, RedirectToRouteResult, JsonResult,

EmptyResult, FileResult.

Difference between Truncate, delete and drop:

Delete duplicate rows with no primary key on a SQL Server table


DELETE TOP (SELECT COUNT(*) -1 FROM dbo.duplicateTest WHERE ID = 1)
FROM dbo.duplicateTest
WHERE ID = 1

You might also like