Category Archives: Interview

18 道 Google 面试题

即使是最成功的公司,它的招聘过程有时也会很不靠谱,经常会出一些奇怪的看似没有答案的面试问题,但标准答案却让应聘者还没来得及接近「起跑线」就被「退赛」了。Google 曾经就是这样的公司,招聘人员会出一些难为应聘者的高质量问题。

事实上,有些问题实在是太古怪了,最终被完全禁用。2009 年,西雅图工作教练 Lewis 列出了他的客户被 Google 公司问过的 140 个问题,并选出了 17 个最让人抓狂的问题。这些问题已经被禁用了,Google 公司未来的新员工应该感到庆幸。下面让我们看看这些让人崩溃的问题吧。

1. 清洗所有西雅图的窗户需要多少钱?seattle-getty

2. 为什么井盖是圆的?

3. 如何在不直接询问你朋友 Bob 的情况下,确认他是否有你的电话号码?

你必须在卡片上写下问题并将卡片给 Eve,Eve 将卡片转交给 Bob 并将问题的回复转达给你。你不能直接将问题写在卡片上,但要确保让 Bob 对回复的信息进行加密,将电话号码对 Eve 保密。

4. 全世界有多少钢琴调音师?6-piano-palyer-get

5. 在一个有 100 对已婚夫妇的村庄里,每个男人都欺骗他的妻子

村里的每个妇人都会立刻知道其他妇人的丈夫是否欺骗了他的妻子,但不知道自己的丈夫有没有欺骗自己。村里规定不允许私通。任何妇人只要能证明她的丈夫对她不忠,她的丈夫就必须在当天被处死。村里的妇人们都遵守这项规定。有一天,村庄的女王宣布至少有一个丈夫不忠。究竟发生了什么?

6. 一个人把车推到了一家旅馆并失去了他的财产,发生了什么?

7. 钟表的指针每天重叠多少次?

daylight-savings-time

8. 美国每年生产多少个真空装置?

9. 为旧金山设计一个疏散计划

10. 解释一下「死牛肉」的重要性

Fui1OkEhMfBfgxx9dc0T2BAanddu

11. 如果一个人在电话上拨了一串数字,这些数字最有可能组成什么单词或是字符串?

12. 如果保证人体密度不变的情况下,将你缩小到一个硬币的大小,并且被扔进了一个空的玻璃搅拌机中,搅拌机将在 60 秒之后启动,你将怎么做?

13. 一辆校车能装多少个高尔夫球?

623221_bin

14. 两个鸡蛋和 100 层大楼的问题

你拥有两个鸡蛋,鸡蛋从某一特定楼层及以上的楼层扔下会破粹,从以下的楼层扔下会完好无损。两个鸡蛋完全相同。现在有一个 100 层的大楼,只有两个鸡蛋可以使用,你需要找出让鸡蛋摔碎的临界楼层,问题是你将扔多少次鸡蛋?

15. 你必须从 A 点到达 B 点,但你并不清楚能否到达,你将怎么办?

16. 你和你的朋友一起参加一个派对,同时出席的一共有十个人(包括你和你的朋友)

v2-drinking

17. 用三句话向你八岁大的侄子解释什么是数据库

from:http://www.techug.com/google-used

原文地址:www.independent.co.uk

100+ Core Java Interview Questions

Table of Contents

  1. Basic Questions
  2. OOPs interview Questions
  3. Exception handling interview Questions
  4. Java Multithreading interview Questions
  5. Serialization interview Questions
  6. String Interview Questions
  7. Java Collections interview Questions
  8. Applet interview Questions

Basic Questions

Q) Is Java platform independent?
Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run it on Linux or any other supported platform. This is one of the main features of java.

Q) What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack

Q) Java vs. C ++?
The following features of java make it different from the C++:

  • Simple
  • Multi-threaded
  • Distributed Application
  • Robust
  • Security
  • Complexities are removed (Pointers, Operator overloading, Multiple inheritance).

Q) What is javac ?
It produces the java byte code from *.java file. It is the intermediate representation of your source code that contains instructions.

Q) What is class?
Class is nothing but a template that describes the data and behavior associated with instances of that class

Q) What is the base class of all classes?
java.lang.Object

Q) Path and ClassPath
Path specifies the location of .exe files while classpath is used for specifying the location of .class files.

Q) Different Data types in Java.

  • byte – 8 bit (are esp. useful when working with a stream of data from a network or a file).
  • short – 16 bit
  • char – 16 bit Unicode
  • int – 32 bit (whole number)
  • float – 32 bit (real number)
  • long – 64 bit (Single precision)
  • double – 64 bit (double precision)

Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int before the calculation is done.

Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.

Q) What are Literals?
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.

Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

Q) What is Type casting in Java?
To create a conversion between two incompatible types, we must use a cast. There are two types of casting in java: automatic casting (done automatically) and explicit casting (done by programmer).

Q) Arrays?
An array is a group of fixed number of same type values. Read more about Arrays here.

Q) What is BREAK statement in java?
It is also referred as terminator. In Java, the break statement can be used in following two cases:

  • It terminates a statement sequence in a switch-case statement.
  • It can be used to come out of a loop

Q) Why can’t I do myArray.length () ? Arrays are just objects, right?
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length.

Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:

Java -jar [-options] jarfile [args...]

Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.

Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided.

Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need to explicitly import this package. The major classes inside this package are

  • Object class
  • Data type wrapper classes
  • Math class
  • String class
  • System and Runtime classes
  • Thread classes
  • Exception classes
  • Process classes
  • Class classes

Q) Arrays can be defined in different ways. Write them down.

int arr[] = null;
int arr[][] = new int arr[][];
int [][] arr = new arr [][];
int [] arr [] = new arr[][];

OOPs Interview Questions

Q) Four main principles of OOPS language?

  • Inheritance
  • Polymorphism
  • Data Encapsulation
  • Abstraction

Q) What is inheritance?
The process by which one class acquires the properties and functionalities of another class. Inheritance brings reusability of code in a java application. Read more here.

Q) Does Java support Multiple Inheritances?
When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between java and C++.  Refer this: Why java doesn’t support multiple inheritance?

Q) What is Polymorphism and what are the types of it?
Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism, read them in detail here.

Q) What is the method overriding?
It is a feature using which a child class overrides the method of parent class. It is only applicable when the method in child class has the signature same as parent class. Read more about method overriding here.

Q) Can we override a static method?
No, we cannot override a static method.

Q) What is method overloading?
Having more than one method with the same name but different number, sequence or types of arguments is known is method overloading. Read more about it here.

Q) Does Java support operator overloading?
Operator overloading is not supported in Java.

Q) Can we overload a method by just changing the return type and without changing the signature of method?
No, We cannot do this.

Q) Is it possible to overload main() method of a class?
Yes, we can overload main() method as well.

Q) What is the difference between method overloading and method overriding?
There are several differences; You can read them here: Overloading Vs Overriding.

Q) What is static and dynamic binding?
Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.

Q) What is Encapsulation?
Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”. Read it here in detail.

Q) Abstract class?
An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.

Q) What is Interface in java?
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Read more about interface here.

Q) What is the difference between abstract class and interface?
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.

Q) Which access modifiers can be applied to the inner classes?
public ,private , abstract, final, protected.

Q) What are Constructors?
Constructors are used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be same and it doesn’t have a return type. Read more about constructors here.

Q) Can we inherit the constructors?
No, we cannot inherit constructors.

Q) Can we mark constructors final?
No, Constructor cannot be declared final.

Q) What is default and parameterized constructors?
Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, compiler creates a default one automatically.

Parameterized: Constructor with arguments are known as parameterized constructors.

Q) Can a constructor call another constructor?
Yes. A constructor can call the another constructor of same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.

Q) Can a constructor call the constructor of parent class?
Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keyword. For e.g. super() can be used for calling super class default constructor.

Note: super() must be the first statement in a constructor.

Q)THIS keyword?
The THIS keyword is a reference to the current object.

Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.

Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,

Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it.
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.

Q) What is static variable in java?
Static variables are also known as class level variables. A static variable is same for all the objects of that particular class in which it is declared.

Q) What is static block?
A static block gets executed at the time of class loading. They are used for initializing static variables.

Q) What is a static method?
Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.

Q) Explain super keyword in Java?
super keyword references to the parent class. There are several uses of super keyword:

  • It can be used to call the superclass(Parent class) constructor.
  • It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
  • To call the constructor of parent class.

Q) Use of final keyword in Java?
Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class. More details.

Q) What is a Object class?
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods

  • objectClone () – to creates a new object that is same as the object being cloned.
  • boolean equals(Object obj) – determines whether one object is equal to another.
  • finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
  • toString () – Returns a string representation of the object.

Q) What are Packages?
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )

Q)What is the difference between import java.util.Date and java.util.* ?
The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.

Q) What is static import?
Read it here.

Q) Garbage collection in java?
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. The whole purpose of Garbage collection is efficient memory management.

Q) Use of finalize() method in java?
finalize() method is used to free the allocated resource.

Q) How many times does the garbage collector calls the finalize() method for an object?
The garbage collector calls the finalize() method Only once for an object.

Q) What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().

Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

Exception handling Interview Questions

Q) What is an exception?
Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.

Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.

Q) What are the types of exceptions?
There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.

Q) What is the difference between Error and Exception?
Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.

Q) What is throw keyword in exception handling?
The throw keyword is used for throwing user defined or pre-defined exception.

Q) What is throws keyword?
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.

Q) Difference between throw and throws in Java
Read the difference here: Java – throw vs throws.

Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.

Q) What is finally block?
Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.

Q) ClassNotFoundException vs NoClassDefFoundError?
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.

Q) Can we have a try block without catch or finally block?
No, we cannot have a try block without catch or finally block. We must have either one of them or both.

Q) Can we have multiple catch blocks following a single try block?
Yes we can have multiple catch blocks in order to handle more than one exception.

Q) Is it possible to have finally block without catch block?
Yes, we can have try block followed by finally block without even using catch blocks in between.

When a finally block does not get executed?
The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.

Q) Can we handle more than one exception in a single catch block?
Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.

Q) What is a Java Bean?
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

Java Multithreading Interview Questions

Q) What is Multithreading?
It is a process of executing two or more part of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.

Q) What is the main purpose of having multithread environment?
Maximizing CPU usage and reducing CPU idle time

Q) What are the main differences between Process and thread? Explain in brief.
1)  One process can have multiple threads. A thread is a smaller part of a process.
2)  Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify etc. This process is known as inter process communication.

Q) How can we create a thread in java?
There are following two ways of creating a thread:
1)  By Implementing Runnable interface.
2)  By Extending Thread class.

Q) Explain yield and sleep?
yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.

Q) What is the difference between sleep() and wait()?
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock

wait() – It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

Q) What is a daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

Q) What does join( ) method do?
if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.

Q) Preemptive scheduling vs. time slicing?
1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or other factor.

Q) Can we call run() method of a Thread class?
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.

Q) What is Starvation?
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Q) What is deadlock?
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

Serialization interview Questions

Q: What is Serialization and de-serialization?
Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization. To know more about serialization with example program, refer this article.

Q) Do we need to implement any method of Serializable interface to make an object serializable?
No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

Q) What is a transient variable?
1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.

String interview questions

Q) A string class is immutable or mutable?
String class is immutable that’s the reason once its object gets created, it cannot be changed further.

Q) Difference between StringBuffer and StringBuilder class?
1) StringBuffer is thread-safe but StringBuilder is not thread safe.
2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.

Q) What is toString() method in Java?
The toString() method returns the string representation of any object.

Java collections interview questions

Q) What is List?
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.

Q) What is Map?
Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.

Q) What is Set?
A Set is a Collection that cannot contain duplicate elements.

Q) Why ArrayList is better than Arrays?
Array can hold fixed number of elements. ArrayList can grow dynamically.

Q) What is the difference between ArrayList and LinkedList?
1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations. Read more here.

Q) For addition and deletion. Which one is most preferred: ArrayList or LinkedList?
LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.

Q) For searches. Which one is most preferred: ArrayList or LinkedList?
ArrayList. Searching an element is faster in ArrayList compared to LinkedList.

Q) What is the difference between ArrayList and Vector?
1) Vector is synchronized while ArrayList is not synchronized.
2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases by half of its size when it is re-sized. More details.

Q) What is the difference between Iterator and ListIterator?
Following are the major differences between them:
1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions(forward and backward). Read more at: ListIterator vs Iterator.

Q) Difference between TreeSet and SortedSet?
TreeSet implements SortedSet interface.

Q) What is the difference between HashMap and Hashtable?
1) Hashtable is synchronized. HashMap is not synchronized.
2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. Read more here.

Q) What is the difference between Iterator and Enumeration?
1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().

Applet Interview Questions

Q) How do you do file I/O from an applet?
Unsigned applets are simply not allowed to read or write files on the local file system .

Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files

Q) What is container ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog

Learning)

  1. Flow Layout is default for panel.
  2. Border Layout is default for Frames.

Q) On Windows, generally frames are invisible, how to make it visible. ?

Frame f = new Frame();
f.setSize(300,200);  //height and width
f.setVisible(true) ;  // Frames appears

Q) JFC – Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility

Learning) Listeners and Methods?
ActionListerner – actionPerformed();
ItemListerner – itemStateChanged();
TextListener – textValueChanged();
FocusListener – focusLost(); & FocusGained();

WindowListener – windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();

MouseMotionListener – mouseDragged(); & mouseMoved();

MouseListener – mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();

Learnings)
parseInt – to convert string to int.
getBytes – string to byte array

Q) Applet Life cycle?
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().

Q) showStatus() ?–
To display the message at the bottom of the browser when applet is started.

Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event Handling.

Q) What is Adapter class?
Adapter class is an abstract class.

Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to override. Straight opposite to Interface.

Further readings:
If you have finished reading above interview questions then you can go through the below tutorials to sharpen your knowledge in java. We will keep adding new question and answers to the above list.

1) Java Collection tutorial
2) Core Java concepts
3) OOPs concepts
4) Java Multithreading
5) String class and its methods
6) Java Exception handling

from:http://beginnersbook.com/2013/05/java-interview-questions/

AngularJS Interview Questions and Answers

Contents

Angular Interview questions and answers

What is AngularJS ?

Explain Directives in Angular?

What are controllers and need of ng-controller and ng-model in Angular?

What are expressions in Angular?

How can we initialize Angular application data?

Explain $scope in Angular?

What is “$rootScope” and how is it related with “$scope”?

Do I need Jquery for Angular?

How is the data binding in Angular ?

How do we make HTTP get and post calls in Angular?

How do we pass data using HTTP POST in Angular ?

What is dependency injection and how does it work in Angular?

How does DI benefit in Angular?

What are services in Angular?

Are Service object instances global or local?

What is a Factory in Angular?

What is the difference between Factory and Service?

My other interview question articles

Angular Interview questions and answers

AngularJS is one of those hot topics which interviewer’s ask for Web programming. In this article we will run through some important Interview questions around AngularJS and how we should be go about answering the same.

Do not forget to see our Learn MVC with Angular in 2 days i.e. ( 16 hours ) video series. Start from this youtube video link. https://www.youtube.com/watch?v=Lp7nSImO5vk

What is AngularJS ?

“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements.”

Let us try to understand the above definition with simple sample code.

Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.

function Customer() 
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();

Now let us say the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.

<input type=text id="TxtCustomerName" onchange="UitoObject()"/>

So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.

function UitoObject() 
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi() 
{
$("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.

Now the same above code can be written in Angular as shown below. The javascript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are binded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.

<div ng-controller="Customer">
<input type=text id="txtCustomerName"  ng-model="CustomerName"/>
</div>

In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Explain Directives in Angular?

Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox “txtCustomerName” has to be binded with the “CustomerName” property.

<input type=text id="txtCustomerName"  ng-model="CustomerName"/>

Some of the most commonly used directives are ng-app,ng-controller and ng-repeat.

What are controllers and need of ng-controller and ng-model in Angular?

“Controllers” are simple javascript function which provides data and logic to HTML UI. As the name says controller they control how data flows from the server to HTML UI.

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” property and Add/ Update logic to save the data to database.

Note: – Do not worry too much about the $scope , we will discuss the same in the next question.
function Customer($scope)
{
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}

“ng-controller” is a directive.Controllers are attached to the HTML UI by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example below is a simple HTML UI which is attached to the “Customer” controller via the “ng-controller” directive and the properties are binded using “ng-model” directive.

<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>

What are expressions in Angular?

Angular expressionsare unit of code which resolves to value. This code is written inside curly braces “{“.

Below are some examples of angular expressions:-

The below expression adds two constant values.

{{1+1}}

The below expression multiplies quantity and cost to get the total value.

The value total cost is {{ quantity * cost }}

The below expression displays a controller scoped variable.

<div ng-controller="CustomerVM">
The value of Customer code is {{CustomerCode}} 
</div>
The value of Customer code is {{CustomerCode}}

How can we initialize Angular application data?

We can use “ng-init” directive to achieve the same. You can see in the below example we have used “ng-init” directive to initialize the “pi” value.

<body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>

Explain $scope in Angular?

“$scope” is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.

For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControllerName” variable.

function Function1($scope)
{
$scope.ControllerName = "Function1";        
}
function Function2($scope)
{
$scope.ControllerName = "Function2";
}

Now to attach the above controllers to HTML UI we need to use “ng-controller” directive. For instance you can see in the below code snippet how “ng-controller” directive attaches “function1” with “div1” tag and “function2” with “div2” tag.

<div id=&rdquo;div1&rdquo; ng-controller="Function1">
Instance of {{ControllerName}} created 
</div>
<div id=&rdquo;div2&rdquo; ng-controller="Function2">
Instance of {{ControllerName}} created 
</div>

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM and following are the sequence of events:-

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. He creates a new instance of “$scope” object and connects to the “div1” UI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. He creates a new instance of “$scope” object and connects to the “div2” UI.

Now once the instances are created, below is a graphical representation of the same. So the “DIV1” HTML UI is binded with “function1” $scope instance and the “DIV2” HTML UI is binded with “function2” $scope instance. In other words now anything changes in the $scope object the UI will be updated and any change in the UI will update the respective $scope object.

What is “$rootScope” and how is it related with “$scope”?

“$rootScope” is a parent object of all “$scope” angular objects created in a web page.

Let us understand how Angular does the same internally. Below is a simple Angular code which has multiple “DIV” tags and every tag is attached to a controller. So let us understand step by step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

The Browser first loads the above HTML page and creates a DOM (Document object model) and Angular runs over the DOM.Below are the steps how Angular creates the rootscope and scope objects.

  • Step 1:- Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.
  • Step 2:- Angular parser moves ahead and finds the expression {{SomeValue}}. It creates a variable
  • Step 3:- Parser then finds the first “DIV” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object it then attaches to “$rootScope” object.
  • Step 4:- Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

<script language="javascript">
function Function1($scope, $rootScope) 
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.Counter = $rootScope.Counter;
        $scope.ControllerName = "Function1";
}
function Function2($scope, $rootScope) 
{
        $rootScope.Counter = (($rootScope.Counter || 0) + 1);
        $scope.ControllerName = "Function2";
}
    var app = angular.module("myApp", []); // creating a APP     app.controller("Function1", Function1); // Registering the VM     app.controller("Function2", Function2);

</script>

Below is the HTML code for the same. You can we have attached “Function1” and “Function2” two times with “ng-controller” which means four instances will be created.

<body ng-app="myApp" id=1>
   Global value is {{Counter}}<br />
<div ng-controller="Function1">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
       Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function1">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
<div ng-controller="Function2">
        Child Instance of {{ControllerName}} created :- {{Counter}}
</div><br />
</body>

Above is the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootScope” object.

Do I need Jquery for Angular?

No , you do not need Jquery for Angular. It’s independent of Jquery.

How is the data binding in Angular ?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

How do we make HTTP get and post calls in Angular?

To make HTTP calls we need to use the “$http” service of Angular. In order to use the http services you need to make provide the “$http” as a input in your function parameters as shown in the below code.

function CustomerController($scope,$http)
{
	$scope.Add = function()
	{
            $http({ method: "GET", url: "http://localhost:8438/SomeMethod"     }).success(function (data, status, headers, config)
		{
                   // Here goes code after success 		}
	}
}

“$http” service API needs atleast three things:-

  • First what is the kind of call “POST” or “GET”.
  • Second the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.
$http({ method: "GET", url: "http://localhost:8438/SomeMethod"    }).success(function (data, status, headers, config)
{
// Here goes code after success }

How do we pass data using HTTP POST in Angular ?

You need to pass data using the “data” keyword in the “$http” service API function. In the below code you can see we have created a javascript object “myData” with “CustomerName” property. This object is passed in the “$http” function using HTTP POST method.

Var myData = {};
myData.CustomerName = &ldquo;Test&rdquo;;
$http({ method: "POST",
	data: myData,
	url: "http://www.xyz.com"})
	.success(function (data, status, headers, config)
	{
	  // Here goes code after success 	}

What is dependency injection and how does it work in Angular?

Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects. DI is everywhere in Angular or we can go one step ahead and say Angular cannot work without DI.

For example in the below code “$scope” and “$http” objects are created and injected by the angular framework. The consumer i.e. “CustomerController” does not create these objects himself rather Angular injects these objects.

function CustomerController($scope,$http)
{
// your consumer would be using the scope and http objects }

How does DI benefit in Angular?

There are two big benefits of DI: – Decoupling and Testing.

Let’s first start with Decoupling. Consider your application has a logger functionality which helps to log errors , warning etc in some central place. This central place can be a file, event viewer, database etc.

function FileLogger()
{
        this.Log = function () {
            alert("File logger");
        };
}
function EventLogger()
{
        this.Log = function () {
            alert("Event viewer logger");
        };
}

Now let’s say you have a “Customer” class who wants to use the “Logger” classes. Now which “Logger” class to use depends on configuration.

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates “EventLogger” object.

function Customer($scope, Logger)
{
        $scope.Logger = {};
        if (config.Loggertype = "File")
{
            $scope.Logger = new FileLogger();
        }
        else
{
            $scope.Logger = new EventLogger();
        }
}

But with DI our code becomes something as shown below. The “Customer” class says he is not worried from where the “Logger” object comes and which type of “Logger” objects are needed .He just wants to use the “Logger” object.

function Customer($scope,$http, Logger)
{
        $scope.Logger = Logger;
}

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.
The second benefit of DI is testing. Let’s say you want to test the “Customer” class and you do not have internet connection. So your “$http” object method calls can throw errors. But now you can mock a fake “$http” object and run your customer class offline without errors.The fake object is injected using DI.

What are services in Angular?

Service helps to implement dependency injection. For instance let’s say we have the below “Customer” class who needs “Logger” object. Now “Logger” object can be of “FileLogger” type or “EventLogger” type.

function Customer($scope,$http, Logger)
{
        $scope.Logger = Logger;
}

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

var app = angular.module("myApp", []); // creating a APP app.controller("Customer", Customer); // Registering the VM app.service("Logger", EventLogger); // Injects a global Event logger object 

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Are Service object instances global or local?

Angular Services create and inject global instances. For example below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

function HitCounter()
{
       var i = 0;
        this.Hit = function ()
        {
            i++;
            alert(i);
        };
}

This “HitCounter” class object is injected in “MyClass” class as shown in the below code.

function MyClass($scope, HitCounter)
{
	$scope.HitCounter = HitCounter;
}

Below code advises the Angular framework to inject “HitCounter” class instance in the “MyClass” class. Read the last line of the below code specially which says to inject the inject the “HitCounter” instance.

var app = angular.module("myApp", []); // creating a APP app.controller("MyClass", MyClass); // Registering the VM app.service("HitCounter", HitCounter); // Injects the object 

Now let’s say that the “Controller” “MyClass” is attached to twodiv tag’s as shown in the below figure.

So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “HitCounter” object instance is created and injected in to “MyClass” first instance.

When the second instance of “MyClass” is created the same “HitCounter” object instance is injected in to second instance of “MyClass”.
Again I repeat the same instance is injected in to the second instance, new instances are not created.

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

What is a Factory in Angular?

“Factory” in real world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers likelaptops,desktops, tablets etc.

Now the process of manufacturing the computer products are same with slight variation. To manufacture any computer we need processor, RAM and hard disk. But depending on what kind of final case packing is the final product shapes.

That’s what the use of Factory in Angular.

For example see the below code we have a “Customer”, “Phone” and “Address” class.

function Customer()
{
        this.CustomerCode = "1001";
        this.CustomerName = "Shiv";
}
function Phone()
{
        this.PhoneNumber = "";
}
function Address()
{
        this.Address1 = "";
        this.Address2 = "";
}

So now we would create different types of “Customer” object types using the combination of “Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has “Address” collection inside it.
  • Or must be we would like to create “Customer” object with “Phone” objects inside it.
  • Or must be “Customer” object with both “Phone” and “Address” objects.

In other words we would like to have different permutation and combination to create different types of “Customer” objects.

So let’s start from bottom. Let’s create two factory function’s one which creates “Address” object and the other which creates “Phone” objects.

functionCreateAddress()
{
var add = new Address();
return add;
}
functionCreatePhone()
{
var phone =  new Phone();
return phone;
}

Now let’s create a main factory function which uses the above two small factory functions and gives us all the necessary permutation and combination.

In the below factory you can see we have three functions:-

  • “CreateWithAddress” which creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” which creates “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” which creates “Customer” object with aggregated “Phone” and “Address” objects.
function CreateCustomer() {

return {
CreateWithAddress: function () {
varcust = new Customer();
cust.Address = CreateAddress();
returncust;
            },
CreateWithPhone: function () {
varcust = new Customer();
cust.Phone = {};
cust.Phone = CreatePhone();
returncust;
            }
            ,
CreateWithPhoneAddress: function () {
debugger;
varcust = new Customer();
cust.Phone = CreatePhone();
cust.Address = CreateAddress();
returncust;
            }
        }
    }

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address” , “Phones” or both of them.

functionCustomerController($scope, Customerfactory)
    {

        $scope.Customer = {};
        $scope.Init = function(TypeofCustomer)
        {

if (TypeofCustomer == "1")
            {
                $scope.Customer = Customerfactory.CreateWithAddress();
            }
if (TypeofCustomer ==  "2")
            {
                $scope.Customer = Customerfactory.CreateWithPhone();
            }
if (TypeofCustomer == "3") {
                $scope.Customer = Customerfactory.CreateWithPhoneAddress();
            }
        }
    }

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

var app = angular.module("myApp", []); // creating a APP app.controller("CustomerController", CustomerController); // Register the VM app.factory("Customerfactory", CreateCustomer);

So if we consume the “CustomerController” in UI , depending on situation it creates different flavors of “Customer” object. You can in the below code we have three different “DIV” tags and depending on the “TypeofCustomer” we are displaying data.

What is the difference between Factory and Service?

“Factory” and “Service” are different ways of doing DI (Dependency injection) in angular. Please read the previous question to understand what is DI.

So when we define DI using “service” as shown in the code below. This creates a new GLOBAL instance of the “Logger” object and injects it in to the function.

app.service("Logger", Logger); // Injects a global object

When you define DI using a “factory” it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app.factory("Customerfactory", CreateCustomer);

Below is a simple image which shows visually how DI process for “Service” is different than “Factory”.

Factory Service
Usage When we want to create different types of objects depending on scenarios. For example depending on scenario we want to create a simple “Customer” object , or “Customer” with “Address” object or “Customer” with “Phone” object. See the previous question for more detailed understanding. When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

My other interview question articles

jQuery, JSON and Less Interview questions with answers

http://www.codeproject.com/Articles/778374/JQUERY-JSON-Angular-and-Less-Interview-questions

100 important ASP.NET MVC interview questions

http://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers

HTML 5 Interview questions with answers

http://www.codeproject.com/Articles/702051/important-HTML-Interview-questions-with-answe

WPF interview questions with answers

http://www.codeproject.com/Articles/744082/WPF-Interview-questions-with-answers

from:http://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-Answers

JQUERY, JSON and Angular Interview questions

What is Jquery ?

So will jquery replace javascript ?

So how do we use these reusable jquery libraries?

What is CDN (Content delivery network)?

For Jquery files which are the popular CDN’s?

How can we reference local Jquery files if CDN fails?

What is the difference between Jquery.js and Jquery.min.js file?

When should we use jquery.js over jquery.min.js ?

What is the use jquery.vsdoc.js ?

How does the basic syntax of Jquery looks like?

What is the “$” sign in Jquery ?

WhenshouldweuseJquery.noConflict()

What are the different ways by which you can select a HTML element in JQuery ?

What is the use of Document.ready in Jquery ?

Can we have two document.ready in a webpage?

What is JSON?

Do all technologies support JSON?

How can you make a JSON call using Jquery ?

How can we post JSON to Server?

How can we post a complete HTML form in JSON format?

How can we convert JSON string in to c# object?

What are single page applications (SPA)?

What is Angular JS ?

What is the need of ng-model, ng-expression and ng-app in Angular?

How is the data binding in Angular?

What is Jquery ?

Jquery is a reusable javascript library which simplifies javascript coding. So rather than writing length javascript code as below.

Collapse | Copy Code
document.getElementById("txt1").value = "hello";

By jquery the above javascript code is now simplified as below.

Collapse | Copy Code
$("#txt1").val("Hello");

If you want to kick start with Jquery start with the below video which is created by www.questpond.com

So will jquery replace javascript ?

No, Jquery is not meant to replace javascript. Jquery is a library while javascript is a language. Jquery sits on the top of javascript to make your development easy.

So how do we use these reusable jquery libraries?

You need to download Jquery.js file from jquery.com and include the same in your web pages. The jquery files are named with version number like “jquery-1.4.1.js” where 1.4.1 is the version of the JS file. So at the top of your web page you need to include the javascript as shown in the below code.

Collapse | Copy Code
<script src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

What is CDN (Content delivery network)?

In CDN multiple copies of the website is copied on different geographical servers. When users request website content which have CDN enabled depending on their geographical location , content is served from the nearest geographical location server of the user.

So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery of data.

For Jquery files which are the popular CDN’s?

There are two popular CDN’s Microsoft and google.

If you want to reference google CDN Jquery files you can use the below script.

Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

If you want to use Microsoft CDN you can use the below javascript.

Collapse | Copy Code
<script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>

How can we reference local Jquery files if CDN fails?

Many times it’s possible that Microsoft and google servers can go down for some time. So in those situations you would like your page to reference jquery files from local server.

So to implement a CDN fallback is a two-step process:-

First reference the CDN jquery. In the below code you can see we have reference Microsoft CDN jquery file.

Collapse | Copy Code
http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js "></script>

Now if Microsoft CDN is down then the Jquery value will be “undefined”. So you can see in the below code we are checking if the Jquery is having “undefined” value then do a document write and reference your local Jquery files.

Collapse | Copy Code
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}

Below is the full code for the same.

Collapse | Copy Code
<script type="text/javascript" src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/%20http:/ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js%2520"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
  document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>

What is the difference between Jquery.js and Jquery.min.js file?

First thing both the files provide the same jquery functionalities. One is a long version and the other is compressed / minified version. The minified version is compressed to save bandwidth and space by compressing and removing all the white spaces.

Below is the view of Jquery.js.

Below this is view of Jquery.min.js file (compressed and minified).

When should we use jquery.js over jquery.min.js ?

When you are doing development use “jquery.js” file because you would like to debug, see the javascript code etc. Use “Jquery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster.

What is the use jquery.vsdoc.js ?

This file you can include if you want to enable intellisense in visual studio for Jquery.

How does the basic syntax of Jquery looks like?

Jquery syntax structure can be broken down in to four parts:-

  • All Jquery commands start with a “$” sign.
  • Followed by the selection of the HTML element. For example below is a simple image where we are selecting a HTML textbox by id “txt1”.
  • Then followed by the DOT (.) separator. This operator will separate the element and the action on the element.
  • Finally what action you want to perform on the HTML element. For instance in the below Jquery code we are setting the text value to “Hello JQuery’.

What is the “$” sign in Jquery ?

The “$” sign is an alias for jquery.

When should we use Jquery.noConflict()?

There are many javascript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout etc. Some of these frameworks also use “$” sign so this can lead to conflict with Jquery framework.

So you can use the “noConflict” method and release the jquery “$” sign as shown in the below code.

Collapse | Copy Code
$.noConflict();
jQuery("p").text("I am jquery and I am working&hellip;");

You can also create your own jquery shortcut as shown below.

Collapse | Copy Code
var jq = $.noConflict();
jq("p").text("I am invoked using jquery shortcut&hellip;");

What are the different ways by which you can select a HTML element in JQuery ?

You can select Jquery elements in the following ways:-

Select all

Below is a simple code snippet which selects all paragraph tags and hides them.

Collapse | Copy Code
$("p").hide();

Select by ID

Collapse | Copy Code
$("#Text1").val("Shiv");

Select using Equal method

Select using Find method

Select using Filter method

What is the use of Document.ready in Jquery ?

“Document.Ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “text1” with value “Sometext”.

Now at the point when Jquery code tries set the textbox value , at that moment that text box is not available in the HTML DOM. So it throws an exception for the same.

Collapse | Copy Code
<script>
      $("#text1").val("Sometext"); // Throws exception as the textbox is not //accessible at this moment
</script>
</head>
<body>
<input type="text" id="text1" />
</body>

So we would like to execute the Jquery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.

Collapse | Copy Code
<script>
       $(document).ready(function(){
           $("#text1").val("Sometext");
       });
</script>

Here is a nice detail article with a video which explains Jquery Ready event in a more detail manner http://www.dotnetinterviewquestions.in/article_jquery-interview-questions:-when-do-we-need-documentreadyevent-_230.html 

 

Can we have two document.ready in a webpage?

Yes.

How can we attach a method to a HTML element event using Jquery ?

Below is a simple code which attaches a function to click event of a button.

Collapse | Copy Code
$("button").click(function(){
$("p").toggle();
});

Below is one more example where we have attached the a function to a mouse enter event of a paragraph.

Collapse | Copy Code
$("#p1").mouseenter(function(){
  alert("You entered p1!");
});

How can we add a style using Jquery?

$(“li”).filter(“.middle”).addClass(“selected”);

Collapse | Copy Code
<style>
      .selected { color:red; }
</style>

What is JSON?

JSON (JavaScript object notation) helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed in to javascript objects.

Below is a simple example of JSON format looks. You can understand from the format how lightweight and easy the format looks.

Figure :- JSON

The biggest advantage of JSON format is it can be evaluated to a javascript object. For instance you can see in the below code snippet we have a JSON format data which has “name”,”street”,”age” and “phone”. Now this data can be consumed as shown in the code snippet below, evaluated to a javascript object and invoked as anobject property.

You can see how we have called the “name” property using an object “JSONObject.name”.

Collapse | Copy Code
<script type="text/javascript">

var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555", 
"age":33,
"phone":"555 1234567"};

alert(JSONObject.name); 
</script>

Was not SOAP meant to do the same thing which JSON does?

SOAP is heavy due to XML tags. For example a SOAP message “Shiv” will become short , sweet and light in JSON like “Name” : “Shiv”. Second most important it evaluates as javascript object. To convert the complicated SOAP XML in to javascript JSON object would be a tough and tedious task.

Figure 11.11:- SOAP meant to do the same thing

Do all technologies support JSON?

Yes , Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.

Collapse | Copy Code
[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
           ResponseFormat=WebMessageFormat.Json)]
string GetData();

If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.

Collapse | Copy Code
public JsonResult  CustomerJson()
{
     List<Customer> obj1 = new List<Customer>();
     Thread.Sleep(5000);
            Customer obj = new Customer();
            obj.CustomerCode = "1001";
            obj1.Add(obj);
            return Json(obj1,JsonRequestBehavior.AllowGet);
}

If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code.”myPerson” is the class.

Collapse | Copy Code
DataContractJsonSerializer serializer = new DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End();

How can you make a JSON call using Jquery ?

Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF , ASP.NET , MVC etc as discussed in the previous questions.

Collapse | Copy Code
public JsonResult  getEmployee()
{
Emp obj = new Emp();
obj.empcode = "1001";
return Json(obj,JsonRequestBehavior.AllowGet);
}

To make a call to the above MVC action using Jquery we need to use “getJSON” method. Below is the simple code for the same. It has three parameters:-

  1. The first parameter is the URL which emits out JSON. For instance in the below code the URL is “/Employee/getEmployee”.
  2. The next parameter helps us to pass data to the resource which emits out JSON currently it’s the MVC action. Currently we are only doing a get so the second parameter is NULL for now.
  3. The last parameter is the call back function which will be invoked once the MVC action returns data. You can see how the “getData” function just displays the “empcode” property. Because the output is in JSON it automatically converts the JSON data to javascript object.
Collapse | Copy Code
$.getJSON("/Employee/getEmployee", null, getData);
function getData(data)
{
alert(data.empcode);
}

How can we post JSON to Server?

We can use the “post” method of jquery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the call back function where we receive the response.

Collapse | Copy Code
var mydata ={name:"Shiv",city:"Mumbai"};

$.post("/Send/Request", // URL
mydata , // Data to be sent
function(data,status){alert(data + &ldquo; &ldquo; + status);}); // Call back function

How can we post a complete HTML form in JSON format?

To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of Jquery.”DisplayData” is a callback function to handle the output given by the server.

Collapse | Copy Code
var Mydata = $("#form1").serialize();
$.post("/Customer/getCustomer",JSON. stringify (MyData), DisplayData);

The above posted JSON string is received at the server side “request.inputstream” , below is a simple sample code for the same.

Collapse | Copy Code
System.IO.Stream body = Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(body);
string s =   reader.ReadToEnd() ;

How can we convert JSON string in to c# object?

To convert a JSON string to a c# object we need to use the “JavascriptSerializer” class as shown in the below code.

“JsonString” is the string which has the JSON value and by using “Deserialize” we are converting the string to a c# object. Now this object which we receive is a collection of “key” and “value” pair which can be browsed and accessed in c#.

Collapse | Copy Code
var jsonser = new JavaScriptSerializer()
var obj = jsonser.Deserialize<dynamic>(JsonString);
foreach (var x in obj)
{
    String strvalue = x[&ldquo;value&rdquo;];
}

What are single page applications (SPA)?

SPA means you web page has the following :-

  • Utilize the browser client power to the maximum by executing the maximum code on the client side by using javascript , HTML and CSS.
  • Rather than loading the complete page necessary HTML fragments or JSON data is loaded as the user demands.
  • Javascript which handles DOM manipulation, binding, Ajax calls are separated in to controllers thus separating views and models.
  • DOM manipulations are replaced by declarative programming.

What is Angular JS ?

Angular JS is JavaScript framework to create SPA applications. It simplifies complex javascript DOM manipulation code by providing declarative tags. This provides a clean separation between DOM manipulation logic and the HTML view.

For example below is a simple Angular code which helps us to display textbox data in the DIV tag when the user types in the textbox.

Collapse | Copy Code
<input type=text ng-model="name">
<div>
Current user's name: {{name}}

Below is a simple video which explain Angular in 5 minutes with an example: –

 

ANGULAR JS Video

What is the need of ng-model, ng-expression and ng-app in Angular?

“ng-model” helps to store data which is typed in the HTML elements while expression helps to display the model data on the page. “ng-app” defines the root element for angular.

Below is a simple angular code which has all the three things: –

  • So whatever is typed in the textbox gets stored in the model.
  • The model is displayed by an expression {{}}.
  • “ng-app” defines the root.
Collapse | Copy Code
<div ng-app>
<input type=text ng-model="name">
Current user's name: {{name}}
</div>

How is the data binding in Angular?

Its two way binding. So whenever you make changes in one entity the other entity also gets updated.

from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions