Java Interview Questions
Q.How can you achieve Multiple Inheritance in Java? Ans: Java's interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations. Q.How To Replace the Characters in a String? Ans:
- Replace all occurrences of 'a' with 'o' String newString = string.replace('a', 'o'); Replacing Substrings in a String
static String replace(String str, String pattern, String replace) { int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e+pattern.length(); } result.append(str.substring(s)); return result.toString(); } Converting a String to Upper or Lower Case
- Convert to upper case
String upper = string.toUpperCase(); // Convert to lower case String lower = string.toLowerCase(); Converting a String to a Number int i = Integer.parseInt("123"); long l = Long.parseLong("123"); float f = Float.parseFloat("123.4"); double d = Double.parseDouble("123.4e10"); Breaking a String into Words String aString = "word1 word2 word3"; StringTokenizer parser = new StringTokenizer(aString); while (parser.hasMoreTokens()) { processWord(parser.nextToken()); Q.What is a transient variable? Ans: A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static. Q.What is the difference between Serializalble and Externalizable interface? Ans: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. Q.How many methods in the Externalizable interface? Ans: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). Q.How many methods in the Serializable interface? Ans: There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable. Q.How to make a class or a bean serializable? Ans: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable. Q.What is the serialization? Ans: The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage. Q.What are synchronized methods and synchronized statements? Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q.What is synchronization and why is it important? Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors. Q.What is the purpose of finalization? Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What happens when a thread cannot acquire a lock on an object? Ans: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. Q.What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Q.What restrictions are placed on method overloading? Ans: Two methods may not have the same name and argument list but different return types. Q.How does multithreading take place on a computer with a single CPU? Ans: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the ResourceBundle class? Ans: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.What is Serialization and deserialization? Ans: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. Q.What are the Object and Class classes used for? Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. Q.Can you write Java code for declaration of multiple inheritance in Java ? Ans: Class C extends A implements B { } Q.What do you mean by multiple inheritance in C++ ? Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student. Q.Write the Java code to declare any constant (say gravitational constant) and to get its value. Ans: Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } } Q.Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level. Ans: SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID AND Level.Level = "freshman" AND Student.Course = 3; Q.What do you mean by virtual methods? Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object. Q.What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. Q.What do mean by polymorphism, inheritance, encapsulation? Ans: Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information. Q.What are the advantages of OOPL? Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful. Q.How many methods do u implement if implement the Serializable Interface? Ans: The Serializable interface is just a "marker" interface, with no methods of its own to implement. Q.Are there any other 'marker' interfaces? Ans: java.rmi.Remote java.util.EventListener Q.What is the difference between instanceof and isInstance? Ans: instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() determines if the specified object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is nonnull and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. Q.why do you create interfaces, and when MUST you use one? Ans: You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved. Q.What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why? Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of the object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with. Q.Discuss the differences between creating a new class, extending a class and implementing an interface; and when each would be appropriate. Ans:
- Creating a new class is simply creating a class with no extensions and no implementations. The signature is as follows
public class MyClass() {
- Extending a class is when you want to use the functionality of another class or classes. The extended class inherits all of the functionality of the previous class. An example
of this when you create your own applet class and extend from java.applet.Applet. This gives you all of the functionality of the java.applet.Applet class. The signature would look like this public class MyClass extends MyBaseClass { }
- Implementing an interface simply forces you to use the methods of the interface implemented. This gives you two advantages. This forces you to follow a standard(forces you to use certain methods) and in doing so gives you a channel for polymorphism. This isn’t the only way you can do polymorphism but this is one of the ways.
public class Fish implements Animal { } Q.Name four methods every Java class will have. Ans: public String toString(); public Object clone(); public boolean equals(); public int hashCode(); Q.What does the "abstract" keyword mean in front of a method? A class? Ans: Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it, it is called abstract method.Abstract method has no body. It has only arguments and return type. Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. Q.Does Java have destructors? Ans: No garbage collector does the job working in the background Q.Are constructors inherited? Can a subclass call the parent's class constructor? When? Ans: You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language. QDoes Java have "goto"? Ans: No Q.What does the "final" keyword mean in front of a variable? A method? A class? Ans: FINAL for a variable : value is constant FINAL for a method : cannot be overridden FINAL for a class : cannot be derived Core Java Interview Questions and Answers Q.what is a transient variable? Ans: A transient variable is a variable that may not be serialized. Q.which containers use a border Layout as their default layout? Ans: The window, Frame and Dialog classes use a border layout as their default layout. Q.Why do threads block on I/O? Ans: Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed Q. How are Observer and Observable used? Ans: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. Q.What is synchronization and why is it important? Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. Q.Can a lock be acquired on a class? Ans: Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. Q.What's new with the stop(), suspend() and resume() methods in JDK 1.2? Ans: The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. Q.Is null a keyword? Ans: The null value is not a keyword. Q.What is the preferred size of a component? Ans: The preferred size of a component is the minimum component size that will allow the component to display normally. Q.What method is used to specify a container's layout? Ans: The setLayout() method is used to specify a container's layout. Q.Which containers use a FlowLayout as their default layout? Ans: The Panel and Applet classes use the FlowLayout as their default layout. Q.What state does a thread enter when it terminates its processing? Ans: When a thread terminates its processing, it enters the dead state. Q.What is the Collections API? Ans: The Collections API is a set of classes and interfaces that support operations on collections of objects. Q.Which characters may be used as the second character of an identifier, but not as the first character of an identifier? Ans: The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects. Q.How does Java handle integer overflows and underflows? Ans: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Q.What is the Vector class? Ans: The Vector class provides the capability to implement a growable array of objects Q.What modifiers may be used with an inner class that is a member of an outer class? Ans: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. Q.What is an Iterator interface? Ans: The Iterator interface is used to step through the elements of a Collection. Q.What is the difference between the >> and >>> operators? Ans: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Q.Which method of the Component class is used to set the position and size of a component? Ans: setBounds() Q.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Ans: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns. Q.What is the difference between yielding and sleeping? Ans: When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. Q.Which java.util classes and interfaces support event handling? Ans: The EventObject class and the EventListener interface support event processing. Q.Is sizeof a keyword? Ans:The sizeof operator is not a keyword Q.What are wrapped classes? Ans: Wrapped classes are classes that allow primitive types to be accessed as objects. Q.Does garbage collection guarantee that a program will not run out of memory? Ans: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection Q.What restrictions are placed on the location of a package statement within a source code file? Ans: A package statement must appear as the first line in a source code file (excluding blank lines and comments). Q.Can an object's finalize() method be invoked while it is reachable? Ans: An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. Q.What is the immediate superclass of the Applet class? Ans: Panel Q.What is the difference between preemptive scheduling and time slicing? Ans: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Q.Name three Component subclasses that support painting. Ans: The Canvas, Frame, Panel, and Applet classes support painting. Q.What value does readLine() return when it has reached the end of a file? Ans: The readLine() method returns null when it has reached the end of a file. Q.What is the immediate superclass of the Dialog class? Ans: Window Q.What is clipping? Ans: Clipping is the process of confining paint operations to a limited area or shape. Q.What is a native method? Ans: A native method is a method that is implemented in a language other than Java. Q.Can a for statement loop indefinitely? Ans: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; Q.What are order of precedence and associativity, and how are they used? Ans: Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left Q.When a thread blocks on I/O, what state does it enter? Ans: A thread enters the waiting state when it blocks on I/O. Q.To what value is a variable of the String type automatically initialized? Ans: The default value of an String type is null. Q.What is the catch or declare rule for method declarations? Ans: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. Q.What is the difference between a MenuItem and a CheckboxMenuItem? Ans: The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. Q.What is a task's priority and how is it used in scheduling? Ans: A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. Q.What class is the top of the AWT event hierarchy? Ans: The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. Q.When a thread is created and started, what is its initial state Ans: A thread is in the ready state after it has been created and started. Q.Can an anonymous class be declared as implementing an interface and extending a class? Ans: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Q.What is the range of the short type? Ans: The range of the short type is -(2^15) to 2^15 - 1. Q.What is the range of the char type? Ans: The range of the char type is 0 to 2^16 - 1. Q.In which package are most of the AWT events that support the event-delegation model defined? Ans: Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. Q.What is the immediate superclass of Menu? Ans: MenuItem Q.What is the purpose of finalization Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.Which class is the immediate superclass of the MenuComponent class. Ans: Object Q.What invokes a thread's run() method? Ans: After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. Q.What is the difference between the Boolean & operator and the && operator? Ans: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Q.Name three subclasses of the Component class. Ans: Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent Q.What is the GregorianCalendar class? Ans: The GregorianCalendar provides support for traditional Western calendars. Q.Which Container method is used to cause a container to be laid out and redisplayed? Ans: validate() Q.What is the purpose of the Runtime class? Ans: The purpose of the Runtime class is to provide access to the Java runtime system. Q.How many times may an object's finalize() method be invoked by the garbage collector? Ans: An object's finalize() method may only be invoked once by the garbage collector. Q.What is the purpose of the finally clause of a try-catch-finally statement? Ans: The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. Q.What is the argument type of a program's main() method? Ans: A program's main() method takes an argument of the String type. Q.Which Java operator is right associative? Ans: The = operator is right associative. Q.What is the Locale class? Ans: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Q.Can a double value be cast to a byte? Ans: Yes, a double value can be cast to a byte. Q.What is the difference between a break statement and a continue statement? Ans: A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. Q.What must a class do to implement an interface? Ans: It must provide all of the methods in the interface and identify the interface in its implements clause. Q.What method is invoked to cause an object to begin executing as a separate thread? Ans: The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. Q.Name two subclasses of the TextComponent class. Ans: TextField and TextArea Q.What is the advantage of the event-delegation model over the earlier event-inheritance model? Ans: The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Q.Which containers may have a MenuBar? Ans: Frame Q.How are commas used in the initialization and iteration parts of a for statement? Ans: Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Q.What is the purpose of the wait(), notify(), and notifyAll() methods? Ans: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. Q.What is an abstract method? Ans: An abstract method is a method whose implementation is deferred to a subclass. Q.How are Java source code files named Ans: A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension. Q.What is the relationship between the Canvas class and the Graphics class? Ans: A Canvas object provides access to a Graphics object via its paint() method. Q.What are the high-level thread states? Ans: The high-level thread states are ready, running, waiting, and dead. Q.What value does read() return when it has reached the end of a file? Ans: The read() method returns -1 when it has reached the end of a file. Q.Can a Byte object be cast to a double value? Ans: No, an object cannot be cast to a primitive value. Q.What is the difference between a static and a non-static inner class? Ans: A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances. Q.What is the difference between the String and StringBuffer classes? Ans: String objects are constants. StringBuffer objects are not. Q.If a variable is declared as private, where may the variable be accessed? Ans: A private variable may only be accessed within the class in which it is declared. Q.What is an object's lock and which object's have locks? Ans: An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. Q.What is the Dictionary class? Ans: The Dictionary class provides the capability to store key-value pairs. Q.How are the elements of a BorderLayout organized? Ans: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. Q.What is the % operator? Ans: It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. Q.When can an object reference be cast to an interface reference? Ans: An object reference be cast to an interface reference when the object implements the referenced interface. Q.What is the difference between a Window and a Frame? Ans: The Frame class extends Window to define a main application window that can have a menu bar. Q.Which class is extended by all other classes? Ans: The Object class is extended by all other classes. Q.Can an object be garbage collected while it is still reachable? Ans: A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. Q.Is the ternary operator written x : y ? z or x ? y : z ? Ans: It is written x ? y : z. Q.What is the difference between the Font and FontMetrics classes? Ans: The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. Q.How is rounding performed under integer division? Ans: The fractional part of the result is truncated. This is known as rounding toward zero. Q.What happens when a thread cannot acquire a lock on an object? Ans: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/ OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.If a class is declared without any access modifiers, where may the class be accessed? Ans: A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. Q.What is the SimpleTimeZone class? Ans: The SimpleTimeZone class provides support for a Gregorian calendar. Q.What is the Map interface? Ans: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. Q.Does a class inherit the constructors of its superclass? Ans: A class does not inherit constructors from any of its superclasses. Q.For which statements does it make sense to use a label? Ans: The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. Q.What is the purpose of the System class? Ans: The purpose of the System class is to provide access to system resources. Q.Which TextComponent method is used to set a TextComponent to the read-only state? Ans: setEditable() Q.How are the elements of a CardLayout organized? Ans: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. Q.Is &&= a valid Java operator? Ans: No, it is not. Q.Name the eight primitive Java types. Ans: The eight primitive types are byte, char, short, int, long, float, double, and boolean. Q.Which class should you use to obtain design information about an object? Ans: The Class class is used to obtain information about an object's design. Q.What is the relationship between clipping and repainting? Ans: When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. Q.Is "abc" a primitive value? Ans: The String literal "abc" is not a primitive value. It is a String object. Q.What is the relationship between an event-listener interface and an event-adapter class? Ans: An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. Q.What restrictions are placed on the values of each case of a switch statement? Ans: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. Q.What modifiers may be used with an interface declaration? Ans: An interface may be declared as public or abstract. Q.Is a class a subclass of itself? Ans: A class is a subclass of itself. Q.What is the highest-level event class of the event-delegation model? Ans: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. Q.What event results from the clicking of a button? Ans: The ActionEvent event is generated as the result of the clicking of a button. Q.How can a GUI component handle its own events? Ans: A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener. Q.What is the difference between a while statement and a do statement? Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. Q.How are the elements of a GridBagLayout organized? Ans: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Q.What advantage do Java's layout managers provide over traditional windowing systems? Ans: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. Q.What is the Collection interface? Ans: The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. Q.What modifiers can be used with a local inner class? Ans: A local inner class may be final or abstract. Q.What is the difference between static and non-static variables? Ans: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. Q.What is the difference between the paint() and repaint() methods? Ans: The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. Q.What is the purpose of the File class? Ans: The File class is used to create objects that provide access to the files and directories of a local file system. Q.Can an exception be rethrown? Ans: Yes, an exception can be rethrown. Q.Which Math method is used to calculate the absolute value of a number? Ans: The abs() method is used to calculate absolute values. Q.How does multithreading take place on a computer with a single CPU? Ans: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. Q.When does the compiler supply a default constructor for a class? Ans: The compiler supplies a default constructor for a class if no other constructors are provided. Q.When is the finally clause of a try-catch-finally statement executed? Ans: The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. Q.Which class is the immediate superclass of the Container class? Ans: Component Q.If a method is declared as protected, where may the method be accessed? Ans: A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. Q.How can the Checkbox class be used to create a radio button? Ans: By associating Checkbox objects with a CheckboxGroup. Q.Which non-Unicode letter characters may be used as the first character of an identifier? Ans: The non-Unicode letter characters $ and _ may appear as the first character of an identifier Q.What restrictions are placed on method overloading? Ans:Two methods may not have the same name and argument list but different return types. Q.What happens when you invoke a thread's interrupt method while it is sleeping or waiting? Ans: When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. Q.What is casting? Ans: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. Q.What is the return type of a program's main() method? Ans: A program's main() method has a void return type. Q.Name four Container classes. Ans: Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane Q.What is the difference between a Choice and a List? Ans: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. Q.What class of exceptions are generated by the Java run-time system? Ans: The Java runtime system generates RuntimeException and Error exceptions. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the difference between a field variable and a local variable? Ans: A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. Q.Under what conditions is an object's finalize() method invoked by the garbage collector? Ans: The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? Ans: A method's throws clause must declare any checked exceptions that are not caught within the body of the method. Q.What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1? Ans: The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. Q.Why are the methods of the Math class static? Ans: So they can be invoked as if they are a mathematical code library. Q.What Checkbox method allows you to tell if a Checkbox is checked? Ans: getState() Q.What state is a thread in when it is executing? Ans: An executing thread is in the running state. Q.What are the legal operands of the instanceof operator? Ans: The left operand is an object reference or null value and the right operand is a class, interface, or array type. Q.How are the elements of a GridLayout organized? Ans: The elements of a GridBad layout are of equal size and are laid out using the squares of a grid. Q.What an I/O filter? Ans: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Q.If an object is garbage collected, can it become reachable again? Ans: Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. Q.What is the Set interface? Ans: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. Q.What classes of exceptions may be thrown by a throw statement? Ans: A throw statement may throw any expression that may be assigned to the Throwable type. Q.What are E and PI? Ans: E is the base of the natural logarithm and PI is mathematical value pi. Q.Are true and false keywords? Ans: The values true and false are not keywords. Q.What is a void return type? Ans: A void return type indicates that a method does not return a value. Q.What is the purpose of the enableEvents() method? Ans: The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods. Q.What is the difference between the File and RandomAccessFile classes? Ans: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. Q.What happens when you add a double value to a String? Ans: The result is a String object. Q.What is your platform's default character encoding? Ans: If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..
Java Interview Questions Java Interview Questions and Answers Q.Which package is always imported by default? Ans: The java.lang package is always imported by default. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.How are this and super used? Ans: this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. Q.What is the purpose of garbage collection? Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. Q.What is a compilation unit? Ans: A compilation unit is a Java source code file. Q.What interface is extended by AWT event listeners? Ans: All AWT event listeners extend the java.util.EventListener interface. Q.What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Q.How can a dead thread be restarted? Ans: A dead thread cannot be restarted. Q.What happens if an exception is not caught? Ans: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. Q.What is a layout manager? Ans: A layout manager is an object that is used to organize components in a container. Q.Which arithmetic operations can result in the throwing of an ArithmeticException? Ans: Integer / and % can result in the throwing of an ArithmeticException. Q.What are three ways in which a thread can enter the waiting state? Ans: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Q.Can an abstract class be final? Ans: An abstract class may not be declared as final. Q.What is the ResourceBundle class? Ans: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. Q.What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement? Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. Q.What is numeric promotion? Ans: Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. Q.What is the difference between a Scrollbar and a ScrollPane? Ans: A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. Q.What is the difference between a public and a non-public class? Ans: A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. Q.To what value is a variable of the boolean type automatically initialized? Ans: The default value of the boolean type is false. Q.Can try statements be nested? Ans: Try statements may be tested. Q.What is the difference between the prefix and postfix forms of the ++ operator? Ans: The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. Q.What is the purpose of a statement block? Ans: A statement block is used to organize a sequence of statements as a single statement group. Q.What is a Java package and how is it used? Ans: A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. Q.What modifiers may be used with a top-level class? Ans: A top-level class may be public, abstract, or final. Q.What are the Object and Class classes used for? Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. Q.How does a try statement determine which catch clause should be used to handle an exception? Ans: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. Q.Can an unreachable object become reachable again? Ans: An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. Q.When is an object subject to garbage collection? Ans: An object is subject to garbage collection when it becomes unreachable to the program in which it is used. Q.What method must be implemented by all threads? Ans: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Q.What methods are used to get and set the text label displayed by a Button object? Ans: getLabel() and setLabel() Q.Which Component subclass is used for drawing and painting? Ans: Canvas Q.What are synchronized methods and synchronized statements? Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q.What are the two basic ways in which classes that can be run as threads may be defined? Ans: A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface. Q.What are the problems faced by Java programmers who don't use layout managers? Ans: Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system. Q.What is the difference between an if statement and a switch statement? Ans: The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects.
Servlets and JSP
Q.What are Servlets? Ans: Servlets are small program which execute on the web server. They run under web server environment exploiting the functionalities of the web server. Q.What are advantages of servlets over CGI? Ans: In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 1000 request then 1000 CGI program is loaded in memory while in servlets there are 1000 thread and only one copy of the servlet class. Q.Can you explain Servlet life cycle? There are three methods which are very important in servlet life cycle i.e. "init”, "service" and "destroy". Server invokes "init ()" method when servlet is first loaded in to the web server memory. Servlet reads HTTP data provided in HTTP request in the "service ()" method. Once initialized servlet remains in memory to process subsequent request. So for every HTTP request "service ()" method of the servlet is called. Finally when server unloads the "servlet ()" from the memory it calls the "destroy" method which can be used to clean up any resource the servlet is consuming. Q.What are the two important API’s in for Servlets? Ans: Two important packages are required to build servlet "javax.servlet" and "javax.servlet.http". They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat. Q.Can you explain in detail “javax.servlet” package? Ans: javax.servlet package has interfaces and classes which define a framework in which servlets can operate. Let’s first make a walk through of all the interfaces and methods and its description. Interfaces in javax.servlet Servlet Interface This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :- void destroy( ):- Executed when servlet is unloaded from the web server memory. ServletConfig getServletConfig() :- Returns back a ServletConfig object that contains initialization data. String getServletInfo( ):- Returns a string describing the servlet. init method :- Called for first time when the servlet is initialized by the web server. void service() method :- Called to process a request from a client. ServletConfig Interface This interface is implemented by the servlet container. Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface:- ServletContext getServletContext():- Gives the servlet context. String getInitParameter(String param):- Returns the value of the initialization parameter named param. Enumeration getInitParameterNames() :- Returns an enumeration of all initialization parameter names. String getServletName( ) :- Returns the name of the invoking servlet. Q.What’s the use of ServletContext? Ans: ServletContext Interface It gives information about the environment. It represents a Servlet's view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects. Following are the methods defined in ServletContext Interface Object getAttribute(String attr) :- Returns the value of the server attribute named attr. String getMimeType(String file) :- Gives MIME type for a file. String getRealPath(String vpath) :- Gives the actual physical path for a virtual path. String getServerInfo( ) :- You can get the server information using this function. void log(String s) :- Used to write to server log. void log(String s, Throwable e) :- Writes s and the stack trace for e to the servlet log. void setAttribute(String attr, Object val) :- Sets the attribute specified by attr to the value passed in val. ServletRequest Interface The ServletRequest interface is implemented by the servlet container. It gives data regarding client request. Following are the methods defined in ServletRequest Interface Object getAttribute(String attr) :- Returns the value of the attribute named attr. String getCharacterEncoding( ) :- Returns the character encoding of the request. int getContentLength( ) :- Gives the size of the request. If no size is there then it returns -1. String getContentType( ) :- Returns the type of the request. A null value is returned if the type cannot be determined. ServletInputStream getInputStream( ) :- Returns a ServletInputStream that can be used to read binary data from the request. String getParameter(String pname) :- Returns the value of the parameter named pname. Enumeration getParameterNames( ) :- Returns an enumeration of the parameter names for this request. String getParameterValues(String name) :- Returns an array containing values associated with the parameter specified by name. String getProtocol( ) :- Gives back protocol description. BufferedReader getReader( ) :- Returns a buffered reader that can be used to read text from the request. String getRemoteAddr() :-Returns client IP address. String getRemoteHost() :- Returns client host name. String getScheme( ) :- Return what’s the transmission protocol HTTP , FTP etc. String getServerName() :- Returns the name of the server. int getServerPort() :- Returns the port number. ServletResponse Interface The ServletResponse interface is implemented by the servlet containerUsed to give response back to the client. Following are the methods defined in ServletResponse Interface String getCharacterEncoding() :- Returns back character encoding. ServletOutputStream getOutputStream() :- Returns a ServletOutputStream that can be used to write binary data to the response. PrintWriter getWriter() :- Returns a PrintWriter that can be used to write character data to the response. void setContentLength(int size) :- Sets the content length for the response to size. void setContentType(String type) :- Sets the content type for the response to type. GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. void log(String s) void log(String s, Throwable e) Here, s is the string to be appended to the log, and e is an exception that occurred. Now let’s revise through different classes. ServletInputStream Class This class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. int readLine(byte buffer, int offset, int size) :- Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered. ServletOutputStream Class The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the “print()” and “println()” methods, which output data to the stream. Servlet Exception Classes javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is unavailableException, which extends ServletException. It indicates that a servlet is unavailable. Q.What's the difference between GenericServlet and HttpServlet? Ans: HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet. Q.Can you explain in detail javax.servlet.http package? Ans: The javax.servlet.http package inherits from “javax.servlet” package and supplies HTTP protocol specific functionalities for JAVA developers. If you are aiming at developing HTTP application you will find “javax.servlet.HTTP” more comfortable than “javax.servlet”. So let’s revisit through the interfaces and methods HttpServletRequest Interface Below are the lists of methods in HttpServletRequest Interface:- String getAuthType( ):- Returns the type of authentication. Cookie getCookies( ) :- Returns the collection of cookies for the request. long getDateHeader(String field) :- Returns the value of the date header field named field. String getHeader(String field) :- Returns the value of the header field named field. Enumeration getHeaderNames( ) :- Returns an enumeration of the header names. int getIntHeader(String field) :- Returns the int equivalent of the header field named field. String getMethod( ) :- What type of method does this request have POST , GET etc. String getPathInfo( ) :- Returns any path information that is located after the servlet path and before a query string of the URL. String getPathTranslated( ) :- Returns any path information that is located after the servlet path and before a query string of the URL after translating it to a real path. String getQueryString( ) :- Returns any query string in the URL. String getRemoteUser( ) :- Returns the name of the user who issued this request. String getRequestedSessionId( ) :- Returns the ID of the session. String getRequestURI( ) :- Returns the URI. StringBuffer getRequestURL( ) :- Returns the URL. String getServletPath( ) :- Returns that part of the URL that identifies the servlet. HttpSession getSession( ) :- Returns the session for this request. If a session does not exist, one is created and then returned. HttpSession getSession(boolean new) :- If new is true and no session exists, creates and returns a session for this request. Otherwise, returns the existing session for this request. This section is explained in more detail in further questions. boolean isRequestedSessionIdFromCookie( ) :- Returns true if the cookie has the session id. boolean isRequestedSessionIdFromURL( ) :- Gives true if the URL has session id. boolean isRequestedSessionIdValid( ) :- Return true if the session is valid in the current context. HttpServletResponse Interface The HttpServletResponse interface is implemented by the servlet container. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. Below are the methods and functions for the interface void addCookie(Cookie cookie) :-Adds cookie to the HTTP response. String encodeURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs generated by a servlet should be processed by this method. String encodeRedirectURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs passed to sendRedirect( ) should be processed by this method. void sendError(int c) :- Sends the error code c to the client. void sendError(int c, String s) :- Sends the error code c and message s to the client. void sendRedirect(String url) :- Redirects the client to url. void setDateHeader(String field, long msec) :- Adds field to the header with date value equal to msec (milliseconds since midnight, January 1, 1970, GMT). void setHeader(String field, String value) :- Adds field to the header with value equal to value. void setIntHeader(String field, int value) :- Adds field to the header with value equal to value. void setStatus(int code) :- Sets the status code for this response to code. HttpSession Interface HTTP protocol is a stateless protocol and this interface enables to maintain sessions between requests. Object getAttribute(String attr) :- Returns the value associated with the name passed in attr. Returns null if attr is not found. Enumeration getAttributeNames( ) :- Returns an enumeration of the attribute names associated with the session. long getCreationTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when this session was created. String getId( ) :- Returns the session ID. long getLastAccessedTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the client last made a request for this session. void invalidate() :- Invalidates this session and removes it from the context. boolean isNew( ) :- Returns true if the server created the session and it has not yet been accessed by the client. void removeAttribute(String attr) :- Removes the attribute specified by attr from the session. void setAttribute(String attr, Object val) :- Associates the value passed in val with the attribute name passed in attr. HttpSessionBindingListener The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound are void valueBound(HttpSessionBindingEvent e) voidvalueUnbound(HttpSessionBindingEvent e) Here, e is the event object that describes the binding. Cookie Class The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user's name, address, and other information. The user does not need to enter this data each time he or she visits the store. A servlet can write a cookie to a user's machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. The names and values of cookies are stored on the user's machine. Some of the information that is saved for each cookie includes name of the cookie, value of the cookie, expiration date of the cookie and domain/path of the cookie. The expiration date determines when this cookie is deleted from the user's machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user's machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here: Cookie(String name, String value) :- Here, the name and value of the cookie are supplied as arguments to the constructor. The methods of the Cookie class are Object clone( ) :- Returns a copy of this object. String getComment( ) :- Returns the comment. String getDomain( ) :- Returns the domain. int getMaxAge( ) :- Returns the maximum age (in seconds). String getName( ) :- Returns the name. String getPath( ) :- Returns the path. boolean getSecure( ) :- Returns true if the cookie is secure. Otherwise, returns false. String getValue( ) :- Returns the value. int getVersion( ) :- Returns the version. void setComment(String c) :- Sets the comment to c. void setDomain(String d) :- Sets the domain to d. void setMaxAge(int secs) :- Sets the maximum age of the cookie to secs. This is the number of seconds after which the cookie is deleted. void setPath(String p) :- Sets the path to p. void setSecure(boolean secure) :- Sets the security flag to secure. void setValue(String v) :- Sets the value to v. void setVersion(int v) :- Sets the version to v. HttpServlet Class The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP DELETE. void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP GET. void doOptions(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP OPTIONS. void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP POST. void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP PUT. void doTrace(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP TRACE. long getLastModified(HttpServletRequest req) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the requested resource was last modified. void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Called by the server when an HTTP request arrives for this servlet. The arguments provide access to the HTTP request and response, respectively. HttpSessionEvent Class HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a change occurs to the session. HttpSession getSession( ) It returns the session in which the event occurred. The HttpSessionBindingEvent Class The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val) Here, session is the source of the event, and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in Val. String getName( ) :- The getName( ) method obtains the name that is being bound or unbound. Its constructor is shown here: HttpSession getSession( ) :- The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound: Object getValue( ) :- The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is shown here: Q.What’s the architecture of a Servlet package? Ans: In the previous questions we saw all the servlet packages. But the basic architecture of the servlet packages is as shown below.
At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like “Get” and “Post”. Finally comes our custom servlet which inherits from HTTP Servlet. Q.Why is HTTP protocol called as a stateless protocol? Ans: A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it.
Above is a pictorial presentation of how a stateless protocol operates. User first sends “request1” and server responds with “response1”. When the same user comes back with “request2” server treats this as new user and has no idea that it’s the same user who has come with the request. In short every request is a new request for the HTTP protocol so it’s called as a stateless protocol. Q.What are the different ways we can maintain state between requests? Ans: Following are the different ways of maintaining state’s between stateless requests:- √ URL rewriting √ Cookies √ Hidden fields √ Sessions Q.What is URL rewriting? Ans: It’s based on the concept of attaching a unique ID (which is generated by the server) in the URL of response from the server. So the server attaches this unique ID in each URL. When the client sends a requests it sends back this ID with the request also which helps the server to identify the client uniquely. Below is a snippet which is extracted from the code which is provided in the CD.
In this sample we have generated a unique ID using the random class of java. This unique ID is then sent in the query string (see step 3 of the above snippet) back to the client. When the client comes back to the server the server first gets the token value from the query string and thus identifying the client uniquely. Q.What’s the difference between getSession(true) and getSession(false) ? Ans: Session's can be considered as a series of related interactions between client and the server that take place over a period of time. Because HTTP is a stateless protocol these series of interactions are difficult to track. That’s where we can use HttpSession object to save in between of these interactions so that server can co-relate between interactions between clients.
Above is the code snippet which displays session data. Step1 returns an HttpSession object from the request object. “true” parameter in the “getsession” function ensures that we get a session object if there is no current session object in request which ensures that we never get a null session object. In Step 2 we are using the “getattribute” function to return the session value. In step 3 we are setting the session value with “Name” key. Q.Which are the different ways you can communicate between servlets? Ans: Below are the different ways of communicating between servlets:-
Related

Advanced JAVA Online Training
Get the essential concepts of Advanced java programming taught by live industry experts and become a master in application development by enhancing your knowledge on different frameworks like Struts,

Angular JS Online Training
Get first-hand experience creating applications from scratch to become an expert in creating apps for the Angular JS platform from live professionals with real-world use cases at the Angular JS Online

C ++ Online Training
Get hands -on experience on problem solving from basic to complex level taugh by real-time industry experts with live usecases and become a master in C++ programming through C++ Online Training Course

C Language Online Training
Become an efficient programmer in developing various kinds of applications in solving complex problems from basic to the advanced level with practical use-cases at the C Language online training cours

Core JAVA Online Training
Get the basics of Java programming from the roots of programming language through the parameters required to build a java program taught by live experts with practical use cases at Core java online tr

DotNet Online Training
Get hands-on experience of application development from basic to the advanced level on the Dot Net framework by live experts with practical use cases through Kits DotNet Online Training Course.

GO Language Online Training
Become a master in application development from basics to the advanced concepts and acquire practical knowledge o solving the complex problems taught by live experts with practical use cases at GO Lan

JAVA Online Training
Get from the roots to the advanced level of programming on Java taught by live experts and acquire hands-on experience of java programing taught by live experts with practical use cases and become a m

PHP Online Training
Make your dream come true as a certified PHP professional and get practical knowledge of developing the application by live experts with live usecases at PHP Online Training.

Python Online Training
Enroll in the Python Online Training Course provided by KITS Online Training to turn your ambition of becoming a certified Python professional into a reality.

R programming Online Training
Get practical knowledge on R programming from beginner to the advanced level taught by industry professionals through R Programming Online Training Course

Explain the role of Flask in Python Programming?
Web apps were developed to generate the content based on retrieved data that changes based on the user interaction with the website. The server side here is responsible for querying, retrieving as well as updating the data. This makes the web applications to be slower and more complicated to deploy in comparison with simple small websites A typical web application ecosystem consists of two primary coding environments namely client as well as server-side scripting. In the Client-side system, the code executed on the user browser is visible to anyone who has the access to the system in the generation of the first results. On the other hand, server-side scripting run on the backend of the webserver. This enables developers to design, build maintains and host web applications over the internet. Today in the article, we are going to discuss the flask() application in python programming. Before going to know about flask(), let us start our discussion with the web application. A web application framework is a collection of modules and libraries that allows helps developers to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is an API that allows programmers to build up web applications. The Flask framework is more explicit than the Django framework and is easier to learn because it has less code to implement a simple web-based application. Flask is based on Web Server Gateway Interface (WSGI) tool kit and the Jinja2 template engine. Are you new to python programming, if so visit What is Python programming? To understand the flask, we initially need to understand the following terms: WGSI: WSGI (Web Server Gateway Interface) has been adopted as a standard for Python web application development. WSGI is a specification for the universal interface between web servers as well as web applications. Werkzeug: It is a WSGI toolkit that implements request, response object, and other utility functions. This enables building the framework of it. This Flask framework uses Werkzeug as one of its bases. Jinja2: This is the most popular python templating engine. This web templating system combines the template with certain data sources to render the dynamic web pages. Getting started with Flask: What is Flask? Flask is a framework that provides libraries to build lightweight applications in python. Many developers consider flask as a micro framework. This framework was developed by Armin Ronacher who leads an international group of Python enthusiasts(. Python 2.6 (or) higher requires the installation of the flask. The programmers can start importing the Flask package on any Python IDE. You can check out the installation of Flask with the following code: #an object of the WSGI application from flask import Flask app = Flask(__name__) # Flask constructor # A decorator used to tell the application # which URL is associated function @app.route('/') def hello(): return 'HELLO' if __name__=='__main__': app.run() Do you want to get a practical explanation for this? If Yes, visit Python Online Training In the above code, the ‘/’ URL bounds with the hello() function. If the webserver homepage is opened in a browser, the output function will be rendered accordingly. Here the flask() is started by calling the run() function. Here the method should be restarted manually for any change in the code. To solve this scenario, debug support is enabled to track any error. app.debug = True app.run() app.run(debug = True) Routing: The web frameworks provide a routing technique, to remember the URL’s easily. It is useful to access the web page directly, without navigating from the home page. In python programming routing is done through the following route() decorator, a bind a URL to the function # decorator to route URL def hello_world(): @app.route(‘/hello’) # binding to the function of route return ‘hello world’ If the user visits http://localhost:5000/hello URL the output of the hello world() function will be rendered in the browser. Besides this, the add_url_rule function of the object is used to bind the URL with the function. def hello_world(): return ‘hello world’ app.add_url_rule(‘/’, ‘hello’, hello_world) Flask Variables: The flask variables were responsible to dynamically build URLs by adding the variable parts to the rule parameter. The variable part here is marked as a keyword argument as shown in the example below: from flask import Flask app = Flask(__name__) # routing the decorator function hello_name @app.route('/hello/') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True) Save the file with the .py extension, and run from the power shell. Now navigate to http://localhost:5000/hello/kitsonlinetrainings. Output: Hello kitsonlinetrainings In the above example, the parameter of the route() decorator contains the variable part attached to the URL ‘/hello’ as an argument. Hence if the user navigates to http://localhost:5000/hello/kitsonlinetrainings , ‘kitsonlinetrainings’ will be passed to the hello() function as an argument. In addition to the default string variable part, other data types like int, float, and path were also used. The Flask URL rules were based on the Werkzeugs routing module. It ensures that the URLs formed are unique and precedents presents here were laid by apache. from flask import Flask app = Flask(__name__) @app.route('/blog/') def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/') def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run() # says the URL is http://localhost:5000/blog/555 Flask Advantages: Utilization of flask framework in python programming has the following advantages: It is easy to use Provision of a built-in server as well as the debugger Provision for integrated unit test support Provision for RESTful request dispatching Contains the best documentation for various scenarios Purely based on Unicode and WGSI 1.0 Contains the best documentation to explore various scenarios Conclusion: In this article, we tried to understand the importance and the application of the flask() in python programming. You can get practical knowledge on the flask() from real-time working professionals through the Python Online Course. In the upcoming post of this blog, I'll be introducing the new framework. Meanwhile, you can also check out the Python Interview Questions written by Industry professionals to get placed in MNC.
Continue reading
What is Garbage Collection? How does it work?
Garbage collection is the process of reclaiming unused memory through the destruction of unused objects. In the languages like C and C++, the programmer is responsible for the creation and destruction of objects. In some cases, the programmer may forget to destroy the useless memory and the memory allocated to them is not released. The used memory of the system keeps on growing, and there might be no memory left to allocate. In such cases, the applications suffer from memory leaks. After a certain point, sufficient memory may not be available for the creation of new objects. In such cases, the entire program gets terminated abnormally due to out-of-memory errors. You can use methods like free() in C and delete in C++ to perform garbage collection. In Java, garbage collection happens automatically during the life cycle of the program. This eliminates the need to deallocate memory and therefore avoid memory leaks. Here you can use methods like free() in C Language and delete() in C++ to perform the garbage collection. In Java, garbage collection happens during the lifecycle of the program. This eliminates the need to deallocates the memory as well as the memory leaks. Are you new to the concept of JAVA, If so, check out What is JAVA? Garbage Collector in JAVA: The process of automatic memory allocation by java programs is known as Java Garbage Collection. JAVA program compiles into bytecode, that can run the JAVA Virtual Machine (JVM). When the JAVA program runs on JVM, objects were created on the heap, which creates a portion of memory to the program. Over the lifetime of the application, new objects were created and released. Here heap consists of two types of objects: Live – Objects are being used and referenced from somewhere else Dead – These objects were no longer used (or) reference from anywhere Garbage Collector Silent Features: It is controlled by a thread known as Garbage Collector JAVA provides two methods gc() and Runtime.gc() that sends a request to JVM for garbage collection. JAVA programmers are free from memory management. Programmers cannot force the garbage collector to collect the garbage it depends on JVM When the garbage collector removes the object from the memory, initially the garbage collector thread () calls the finalize () of the object and then remove it. Object Allocation: When an object allocates, the Jrocket JVM checks the size of the object. It distinguishes between small and large objects. Here the small, as well as the large size, depends on heap size, JVM Version, Garbage collection strategy, and the platform used. The actual size of the object varies from 2KB to 128KB. The small objects here were stored in a Thread Local Area (TLA) which is a free chunk of the heap. If the thread is using the young space, it is directly stored in the old space. Here the large object requires more synchronization between the threads. When is an object eligible for Garbage Collection? An object becomes eligible only if it is not used by any program (or) thread (or) any static references. If two objects having a reference to each other and do not have any live reference, then the objects are collected by the garbage collector. There are some other cases where an object is eligible for garbage collection, If the reference of the object is set to null An object is created inside the block and the scope goes out of the scope. How does JAVA Garbage Collector in JAVA work? JVM Controls JAVA Garbage collector. JVM decides when to perform the Garbage collection. You can also request JVM to run the garbage collector. But there is no guarantee that JVM will compile in all conditions. JVM runs the garbage collector if it senses that the memory is running low. When the JAVA program requests the garbage collection, JVM usually accepts it in short order. But it doesn’t make sure that the request has been accepted. Do you want to know the practical working of JAVA Garbage Collector? If yes, visit JAVA Online Training Which method is used for garbage collection? In JAVA, every program has more than one thread and every thread has its execution stack. The main() method contains a thread that is responsible for running a JAVA program. If no live thread is accessing the garbage collector, then-current the thread will access the garbage collector. Once accessed, the garbage collector considers the object is eligible for deletion. If the program has a reference variable that references the object, that reference variable available to the live thread is known as reachable. Usually, the garbage collection happens to the memory when the object is no longer needed. Even though JAVA programming contains many live objects, garbage collection does not guarantee that there is enough memory. Java compiler usually maintains the enough memory Types of Garbage Collection: Serial GC: It uses the mark and sweeps approach for the young and old generations. i.e minor and major Garbage Collections Parallel GC: It is similar to the serial GC except, it spawns N threads for young generation garbage collection. Parallel Old GC: It uses multiple threads in both generations and the rest is similar to the parallel GC G1 Garbage collector: It is introduced in JAVA 7. Its main objective is to replace the CMS collector. It’s a parallel, concurrent well as the CMS collector. Here, there is no young and the old generation space. Here the heap is divided into different equal-sized heaps which collects the regions with lesser live data. Concurrent Mask Sweep Collector: It does the garbage collection for the old generation. Here through XX: ParallelCMSThreads = JVM option you can limit the number of threads in the CMS collector. Some people also call it a concurrent Low Pause Collector. Mark and Sweep Algorithm: JRockit uses the mark and sweeps algorithm for garbage collection. It contains two phases namely the mark phase as well as the sweep Phase. Mark Phase: This phase makes the objects accessible from various sources like native handles, threads and other GC root sources and marks them as alive. Every object tree has more than one root object where the GC root is always reachable. So any object that has a garbage collection at its root identifies and marks all the objects that are in use and the rest were considered as garbage. Sweep Phase: This phase finds the gaps between the objects by reversing the heap. The free list present here records the gaps and is made available for new object allocation. JVM perform the garbage collection through this process and has the following pros and cons: Pros: It's an infinite loop It’s a recurrent process No additional overhead during the algorithm execution Cons: Cannot run the normal program parallelly Runs multiple times on a program We cannot find a process with no cons. Every program has an equal number of pros and cons. Keeping the cons aside Garbage collection is the best process in programming languages like JAVA. But this concept is very good at memory deallocation. You can grab practical knowledge on garbage collection from Real-time professionals through JAVA Online Course. Additionally, you can also check out the JAVA Interview Questions prepared by real-time professionals to get placed in MNC’s
Continue reading
What is Java
Java is an evergreen programming language for developing various kinds of the application over the past decade. This programming language suits best for developing the various kinds of applications across the globe. The importance of this programming language has not decreased even though many programming languages arose after that. Have you ever thought of why this programming language has gained importance? Do you know why other programming languages could not replace this? Read the complete article to get the answer to all these questions. Let us start our discussion with java definition Java is a programming language and computing platform released by the sun microsystem in 1995. It is object-oriented programming similar to C++. This language is free to access and can run on all platforms. We can say this programming language as : a)concurrent: It can execute multiple statements instead of executing sequentially b)Class-based: It executes the statements in different classes through objects. c)Independent: It is an independent programming language that follows the logic of “ Write once Run Anywhere”. i.e the compiled code is responsible to run on all platforms that support java. History of Java: Java was originally developed by James gosling with his colleagues at Sun MicroSystems during the early 1990s. This programming language is similar to C and C++. The name java was later selected after enough brainstorming and is based on the name of the expression bean. Java 1.0 is the first version released in the year 1995. Time being oracle owned this sun microsystem. From that time, this programming language is releasing various versions by adding new features to the latest versions. As on March 2020, its latest version is java 14 You people can get the latest version Java download online. What is the Java platform? Java platform is a software platform that is different from traditional platforms like Windows, Mac, Linux, and Solaris. This platform runs on the top of the hardware of the latter platforms. These platforms go through virtual machines that convert the byte into native code and thus make the program to run anywhere. Hence, the user does not require specific machine compilers for the java code to run. This programming language is different from its platform. Moreover, this programming language is responsible to build java applications. The code written in this programming language is developed and run with the help of an existing collection of tools and programs collectively known as the JAVA platform. This programming platform consists of JDK, JVM, and JRE. The four platforms of this programming language are: a)Standard Edition(SE) b)Enterprise Edition(EE) c)J Micro Edition(ME) d)Java FX Among these, SE Platforms were capable of building stand alone applications, World wide web (Internet) uses JEE. And Micro Edition(ME) suits well for small applications Get the practical exposure of these platforms from live experts at Java Online Training Components of Java: Java Virtual Machine (JVM): JVM is an abstract machine. It is a specification that provides the run-time environment in which byte code can be executed. It usually follows three notations: Specification: It is a document that described the implementation of JVM. It is provided by the sun and other companies Implementation: It is a program that meets the requirements of JVM specification. Run time Instance: An instance of JVM is created, whenever you write command on the command prompt and run the class. Java Run time Environment(JRE): JRE refers to the Java Run time Environment in which byte code executes. It implements JVM and provided all the class libraries and other support files that JVM uses at run time. Hence JRE is a software package that contains all the necessary libraries to run the program. It is an implementation of JVM that physically exists. Java Development Kit: It is a tool that is responsible to compile, document, and package the software programs. Here the JDK completely uses JRE which contains tools for programmers. Besides, this Development Kit is available free of charge. This JDK includes JRE, interpreter/loader, compiler, an archiver, document generators, and other tools to develop an application. Hence in some cases, it also is known as JRE+ and other tools. Features of Java: Simple: This programming language is simple and easy to learn when compared to other programming languages. Because this programming language makes the application development much easier by removing all the complexities such as pointers, operator overloading in C++, and so on. Portable: This programming language is a platform-independent language. Hence application written on one platform can be easily ported to the other platform. Object-Oriented: Everything in this programming language is considered to be object-oriented. This feature enables the same state, behavior when operations were performed using these objects. Secured: All the code is converted into byte code after compilation that is not readable by a human. Moreover, as mentioned above, this programming language does not use any explicit pointer and runs the programs inside the sandbox to prevent illegal activities from untrusted sources. Hence it enables to develop virus-free tamper-free applications/ systems Dynamic: This programming language is capable of adopting the evolving environment that supports dynamic memory allocation. Hence by we can reduce the memory wastage and can increase the application performance. Distributed: This programming language allows users to create distributed applications. Using Remote Method Invocation(RMI), a program is capable of invoking a method of another program across the network. Moreover, it allows the program to access the files from any machine using the internet. Hence likewise, many excellent features make to stand on the top of the programming languages. Get all features with live use cases at java online course. So due to these excellent features, this programming suits best in different areas like mobile, Desktop GUI, Enterprise. Scientific, gaming applications. Besides it also opted as the programming languages in big data, business, distributed, and cloud-based applications. Hence with this, I hope you people have got an overview of this programming language. In my next articles of the blog, I'll be sharing the details of this programming application in various areas. Meanwhile, have a glance at out java interview questions and get placed in your dream company
Continue reading
What is Python programming?
Python is the buzz that has created today in the IT world. This buzz has changed the way of application development in the IT industry. Today many people were curious to learn python. And you are one among them to know what it is? How it is utilized in the IT industry. Read the complete article to get rid of your curiosity. Before getting deep into the topic, let us walkthrough What is Python? Python is a high-level interpreted programming language, This programming language has an easy syntax and dynamic semantics. This programming language is much easier than many other programming languages in the IT industry. With the arrival of this programming language, application development becomes easy to use. Moreover, developers can develop a beautiful application with less code within a short period. Moreover, its high-level in-built data structures, combined with dynamic typing and dynamic binding make it interactive for rapid application development. Hence this easy to learn syntax increases readability and reduces the cost of programming maintenance. Besides, this programming language support modules and packages that encourage the programming modularity and code use. Since there is no compilation step, the edit-debug step is incredibly fast. Here the debugger is written in the python itself to testify the python's introspective power. Why python? Do you know why this programming language has gained more importance when compared to other programming languages? This is because of the following reasons: a)High–level: This programming language derives the components from the natural programming language that humans communicate with each other. Thus this programming language makes it easier for anyone to try and relate what exactly happening. Hence this gets rid of reading the tons of machine code. b)Interpreted: This programming language code is interpreted line by line. Hence this feature makes the application development easier and efficient. Moreover, the programming cost is also very less when compared to the other programming languages c)Easy Syntax: The syntax of this programming language is very easy when compared to other programming languages. For instance, this programming language makes use of indentations instead of braces. Hence this makes it easier for the user to understand what blocks of code come under the function. Hence the code is well distributed to read, it makes it easy for anyone to read it. d)Dynamic Semantics: Unlike the other programming language, this programming language does not require to initialize the variable. The interpreter will automatically take care of all those initialization dynamically Likewise, there are many other reasons to opt for this programming language. You people can acquire hands-on experience in this language at Python Online Training Python Features: The major utilization of this programming language is due to its excellent features as shown below: Simplicity: This programming language is known for its simplicity. With this programming language, you can solve the complex problems with fewer lines of code Open-Source: This programming language is free for anyone to use. Hence this programming language allows the user to modify the source code according to the needs without any interruptions Portability: The code developed in one platform can be able to run in other platforms without any changes. And this feature is very helpful when a couple of people working in a project Versatile: This programming language allows the user to embedded the code from other programming languages. This makes the programming language more versatile and flexible Interpretation: Since the python programming is interpreted line-by-line debugging is more easy and powerful. Hence this makes the application run faster and efficient Library support: Python programming language supports a huge number of libraries to deliver the inbuilt code to its users. Hence with this huge library support, developers can concentrate more on application logic rather than the programming logic OOPs: This is one of the best features of this programming environment. With this feature, you can replicate the real-world scenarios to your code and also provide security. Hence the developer can develop the best application with this. Hence, likewise, there are many excellent features of python programming in the real world to develop various kinds of applications. How Python is useful in application development? This programming language is useful in many ways in application development. Some of them were as follows : a) Creating the web application with python frameworks such as Flask and Django b) Creates workflows for the software that you were working on c) To modify the files and data stored in databases Likewise, there is much application of this programming language in the IT industry. Moreover, today companies were paying the best salaries to these professionals. Besides, this programming language suits best in problem-solving. Hence once you master this platform, you can join in any one of the following areas: a)Data Scientist: A Data Scientist is a person who cracks the complex problems related to math, statistics, and so on. Using a programming language, Data Scientist does solve the complex problems logically as per the client requirements b)software Engineer: These people design, develop, test, and maintain the software applications according to the client requirements c)Web Developer: As a web developer, you people can utilize this programming language to serve the users using the client-server model. With python, we can develop different applications like information sharing, social networking platforms, entertainment, and so on. Likewise, there are many areas that python programming can be applied. Now, we will also discuss the opposite side of this Where python cannot be applied? Since python is a high-level programming language, this does not suites well in system-level programming. Some of them were device drivers, Os Kernel, and so on. Besides, this platform also not suits well in calling the cross-platform standalone applications. But you can build the standalone python application for Windows, Mac, Linux and so in a smart way. And it also does not suit well for application where speed is the most important factor. Hence like this, there are many more features that were available in this programming. You people can learn python and acquire hands-on experience on these features by live experts online at Python Online Course. I hope you people have got enough idea regarding python basics. In my next article, I'll be discussing you with the python programming examples with the live use cases as per the market. Also, check our Python Interview Questions and get selected in a reputed firm and make your dream comes true
Continue reading
What is Python used for?
Python has become the most popular language in recent years. This programming language has become more popular due to its wide range of applications. We can apply python programming from machine learning to build websites and software testing, self-driving cars. It can be used by both developers and non-developers alike. Besides this, python can also be applied in Data Science, Software Development and application, automation, and many more. Are you looking to know the application of python programming in detail? If yes, you are at the right place. Read the article till the end to know python applications. Before going to the actual discussion, let us have a quick discussion, What is python? Python is an objected-oriented interpreted programming language, used to build websites, software, automate the task and conduct data analysis. This general-purpose programming language is used to create a variety of different programs and is not specialized for any specific problems. Even non-programmers like accountants and scientists can adapt to a variety of tasks like organizing and finances. You can get more information on what is python on this website. Python programming is used in the following areas: Python Applications: Data Analysis and Machine Learning: Python has become a staple in Data Science, allowing the data analyst and other professionals, to use the language to conduct complex statistical calculations, creation of data visualizations, building machine learning algorithms, Data Analysis, and other Data related tasks. Through Python, we can create different data visualizations like Line and Bar graphs, Histograms, Pie charts, and 3D plots. This programming language has several libraries that enable coders to write programs for data analysis and machine learning quickly. Data Visualization: Data Visualization plays a major role in the IT industry. Python is an open-source and flexible programming language that provides a variety of graphic libraries with all kinds of features. Whether it is a simple graphical representation (or) an interactive plot, you can find the library to match your needs. Python Programming language has vast possibilities that allow you to transform the data into meaningful insights. Web Development: Python is often used to develop the backend of the website (or) application. Python plays a major role in web development like sending the data to and from the servers, data processing and communicating the data with Databases, URL routing to ensure security. This programming language has some frameworks like Django and Flask for Web Development. Programming Application: Developers can develop a variety of applications using python. This general-purpose programming language can be used to read and create file directories, Create GUI, API, and many more. Irrespective of the application type i.e blockchain application, audio, and video apps (or) machine learning applications you can build them all with python. Automation (or ) scripting: There might be some situations where you require the execution of repeated tasks again and again which is a time taking process. So to overcome this process, automation is done. Writing the code to build the automated scripts is called Scripts. In this programming world, automation can be used to check for errors, across multiple files. Convert files, execute the simple and remove the duplicates. Do you want to know about automation in python programming? If yes, visit Python Online Training Software Testing and Prototyping: In Software Development, python can aid tasks like build control, bug tracking, and testing. With python, software developers can automate the testing for new products (or)features. Green and Requestium were some of the tools used for software testing. Game Development : Besides Software Development, python can also be used for Game development. With the Python programming language, it is possible to develop simple games. Besides, we can quickly create a prototype where certain functions like dialogue tree creation are also available in python. Language Development : The simple and elegant use of the python programming language has inspired the creation of new programming languages. Languages such a Go, COBRA, Coffe Script were similar to that of python. Many developers suggest that python is a powerful gateway language, where the understanding of python's programming language helps you enhance your programming skills and also lets you master multiple areas very easily. Finance: Rather than IT, python can also be used in the field of Finance. The concept of python programming can be applied in Quantitative and Qualitative Analysis. Python Programming Language is good at determining the price trends and predictions as well as automating the workflows across the different data sources. This python is an ideal tool for SEO: SEO is another field where the application of python programming exists. Python helps in categorizing keywords (or) multiple pages. SEO works using Natural Language Processing (NLP) and python suits best in NLP and helps you in understanding how people search and how search engines return results. Design: This programming language can also be used to develop graphic design applications. This language is used across a range of 2D imaging software such as Paint Shop Pro and Gimp. This programming language is even used in 3D Animation Software such as lightwave, Blender, and Cinema 4D. Calculators: You can build a Graphical User Interface (GUI) calculator using python. Using Python programming, you can calculate complex calculations. Operating Systems: Python is so robust that can be used to build the entire operating system. The Object-oriented feature of this programming language makes large projects easier to manage. And speaking of the operating systems, python is compactable with all the operating systems. i.e. you can build the native applications for both Windows and Mac Operating Systems. These are some of the applications to name it. But in real-time there are multiple applications of python programming. By reaching the end of this article, I hope you people have got enough information on python programming. You can get a more practical explanation of python programming by Real-Time industry professionals through Python Online Course. In the upcoming posting of this blog, I'll be sharing the details of the execution of python programming in different environments. Meanwhile, have a glance at our Python Interview Questions
Continue reading
What's New in JAVA 17
This blog post is an example to show you JAVA is a Ever Green Programming language. Even though many programming languages arose after this language, this programming language stood on the top of all other programming languages. Java programming language continuous to be a choice for developers as well as the enterprises to build a high scalable, superior and secure software application across the globe. Since 1996, it has releasing the new features by adding the new features to the programming language. Once you observe the periodic updates, Oracle continues to deliver the JAVA updates for every six months. Last year Oracle and JDK Community has celebrated the JAVA 25th birthday, According to the IDC reports JAVA turns 25 where one million developers representing 69% of the full time developers uses JAVA. This platform has release JAVA 16 on March 2021 and it is expecting to release the next version i.e Java 17 in September 2021. In this post im going to share you the exciting features of JAVA 17. Will JAVA17 will be LTS? LTS refers to the Long Term Support is product Life Cycle Management Policy in where a stable release of Computer Software is maintained for a longer period of time than the Standard Version. The term LTS is used for the Open Source Software, where the versions is supported for years (or) months than the Standard Edition. And JAVA 17 is considered as the next LTS version of JAVA. The following are the exciting features of JAVA 17 What's coming in JAVA 17? Context Specific Deserialzation Filters: This allows applications to configure dynamically selected and context-specific deserialization filters, using a JVM Wide filter factory which uses the filter for each deserialization operation. The opearation of Deserialization of untrusted data is intrinsically risky. This is because; the contents of the incoming data stream were obtained in many cases via unknown (or) the unauthenticated client. The key to prevent serialization is to prohibit the instances of arbitrary classes from being serialized that prevent the execution of methods directly (or) indirectly. An attacker can run the code from any class with the bad intent by carefully constructing the stream. Foreign Function and Memory API: This feature of the JAVA programming language allows the JAVA users to call up the Native Libraries, and process the native data without the risk of JNI, by efficiently invoking the foreign functions and securely accessing the foreign memory, This feature was implemented with the following goals Goals: Ease to Use: Replaces the superiors pure JAVA model with the JAVA Native Interface (JNI) Performance: The performance is similar to the existing API's like JNI's Safety: Deactive the unsecure options to the application only if developer (or) the end user has expreslly opted in. General: Provides the ways to work with the various types of external memories, and to accommodate other programming langauges over time Vector API (Second Incubator): This feature was introduced again introduced in this platform, even though it was introduced in JAVA 16 to express the vector computations, that were reliably to optimal the vector instructions, on supported CPU architectures at Run time, with scalar operations. This was introduced to improve the performance, and implementation including the enhancements to translate the byte vectors to and fro from the boolean arrays. This feature has the following goals: Clear and Concise API: The API present in this platform is good enough and is capbale of expressing broad variety of vector computations in a clear and concise manner. Platform Agnostic: The API Should be independent of CPU Artchitecture, allowing the implementations of variety of artchitecures, that supports the vector additions. Graceful Degradation: If a vector computation cannot be efficiently compiled to the vector instructions, then warnings can be issued. Deprecates the security Manager for Removal: Security Manager has deprecated in JAVA 17, and will be removed in the future version, along with the legacy applet. This feature has the following goals: Prepares developers for security Manager removal in the future version of JAVA. If the users JAVA program relies of security Manager, it isssues an alert. Evaluate the new API's (or) mechanisms to fix the limit (or) unique use cases when the security manager has been used such as blocking systems:exit. Removes the AOT and JIT Compiler: Removes Java bases Ahead of Time (AOT) and Just In Time Compiler, because of the limited usage and the effort required to maintain. As an experimental feature, JDK 9 has been integrated with ahead of time compilation. For AOT Compilation, Jaotc uses the java written, Graal compiler. Since the experiemental efforts have not been used there is considerable effort to maintain and improve them. Sealed Classes: This feature ehances the JAVA programming languages with sealed classes and interfaces. Sealed Classes and interfaces, restricts other classes (or) interfaces that can implement (or) extend. This feature has the following goals: Enables the class (or) interactive author, to control which to implement it. Support future pattern matching directions, with the basis to examine the trends. Do you want to know more on Sealed Classes ? If Yes, visit JAVA Online Training Removes RMI Activiation: The Remote Methods Invocation (RMI) mechanism will be removes but the rest of the RMI should be preserved. The RMI activation has become reduntant and is no longer in use. Pattern Matching for Switch: The Pattern Matching for Switch allows the switch expressions and the statements to the verified against a variety of patterns each with a different action. Hence this makes it possible to express the complex data-oriented queries in a simplistic and secure manner. This feature has the following goals, Goals: Allows patterns to appear in Case labels, increases the expresiveness and applicability of script phases and statements Ensures all the existing Switch expressions and statements compile with the identical semantics and perform them without any modifications Besides, two new patterns were introduced: Guardrd patterns: To refine the pattern matching logic using arbitraty boolean expressions Parentheseized Patterns: to clear up the parsing ambiguities. Strongly Encapsulate the JDK Signals: This feature strongly encapsulate every elements of JDK, except for the critical Internal API's such as sun.misc.Unsafe. It is no longer be possible to relax the strict encapsulation, of internal parts with a single command line option. Depreacte the Applet API for Removal: Since all the web browsers vendors have removed (or) revealed the plans to drop the support for JAVA browser plugins, Applet API is effectively use less. Mac OS / AArch 64 Port: Apple decides to move from X64 to AArch 64 on its macintosh computers. For Linux, Aarch 64 version of JAVA is already available and the development of windows port is currently under way. Because of the discrepancies in lower level conversations, such as binary interface, JAVA developers plan to use the existing AArch 64 Code from these ports by using the conditional compilation New Mac OS Renedering Pipeline: Since the JAVA 2D is totally reliant on Open GL, there is need for new JAVA 2D rendering pipeline, for mac OS using the new Apple metal framework. This has the following goals: Goals: Provide a completely functioning rendering pipeline for the mac OS metal framework based 2D API. Co-exist with Open GL until it is discontinued. Enhanced Pseudo Random Number Generators: Introduces new interface and implementations for pseudo random generators, that includes the jumpable PRNG and a splittable class PRNG algorithm Removes the Reduntant code from the current PRNG groups and can better support stream based programming Maintains Java.util.Random class as far as possible. Restore the Strict Floating Point Semantics: Rather of having both severe floating point semantics (strict fp) and significantly different default floating point semantics make floating point operations uniformly strict. Likewise, there are few other Java updates, that were every JAVA user is going to enjoy from September 2021. By reaching the end of this blog, I hope you people have acquired good information on what's new in Java 17. For practical explanation of these features, enroll today at JAVA Online Course and impart then necessary knowledge to become a certified JAVA Professional.
Continue reading
Ajax Interview Questions
Q.What Is Ajax? Ans: AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google Suggest, and Google Maps hit the streets. Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates: * standards-based presentation using XHTML and CSS; * dynamic display and interaction using the Document Object Model; * data interchange and manipulation using XML and XSLT; * Asynchronous data retrieval using XMLHttpRequest; * JavaScript binding everything together. Q.Who Is Using Ajax? Ans: Google is making a huge investment in developing the Ajax approach. All of the major products Google has introduced over the last year like Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques. These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn’t another technology that only works in a laboratory. Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps. At Adaptive Path, we’ve been doing our own work with Ajax over the last several months, and we’re realizing we’ve only scratched the surface of the rich interaction and responsiveness that Ajax applications can provide. Ajax is an important development for Web applications, and its importance is growing. The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. As there are so many developers out there who already know how to use these technologies, we expect to see many more organizations following Google’s lead in reaping the competitive advantage Ajax provides. The challenges are for the designers of these applications to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities Q.How Ajax Is Different? Ans: An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by introducing an intermediary — an Ajax engine — between the user and the server. It seems like adding a layer to the application would make it less responsive, but the opposite is true. Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually tucked away in a hidden frame. This engine is responsible for both rendering the interface the user sees and communicating with the server on the user’s behalf. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something. The synchronous interaction pattern of a traditional web application (top) compared with the asynchronous pattern of an Ajax application (bottom). Every user action that normally would generate an HTTP request takes the form of a JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a trip back to the server such as simple data validation, editing data in memory, and even some navigation the engine handles on its own. If the engine needs something from the server in order to respond if it’s submitting data for processing, loading additional interface code, or retrieving new data the engine makes those requests asynchronously, usually using XML, without stalling a user’s interaction with the application. Q.Where Should I Start? Ans: Assuming the framework you are using does not suffice your use cases and you would like to develop your own AJAX components or functionality I suggest you start with the article Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition. If you would like to see a very basic example that includes source code you can check out the tech tip Using AJAX with Java Technology. For a more complete list of AJAX resources the Blueprints AJAX Home page.Next, I would recommend spending some time investigating AJAX libraries and frameworks. If you choose to write your own AJAX clients-side script you are much better off not re-inventing the wheel. AJAX in Action by Dave Crane and Eric Pascarello with Darren James is good resource. This book is helpful for the Java developer in that in contains an appendix for learning JavaScript for the Java developer. Q.Do Ajax Applications Always Deliver A Better Experience Than Traditional Web Applications? Ans: Not necessarily. Ajax gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use Ajax to enhance the user experience of our applications, not degrade it. Q.Are Ajax Applications Easier To Develop Than Traditional Web Applications? Ans: Not necessarily. Ajax applications inevitably involve running complex JavaScript code on the client. Making that complex code efficient and bug-free is not a task to be taken lightly, and better development tools and frameworks will be needed to help us meet that challenge. Q.Does Ajax Work With Java? Ans: Absolutely. Java is a great fit for AJAX! You can use Java Enterprise Edition servers to generate AJAX client pages and to serve incoming AJAX requests, manage server side state for AJAX clients, and connect AJAX clients to your enterprise resources. The JavaServer Faces component model is a great fit for defining and using AJAX components. Q.Do I Really Need To Learn Javascript? Ans: Basically yes if you plan to develop new AJAX functionality for your web application. On the other hand, JSF components and component libraries can abstract the details of JavaScript, DOM and CSS. These components can generate the necessary artifacts to make AJAX interactions possible. Visual tools such as Java Studio Creator may also use AJAX enabled JSF components to create applications, shielding the tool developer from many of the details of AJAX. If you plan to develop your own JSF components or wire the events of components together in a tool it is important that you have a basic understanding of JavaScript. There are client-side JavaScript libraries (discussed below) that you can call from your in page JavaScript that abstract browser differences. Object Hierarchy and Inheritance in JavaScript is a great resource for a Java developer to learn about JavaScript objects. Q.Won't My Server-side Framework Provide Me With Ajax? Ans: You may be benefiting from AJAX already. Many existing Java based frameworks already have some level of AJAX interactions and new frameworks and component libraries are being developed to provide better AJAX support. I won't list all the Java frameworks that use AJAX here, out of fear of missing someone, but you can find a good list at www.ajaxpatterns.org/Java_Ajax_Frameworks. If you have not chosen a framework yet it is recommended you consider using JavaServer Faces or a JavaServer Faces based framework. JavaServer Faces components can be created and used to abstract many of the details of generating JavaScript, AJAX interactions, and DHTML processing and thus enable simple AJAX used by JSF application developer and as plug-ins in JSF compatible IDE's, such as Sun Java Studio Creator. Q.Did Adaptive Path Invent Ajax? Did Google? Did Adaptive Path Help Build Google's Ajax Applications? Ans: Neither Adaptive Path nor Google invented Ajax. Google’s recent products are simply the highest-profile examples of Ajax applications. Adaptive Path was not involved in the development of Google’s Ajax applications, but we have been doing Ajax work for some of our other clients. Q.Is It Possible To Set Session Variables From Javascript? Ans: It's not possible to set any session variables directly from javascript as it is purely a client side technology. You can use AJAX though to asynchronously... Q.Cannot Parse Xml Generated By Jsp I Am Generating An Xml Using Jsp, When I Run The Jsp In Ie It Shows The Xml As Per Dom, But When I Try To Parse It Using Javascript , The Command Xmldoc.documentelement ? Ans: This is working code, it might help you. if (!isIE) xmldoc = req.responseXML; else { //IE does not take the responseXML as. Q.What Do I Need To Know To Create My Own Ajax Functionality? Ans: If you plan not to reuse and existing AJAX component, here are some of the things you will need to know. Plan to learn Dynamic HTML (DHTML), the technology that is the foundation for AJAX. DHTML enables browser-base real time interaction between a user and a web page. DHTML is the combination of JavaScript, the Document Object Model (DOM) and Cascading Style Sheets (CSS). JavaScript - JavaScript is a loosely typed object based scripting language supported by all major browsers and essential for AJAX interactions. JavaScript in a page is called when an event in a page occurs such as a page load, a mouse click, or a key press in a form element. DOM - An API for accessing and manipulating structured documents. In most cases DOM represent the structure of XML and HTML documents. CSS - Allows you to define the presentation of a page such as fonts, colors, sizes, and positioning. CSS allow for a clear separation of the presentation from the content and may be changed programmatically by JavaScript. Understanding the basic request/response nature of HTTP is also important. Many subtle bugs can result if you ignore the differences between the GET and OIst methods when configuring an XMLHttpRequest and HTTP response codes when processing callbacks. JavaScript is the client-side glue, in a sense. JavaScript is used to create the XMLHttpRequest Object and trigger the asynchronous call. JavaScript is used to parse the returned content. JavaScript is used to analyze the returned data and process returned messages. JavaScript is used to inject the new content into the HTML using the DOM API and to modify the CSS. Q.What Javascript Libraries And Frameworks Are Available? Ans: There are many libraries/frameworks out there (and many more emerging) that will help abstract such things as all the nasty browser differences. Three good libraries are The Dojo Toolkit, Prototype, and DWR. The Dojo Toolkit contains APIs and widgets to support the development of rich web applications. Dojo contains an intelligent packaging system, UI effects, drag and drop APIs, widget APIs, event abstraction, client storage APIs, and AJAX interaction APIs. Dojo solves common usability issues such as support for dealing with the navigation such as the ability to detect the browser back button, the ability to support changes to the URL in the URL bar for bookmarking, and the ability to gracefully degrade when AJAX/JavaScript is not fully support on the client. Dojo is the Swiss Army Knife of JavaScript libraries. It provides the widest range of options in a single library and it does a very good job supporting new and older browsers. Prototype focuses on AJAX interactions including a JavaScript AJAX object that contains a few objects to do basic tasks such as make a request, update a portion of a document, insert content into a document, and update a portion of a document periodically. Prototype JavaScript library contains a set of JavaScript objects for representing AJAX requests and contains utility functions for accessing in page components and DOM manipulations. Script.aculo.us and Rico are built on top of Prototype and provide UI effects, support for drag and drop, and include common JavaScript centric widgets. If you are just looking to support AJAX interactions and a few basic tasks Prototype is great. If you are looking for UI effects Rico and Script.aculo.us are good options. DWR (Dynamic Web Remoting) is a client-side and server-side framework that focuses on allowing a developer to do RPC calls from client-side JavaScript to plain old Java objects in a Java Enterprise Edition web container. On the server side DWR uses a Servlet to interact with the Java objects and returns object representations of the Java objects or XML documents. DWR will be easy to get up and running and plays well with other Java technologies. If you are looking for a client-side and server-side framework that integrates well use DWR. There are many new and emerging libraries for JavaScript and this list only reviews some of the more common libraries. When making a choice choose the library which suites your needs the best. While it might be better to choose one, there is nothing stopping you from using more than one framework. For a more extensive list of client-side frameworks see: Survey of AJAX/JavaScript Libraries. Q.What Is The Difference Between Proxied And Proxyless Calls? Ans: Proxied calls are made through stub objects that mimic your PHP classes on the JavaScript side. E.g., the helloworld class from the Hello World example. Proxyless calls are made using utility javascript functions like HTML_AJAX.replace() and HTML_AJAX.append(). Q.Should I Use Xml Or Text, Javascript, Or Html As A Return Type? Ans: It depends. Clearly the 'X' in AJAX stands for XML, but several AJAX proponents are quick to point out that nothing in AJAX, per se, precludes using other types of payload, such as, JavaScript, HTML, or plain text. XML - Web Services and AJAX seem made for one another. You can use client-side API's for downloading and parsing the XML content from RESTful Web Services. (However be mindful with some SOAP based Web Services architectures he payloads can get quite large and complex, and therefore may be inappropriate with AJAX techniqes.) Plain Text - In this case server-generated text may be injected into a document or evaluated by client-side logic. JavaScript - This is an extension to the plain text case with the exception that a server-side component passes a fragment of JavaScript including JavaScript object declarations. Using the JavaScript eval() function you can then create the objects on the client. JavaScript Object Notation (JSON), which is a JavaScript object based data exchange specification, relies on this technique. HTML - Injecting server-generated HTML fragments directly into a document is generally a very effective AJAX technique. However, it can be complicated keeping the server-side component in sync with what is displayed on the client. Mashup is a popular term for creating a completely new web application by combining the content from disparate Web Services and other online API's. A good example of a mashup is housingmaps.com which graphically combines housing want-ads from craiglist.org and maps from maps.google.com. Q.Are There Usability Issues With Ajax? Ans: The nature of updating a page dynamically using data retrieved via AJAX interactions and DHTML may result in drastically changing the appearance and state of a page. A user might choose to use the browser's back or forward buttons, bookmark a page, copy the URL from the URL bar and share it with a friend via an email or chat client, or print a page at any given time. When designing an AJAX based application you need to consider what the expected behavior would be in the case of navigation, bookmarking, printing, and browser support as described below. Navigation -What would be the expected behavior of the back, forward, refresh, and bookmark browser buttons in your application design. While you could implement history manipulation manually it may be easer to use a JavaScript frameworks such as Dojo that provides API's history manipulation and navigation control. Bookmarking and URL sharing -Many users want to bookmark or cut and paste the URL from the browser bar. Dojo provides client-side for bookmarking and URL manipulation. Printing - In some cases printing dynamically rendered pages can be problematic. Other considerations as a developer when using AJAX are: Browser Support - Not all AJAX/DHTML features are supported on all browsers or all versions of a browser. See quirksmode.org for a list of browser support and possible workarounds. JavaScript disabled -You should also consider what happens if the user disables JavaScript. Additionally, there are several legitimate reasons why JavaScript and CSS support may be unavailable on a user's web browser. Latency -Keep in mind latency in your design. A running application will be much more responsive than when it is deployed. Latency problems: myth or reality? Accessibility -Guaranteeing your site is accessible to people with disabilities is not only a noble goal, it is also requited by law in many markets. Some marvelous enabling technology is available to help people use the Web in spite of disabilities including visual, auditory, physical, speech, cognitive, and neurological disabilities. With a little forethought, and comprehension of some well documented best practices, you can assure that your application is compatible with that enabling technology. Degradability is the term used to describe techniques used by web applications to adapt to the wide range of web browser capabilities. Many AJAX libraries have automatic degradability built in. But if you are coding your own custom AJAX functionality, simply taking some care to follow the best practices promoted by standards bodies like the World Wide Web Consortium (W3C), and grass root movements like the Web Standards community and many others, your application can run usefully on browsers that are incapable of AJAX behaviors. Granted, your application may loose some of the "wow factor" on these less capable browsers, but your application will still be usable. Remember to not design with AJAX just for the sake of coolness. The reason you built your application is so people will use it. And people will not use your application if your application is not compatible with their web browser. Q.Are There Any Frameworks Available To Help Speedup Development With Ajax? Ans: There are several browser-side frameworks available, each with their own uniqueness... Q.Is Adaptive Path Selling Ajax Components Or Trademarking The Name? Where Can I Download It? Ans: Ajax isn’t something you can download. It’s an approach — a way of thinking about the architecture of web applications using certain technologies. Neither the Ajax name nor the approach is proprietary to Adaptive Path. Q.Should I Use An Http Get Or Post For My Ajax Calls? Ans: AJAX requests should use an HTTP GET request when retrieving data where the data will not change for a given request URL. An HTTP POST should be used when state is updated on the server. This is in line with HTTP idempotency recommendations and is highly recommended for consistent web application architecture. Q.How Do We Debug Javascript? Ans: There are not that many tools out there that will support both client-side and server-side debugging. I am certain this will change as AJAX applications proliferate. I currently do my client-side and server-side debugging separately. Below is some information on the client-side debuggers on some of the commonly used browsers. Firefox/Mozilla/Netscape - Have a built in debugger Venkman which can be helpful but there is a Firefox add on known as FireBug which provides all the information and AJAX developer would ever need including the ability to inspect the browser DOM, console access to the JavaScript runtime in the browser, and the ability to see the HTTP requests and responses (including those made by an XMLHttpRequest). I tend to develop my applications initially on Firefox using Firebug then venture out to the other browsers. Safari - Has a debugger which needs to be enabled. See the Safari FAQ for details. Internet Explorer - There is MSDN Documentation on debugging JavaScript. A developer toolbar for Internet Explorer may also be helpful. While debuggers help a common technique knowing as "Alert Debugging" may be used. In this case you place "alert()" function calls inline much like you would a System.out.println. While a little primitive it works for most basic cases. Some frameworks such as Dojo provide APIs for tracking debug statements. Q.How Do I Provide Internationalized Ajax Interactions? Ans: Just because you are using XML does not mean you can properly send and receive localized content using AJAX requests. To provide internationalized AJAX components you need to do the following: Step 1. Set the charset of the page to an encoding that is supported by your target languages. I tend to use UTF-8 because it covers the most languages. The following meta declaration in a HTML/JSP page will set the content type: Step 2.In the page JavaScript make sure to encode any parameters sent to the server. JavaScript provides the escape() function which returns Unicode escape strings in which localized text will appear in hexadecimal format. For more details on JavaScript encoding seeComparing escape(), encodeURI(), and encode URI Component(). Step 3. On the server-side component set the character encoding using the HttpServletRequest.setCharacterEncoding() method. Before you access the localized parameter using the HttpServletRequest.getParameter() call. In the case of UTF this would be request .set Characther Encoding ("UTF-8");. A server-side component returning AJAX responses needs to set the encoding of the response to the same encoding used in the page. response.setContentType("text/xml;charset=;UTF-8"); response.getWriter().write(" invalid "); For more information on using AJAX with Java Enterprise Edition technologies see AJAX and Internationalization and for developing multi-lingual applications see Developing Multilingual Web Applications Using JavaServer Pages Technology. Q.Some Of The Google Examples You Cite Don't Use Xml At All. Do I Have To Use Xml And/or Xslt In An Ajax Application? Ans: No. XML is the most fully-developed means of getting data in and out of an Ajax client, but there’s no reason you couldn’t accomplish the same effects using a technology like JavaScript Object Notation or any similar means of structuring data for interchange. Q.When Do I Use A Synchronous Versus Asynchronous Request? Ans: They don't call it AJAX for nothing! A synchronous request would block in page event processing and I don't see many use cases where a synchronous request is preferable. Q.How Do I Handle Concurrent Ajax Requests? Ans: With JavaScript you can have more than one AJAX request processing at a single time. In order to insure the proper post processing of code it is recommended that you use JavaScript Closures. The example below shows an XMLHttpRequest object abstracted by a JavaScript object called AJAXInteraction. As arguments you pass in the URL to call and the function to call when the processing is done. function AJAXInteraction(url, callback) { var req = init(); req.onreadystatechange = processRequest; unction init() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } } function processRequest () { if (req.readyState == 4) { if (req.status == 200) { if (callback) callback(req.responseXML); } } } this.doGet = function() { req.open("GET", url, true); req.send(null); } this.doPost = function(body) { req.open("POST", url, true); req.setRequestHeader("Content-Type", " application/x-www-form-urlencoded"); req.send(body); } } function makeRequest() { var ai = new AJAXInteraction("processme", function() { alert("Doing Post Process");}); ai.doGet(); } The function makeRequest() in the example above creates an AJAXInteraction with a URL to of "processme" and an inline function that will show an alert dialog with the message "Doing Post Process". When ai.doGet() is called the AJAX interaction is initiated and when server-side component mapped to the URL "processme" returns a document which is passed to the callback function that was specified when the AJAXInteraction was created. Using this closures insures that the proper callback function associated with a specific AJAX interaction is called. Caution should still be taken when creating multiple closure objects in that make XmlHttpRequests as to there is a limited number of sockets that are used to make requests at any given time. Because there are limited number of requests that can be made concurrently. Internet Explorer for example only allows for two concurrent AJAX requests at any given time. Other browsers may allow more but it is generally between three and five requests. You may choose to use pool of AJAXInteraction objects. One thing to note when making multiple AJAX calls from the client is that the calls are not guaranteed to return in any given order. Having closures within the callback of a closure object can be used to ensure dependencies are processed correctly. There is a discussion titled Ajaxian Fire and Forget Pattern that is helpful. Q.What Do I Do On The Server To Interact With An Ajax Client? Ans: The "Content-Type" header needs to be set to"text/xml". In servlets this may be done using the HttpServletResponse.setContentType()should be set to "text/xml" when the return type is XML. Many XMLHttpRequest implementations will result in an error if the "Content-Type" header is set The code below shows how to set the "Content-Type". response.setContentType("text/xml"); response.getWriter().write("invalid"); You may also want to set whether or not to set the caches header for cases such as autocomplete where you may want to notify proxy servers/and browsers not to cache the results. response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("invalid"); Note to the developer: Internet Explorer will automatically use a cached result of any AJAX response from a HTTP GET if this header is not set which can make things difficult for a developer. During development mode you may want set this header. Where do I store state with an AJAX client As with other browser based web applications you have a few options which include: On the client in cookies - The size is limited (generally around 4KB X 20 cookies per domain so a total of 80KB) and the content may not be secure unless encrypted which is difficult but not impossible using JavaScript. On the client in the page - This can be done securely but can be problematic and difficult to work with. See my blog entry on Storing State on the Client for more details on this topic. On the client file system - This can be done if the client grants access to the browser to write to the local file system. Depending on your uses cases this may be necessary but caution is advised. On the Server - This is closer to the traditional model where the client view is of the state on the server. Keeping the data in sync can be a bit problematic and thus we have a solution Refreshing Data on this. As more information processing and control moves to the client where state is stored will need to be re-evaluated. Q.Whats With The -alpha In The Install Instructions? Ans: HTML_AJAX hasn't had a stable release yet and the pear installer doesn't install non stable packages by default unless you specify a version. Q.How Do I Submit A Form Or A Part Of A Form Without A Page Refresh? Ans: When creating a form make sure that the "form" element "onSubmit" attribute is set to a JavaScript function that returns false. You can also submit data by associating a function with a form button in a similar way. Note that the form "onSubmit" attribute is still set. If the user hits the enter key in the text field the form will be submitted so you still need to handle that case.When updating the page it is recommend you wait to make sure that the AJAX update of the form data was successful before updating the data in the page. Otherwise, the data may not properly update and the user may not know. I like to provide an informative message when doing a partial update and upon a successful AJAX interaction I will then update the page. Q.How Do I Test My Ajax Code? Ans: There is a port of JUnit for client-side JavaScript called JsUnit. Q.What Exactly Is The W3c Dom? Ans: The W3C Document Object Model (DOM) is defined by the W3C as the following: The Document Object Model is a platform- and language-neutral interface. Q.When Will Html_ajax Have A Stable Release? Ans: Once all the major features are complete and the API has been tested, the roadmap gives an idea of what is left to be done. Q.What Parts Of The Html_ajax Api Are Stable? Ans: We don't have a list right now, but most of the API is stable as of 0.3.0. There should be no major changes at this point, though there will be lots of new additions. Q.What Browsers Does Html_ajax Work With? Ans: We don't have a list right now, but most of the API is stable asAs of 0.3.0, all the examples that ship with HTML_AJAX have been verified to work with Firefox 1.0+ Internet Explorer 5.5+ (5.0 should work but it hasn't been tested) Most things work with Safari 2+ Opera 8.5+ of 0.3.0. There should be no major changes at this point, though there will be lots of new additions. Q.Is The Server Or The Client In Control? Ans: It depends. With AJAX the answer is more in between. Control can be more centralized in a server-side component or as a mix of client-side and server-side controllers. Centralized server-side controller - When having a more centralized controller the key is to make sure the data in client-side page is in sync with that of the server. Some applications may keep all the state on the server and push all updates to client DOM via a simple JavaScript controller. Client and server-side controllers - This architecture would use JavaScript to do all presentation related control, event processing, page manipulation, and rendering of model data on the client. The server-side would be responsible for things such as business logic and pushing updated model data to the client. In this case the server would not have intimate knowledge of the presentation short of the initial page that would be sent to the client page request. There are some use cases where an entire AJAX application can be written in a single page. Keep in mind if you choose this type of architecture that navigation and bookmarking should be considered. Both methods are viable depending on what you are trying to accomplish. I tend to prefer spreading the control across the client and server. Q.Is Ajax Just Another Name For Xmlhttprequest? Ans: No. XMLHttpRequest is only part of the Ajax equation. XMLHttpRequest is the technical component that makes the asynchronous server communication possible; Ajax is our name for the overall approach described in the article, which relies not only on XMLHttpRequest, but on CSS, DOM, and other technologies. Q.How Do I Abort The Current Xmlhttprequest? Ans: Just call the abort() method on the request. Q.What Is The Minimum Version Of Php That Needs To Be Running In Order To Use Html_ajax? Ans: The oldest PHP version i've fully tested HTML_AJAX is 4.3.11, but it should run on 4.2.0 without any problems. (Testing reports from PHP versions older then 4.3.11 would be appreciated.) Q.Why Does Html_ajax Hang On Some Server Installs? Ans: If you run into an HTML_AJAX problem only on some servers, chances are your running into a problem with output compression. If the output compression is handled in the PHP config we detect that and do the right thing, but if its done from an apache extension we have no way of knowing its going to compress the body. Some times setting HTML_AJAX::sendContentLength to false fixes the problem, but in other cases you'll need to disabled the extension for the AJAX pages. I've also seen problems caused by debugging extensions like XDebug, disabling the extension on the server page usually fixes that. Questions dealing with Using HTML_AJAX, and general JavaScript development Q.How Do We Get The Xmlhttprequest Object? Ans: Depending upon the browser... if (window.ActiveXObject) { // Internet Explorer http_request = new ActiveXObject("Microsoft.XMLHTTP"); } else if. Q.Are There Any Security Issues With Ajax? Ans: JavaScript is in plain view to the user with by selecting view source of the page. JavaScript can not access the local file system without the user's permission. An AJAX interaction can only be made with the servers-side component from which the page was loaded. A proxy pattern could be used for AJAX interactions with external services. You need to be careful not to expose your application model in such as way that your server-side components are at risk if a nefarious user to reverse engineer your application. As with any other web application, consider using HTTPS to secure the connection when confidential information is being exchanged. Q.What About Applets And Plugins? Ans: Don't be too quick to dump your plugin or applet based portions of your application. While AJAX and DHTML can do drag and drop and other advanced user interfaces there still limitations especially when it comes to browser support. Plugins and applets have been around for a while and have been able to make AJAX like requests for years. Applets provide a great set of UI components and APIs that provide developers literally anything. Many people disregard applets or plugins because there is a startup time to initialize the plugin and there is no guarantee that the needed version of a plugin of JVM is installed. Plugins and applets may not be as capable of manipulating the page DOM. If you are in a uniform environment or can depend on a specific JVM or plugin version being available (such as in a corporate environment) a plugin or applet solution is great. One thing to consider is a mix of AJAX and applets or plugins. Flickr uses a ombination of AJAX interactions/DHTML for labeling pictures and user interaction and a plugin for manipulating photos and photo sets to provide a great user experience. If you design your server-side components well they can talk to both types of clients. Q.Is Ajax Code Cross Browser Compatible? Ans: Not totally. Most browsers offer a native XMLHttpRequest JavaScript object, while another one (Internet Explorer) require you to get it as an ActiveX object.... Q.Techniques For Asynchronous Server Communication Have Been Around For Years. What Makes Ajax A "new" Approach? Ans: What’s new is the prominent use of these techniques in real-world applications to change the fundamental interaction model of the Web. Ajax is taking hold now because these technologies and the industry’s understanding of how to deploy them most effectively have taken time to develop. Q.Is Ajax A Technology Platform Or Is It An Architectural Style? Ans: It’s both. Ajax is a set of technologies being used together in a particular way. Q.How Do I Handle The Back And Forward Buttons? Ans: While you could go out and create a custom solution that tracks the current state on your application I recommend you leave this to the experts. Dojo addresses the navigation in a browser neutral way as can be seen in the JavaScript example below. function updateOnServer(oldId, oldValue, itemId, itemValue) { var bindArgs = { url: "faces/ajax-dlabel-update", method: "post", content: {"component-id": itemId, "component-value": itemValue}, mimetype: "text/xml", load: function(type, data) { processUpdateResponse(data); }, backButton: function() { alert("old itemid was " + oldId); }, forwardButton: function(){ alert("forward we must go!"); } }; dojo.io.bind(bindArgs); } The example above will update a value on the server using dojo.io.bind() with a function as a property that is responsible for dealing with the browser back button event. As a developer you are capable of restoring the value to the oldValue or taking any other action that you see fit. The underlying details of how the how the browser button event are detected are hidden from the developer by Dojo. AJAX: How to Handle Bookmarks and Back Buttons details this problem and provides a JavaScript library Really Simple History framework (RSH) that focuses just on the back and forward issue. Q.How Does Html_ajax Compare With The Xajax Project At Sourceforge? Ans: XAJAX uses XML as a transport for data between the webpage and server, and you don't write your own javascript data handlers to manipulate the data received from the server. Instead you use a php class and built in javascript methods, a combination that works very similiar to the HTML_AJAX_Action class and haSerializer combo. XAJAX is designed for simplicity and ease of use. HTML_AJAX allows for multiple transmission types for your ajax data - such as urlencoding, json, phpserialized, plain text, with others planned, and has a system you can use to write your own serializers to meet your specific needs. HTML_AJAX has a class to help generate javascript (HTML_AJAX_Helper) similiar to ruby on rail's javascript helper (although it isn't complete), and an action system similiar to XAJAX's "action pump" that allows you to avoid writing javascript data handlers if you desire. But it also has the ability to write your own data handling routines, automatically register classes and methods using a server "proxy" script, do different types of callbacks including grabbing remote urls, choose between sync and async requests, has iframe xmlhttprequest emulation fallback capabilities for users with old browsers or disabled activeX, and is in active development with more features planned (see the Road Map for details) HTML_AJAX has additional features such as client pooling and priority queues for more advanced users, and even a javascript utility class. Although you can use HTML_AJAX the same way you use XAJAX, the additional features make it more robust, extensible and flexible. And it is a pear package, you can use the pear installer to both install and keep it up to date. If you're asking which is "better" - as with most php scripts it's a matter of taste and need. Do you need a quick, simple ajax solution? Or do you want something that's flexible, extensible, and looking to incorporate even more great features? It depends on the project, you as a writer, and your future plans. Q.What Browsers Support Ajax? Ans: Internet Explorer 5.0 and up, Opera 7.6 and up, Netscape 7.1 and up, Firefox 1.0 and up, Safari 1.2 and up, among others. Q.How Do I Send An Image Using Ajax? Ans: While it may appear that images are being sent when using AJAX with an application like Google Maps what is really happening is that the URLs of images are being send as the response of an AJAX request and those URLs are being set using DHTML. In this example an XML document is returned from an AJAX interaction and the category bar is populated. 1 Books Fun to read books_icon.gif 2 Electronics Must have gadgets electronics.gif Notice that the image-url element contains the location of the URL for the image representing a category. The callback method of an AJAX interaction will parse the response XML document and call the addCategory function for each category included in the response XML document. The addCategory function looks up a table row element "categoryTable" in body of the page and adds a row to the element which contains the image. ... function addCategory(id, name, imageSrc) { var categoryTable = document.getElementById("categoryTable"); var row = document.createElement("tr"); var catCell = document.createElement("td"); var img = document.createElement("img"); img.src = ("images\" + imageSrc); var link = document.createElement("a"); link.className ="category"; link.appendChild(document.createTextNode(name)); link.setAttribute("onclick", "catalog?command=category&catid=" + id); catCell.appendChild(img); catCell.appendChild(link); row.appendChild(catCell); categoryTable.appendChild(row); } ... Body Here Note that the source of the image is set to the image source. The image is loaded by a subsequent HTTP request for the image at the URL "images/books_icon.gif" or "images/electronic_icon.gif" that occurs when the img element is added to the categoryTable. Q.Will Html_ajax Integrate With Other Javascript Ajax Libraries Such As Scriptaculous? How Would This Integration Look Like? Ans: HTML_AJAX doesn't have specific plans to integrate with other JavaScript libraries. Part of this is because external dependencies make for a more complicated installation process. It might make sense to offer some optional dependencies on a library like scriptaculous automatically using its visual effects for the loading box or something, but there isn't a lot to gain from making default visuals like that flashier since they are designed to be asily replaceable. Most integration would take place in higher level components. Its unclear whether higher level components like that should be part of HTML_AJAX delivered through PEAR or if they should just be supported by HTML_AJAX and made available from http://htmlajax.org or some other site. If your interested in building widgets or components based on HTML_AJAX please let me know. HTML_AJAX does however offer the ability to use its library loading mechanism with any JavaScript library. I use scriptaculous in conjunction with HTML_AJAX and I load both libraries through the server. To do this you just need to register the library with your server and load add its flag to your include line. server->registerJSLibrary('scriptaculous', array('prototype.js','scriptaculous.js','builder.js',' effects.js','dragdrop.js','controls.js','slider.js'), '/pathto/scriptaculous/'); ?> Q.When Should I Use A Java Applet Instead Of Ajax? Ans: Applets provide features like custom data streaming, graphic manipulation, threading, and advanced GUIs which AJAX cannot. However, with the help of DHTML, the functionalities of AJAX can be extended further. AJAX requires that the browser be DHTML and AJAX capable. AJAX-based functionality does need to take browser differences into consideration due to which using a JavaScript library such as Dojo which abstracts browser differences is recommended. AJAX/DHTML works well for applications where the latest browsers are used. Q.What Kinds Of Applications Is Ajax Best Suited For? Ans: We don’t know yet. Because this is a relatively new approach, our understanding of where Ajax can best be applied is still in its infancy. Sometimes the traditional web application model is the most appropriate solution to a problem. Q.Does This Mean Adaptive Path Is Anti-flash? Ans: Not at all. Macromedia is an Adaptive Path client, and we’ve long been supporters of Flash technology. As Ajax matures, we expect that sometimes Ajax will be the better solution to a particular problem, and sometimes Flash will be the better solution. We’re also interested in exploring ways the technologies can be mixed (as in the case of Flickr, which uses both). Q.Where Can I Find Examples Of Ajax? Ans: While components of AJAX have been around for some time (for instance, 1999 for XMLHttpRequest), it really didn't become that popular until Google took. But Global Guide Line guide all of its viewers to learn AJAX from absolute beginner to advance level. Q.What Is The Xmlhttprequest Object? Ans: It offers a non-blocking way for JavaScript to communicate back to the web server to update only part of the web page. Q.Does Ajax Have Significant Accessibility Or Browser Compatibility Limitations? Do Ajax Applications Break The Back Button? Is Ajax Compatible With Rest? Are There Security Considerations With Ajax Development? Can Ajax Applications Be Made To Work For Users Who Have Javascript Turned Off? Ans: The answer to all of these questions is “maybe”. Many developers are already working on ways to address these concerns. We think there’s more work to be done to determine all the limitations of Ajax, and we expect the Ajax development community to uncover more issues like these along the way. Q.How Do I Access Data From Other Domains To Create A Mashup With Java? Ans: From your JavaScript clients you can access data in other domains if the return data is provide in JSON format. In essence you can create a JavaScript client that runs operates using data from a different server. This technique is know as JSON with Padding or JSONP. There are questions as to whether this method is secure as you are retrieving data from outside your domain and allowing it to be excuted in the context of your domain. Not all data from third parties is accessible as JSON and in some cases you may want an extra level of protection. With Java you can provide a proxy to third party services using a web component such as a servlet. This proxy can manage the communication with a third party service and provide the data to your clients in a format of your choosing. You can also cache data at your proxy and reduce trips to service. For more on using a Java proxy to create mashups see The XmlHttpProxy Client for Java. Q.Does Java Have Support For Comet Style Server-side Push? Ans: Current AJAX applications use polling to communicate changes data between the server and client. Some applications, such as chat applications, stock tickers, or score boards require more immediate notifications of updates to the client. Comet is an event based low latency server side push for AJAX applications. Comet communication keeps one of the two connections available to the browser open to continuously communicate events from the server to the client. A Java based solution for Comet is being developed for Glassfish on top of the Grizzly HTTP connector. See Enabling Grizzly by Jean-Francois Arcand for more details. Q.How Do We Create A Thread To Do Ajax Polling? Ans: JavaScript does not have threads. JavaScript functions are called when an event happens in a page such as the page is loaded, a mouse click, or a form element gains focus. You can create a timer using the set Timeout which takes a function name and time in milliseconds as arguments. You can then loop by calling the same function as can be seen in the JavaScript example below. function checkForMessage() { // start AJAX interaction with processCallback as the callback function } // callback for the request function processCallback() { // do post processing setTimeout("checkForMessage()", 10000); } Notice that the checkForMessage will continue to loop indefinitely. You may want to vary the increment the interval based on activity in the page or your use cases. You may also choose to have logic that would break out of the loop based on some AJAX response processing condition. Q.Is The Xmlhttprequest Object Part Of A W3c Standard? Ans: No. Or not yet. It is part of the DOM Level 3 Load and Save Specification proposal. Q.How Does One Call A Javascript Function From The Ajax Code? Ans: Ajax is a form of JavaScript, which uses XML Http Request objects that take action event parameters into a method called “open”. The term AJAX symbolizes Asynchronous Java script and XML, wherein there is no order in which the requests and responses are tracked.”XMLHttpRequest.open” takes action events as URL Parameters. On the other hand, “XMLHttp Request.send” sends the Request object either asynchronously or synchronously, depending on whether the option for the synchronous version is true or false. Q.Can You List Some Examples Of Ajax-based Applications? Ans: Some applications and scenarios in which AJAX is utilized include login forms, auto-complete (e,g. Google search ), voting and rating systems, updating with user content, form submission and validation, chat rooms and instant messaging, Slicker UIs, external widgets, light-boxes (as opposed to pop-ups), and Flash (e.g. Flash games). Q.Is Ajax A Browser-dependent Or A Browser-independent Script? Ans: AJAX is a browser-dependent technology. The Ajax engine runs on Firefox, Opera 8, Safari and later Mozilla builds, and the Microsoft ActiveX object. Q.Describe The Animation Extender Control And The Method By Which This Control Is Utilized? Ans: The Animation Extender control permits you to program fluid animations to the controls that you put on the page. This control allows you to program elements that can move around the page based upon specific end user triggers (such as a button click). There are specific events available against which to program your animations. These events include “OnClick,” “OnHoverOver”, “OnHoverOut”, “OnLoad,” “OnMouseOver,” and “OnMouseOut,” which are to be constructed as: Q.Does Load Runner Support Ajax Apps? Ans: Load Runner supports AJAX Apps. However, Ajax protocols in Load Runner are not as efficient as they are in HTTP. Yet, using HTTP to record AJAX web requires copious custom coding. AJAX protocols heavily depend on memory, and running more than 2GB of ram could cause the machine to freeze. Q.Describe The Process And Benefits Of Using The Always Visible Control Extender? Ans: The Always Visible Control Extender authorizes a control to be pinned to a particular location. For example, when a control has been permanently set to be present at the left corner of the page, the control will be so in the prescribed left and right co-ordinates. This placement will apply, whenever the page is resized or scrolled. Q.What Are Synchronous And Asynchronous Ajax Requests? Ans: During the initiation of synchronous requests, the script desists and awaits a reply from the server before proceeding; but during the initiation of asynchronous requests, the script sanctions the procession of the page and handles the reply. Q.How We Can Send More Values Through The Response Text? Ans: We can send text values with the concatenation of ‘I’ operator and by splitting with the pipe operator like ’responseText.split(‘|’);’ If done properly, we would receive an array of our text. Now, we can access it, or we can use JSQN to send multiple text values in a array format. Q.What Is The Predominant Distinction Between Javascript And J-query? Ans: JavaScript is a language, while j-query is merely a library written using JavaScript. This library is light-weight, cross-browser compatible, and simple. One can also assert that j-query is a plugin used to build function. Q.When Should We Use A Java Applet Instead Of Ajax? Ans: Many amazing things can be done with AJAX/DHTML, but there are limitations. AJAX and applets can be used together in the same UIs, with AJAX providing the basic structure and applets providing more advanced functionality. The java applet can communicate to JavaScript using the Live-Connect APIs. One should not ask: “should we use AJAX or applets?” Instead, one should discover which technology best fits your needs. In summary, AJAX and applets need not be mutually exclusive. Q.What Is The Difference Between A Destructor And A Garbage Collector? Ans: A destructor is a special member function of a class called as soon as an object is de-allocated, while a garbage collector is either a program or an application that de-allocates the memory of a formerly unreachable object. Q.Do Ajax Applications Always Deliver A Better Experience Than That Delivered By A Traditional Web Application? Ans: AJAX gives interaction designers more flexibility. However, the more power we have, the more caution we must use in exercising it. We must be careful to use AJAX only to enhance the user experience of our applications. Q.How Do We Manage Concurrent Request? Ans: For managing concurrent request we can write a function or we can use Java Script closures. After code processing is finishes the call back function and the URL would pass as parameters, they are passed to the object (Ajax Interaction). These closures are good in the way that they insure the right callback function will be invoked and this will have a particular Ajax Interaction. Q.Which Are The Problems That Can Be Fixed Using Ajax And What Is The Actual Meaning Of Ajax? Ans: The technologies that represent Ajax belong to the client and they make possible an asynchronous client to server communication. When synchronous communication is involved at every event a complete round trip takes place, issue solved by using asynchronous communication. Q.Is There Any Use Abilities Problems In Ajax? Ans: The appearance of a page is changed very much when we used Ajax interaction to dynamically update it. Because of the dynamically changes, also the state of the page is modify and the page behavior has to be defined for the following actions :navigation, using back , slash forward, page bookmarks, URL sharing, time dependant , printing of pages. Navigation-we have to define page refreshing, back and forward and so on .For simplifying navigation we can use a Java Script framework like Dojo. For bookmarking or URL sharing we have Dojo. Printing-problems may appear when the rendered pages are printed dynamically. Q.Which Are The Knowledge Requirements For Personal Ajax Functionality? Ans: To make a personal Ajax component and not reuse an already made one we need to have knowledge of the following: Learning of DHTML or Dynamic HTML is a must because this is the Ajax foundation; it enables a high level of interaction in the browsers between users and pages. CSS, Document Object Model and Java Script form together what is called DHTML. We must also learn JavaScript which is an object based language compatible with the majority of browsers and very important for the interactions of Ajax, JavaScript is invoked on mouse clicks, page boots pr completing various form. Document Object Model or DOM is an application used for handling structured documents usually with HTML or XML documents. CSS-gives us the possibility to dyne the appearance(fonts, sizes, colors, positions it).In addition to these we must also known about the requestresponse behavior of HTTP, because ignoring some of the things involved can load to serious bugs. Q.Which Are The Trigger Types That We Find In Update Panel? Ans: The types or triggers are in member of two: PostBackTrigger and AsynPostBackTrigger. The first one makes a complete postback. It doesn’t work asynchronously, the second one makes a practical postback and this is working asynchronously. Q.How Can Javascript Be Debugged? Ans: Right now the number of utilities that are compatible with both client and server debugging is small, but this could change over time. The debugging is currently made in separate way. Some of the client debuggers for some popular browsers are presented below: the Venkman debugger is a built-in feature of Netscape/Mozilla browser and also there is an add-on called FireBug, also the browser Safari has a similar debugger that can be used by activation and Internet Explorer has some methods of debugging JavaScript. A common method used by debuggers is “Alert Debugging” with the function “alert( )”. Q.What Are The Protocols And Forms In Ajax? Ans: XMLHttpRequest, this protocol is meant for doing requests to a server. The client browser makes an object, the transfer of data happens in JSON or plain text. The JSON format can be parsed by java script and will be compatible with every browser. Q.Do We Have To Use Http Get/post For The Ajax Calls? Ans: If the data doesn’t change for a particular request URL, HTTP GET requests are necessary. If the state on a server is going to be updated then a HTTP POST is necessary. Q.Easy Trough That The Classical Web Applications Are Harder To Make Than Ajax Applications? Ans: Not really, because the code that has to run on the client is complicated and it is hard to create such a code, without having bugs and we need the aid of many tools of an efficient code. Q.Why Is Html_ajax Having Stability Issues On Some Installations? Ans: If the problem that we have with is specific to certain servers the best explanation would be that the problem relates to output compression. It can be dictated and fixed PHP config but if it is a related apache extension it is almost impossible to be detected properly. In most cases we will have to disable the AJAX extension, but in rare cases we can fix the issue by using the setting sendContentLength to false. Also xDdebug can create some issues but they can be fixed by the activating the extension. Q.Is It True That Ajax Is Code Browser Compatible? Ans: Yes but only partially. The majority of browsers give us a built-in XMLHttpRequest JavaScript object but some, like Internet Explorer, will asked it in the form of an ActiveX object. Q.Is It True That A Xmlhttprequest Objects Belongs To The W3c Standard? Ans: This hasn’t been decided until now but we know just that it belongs to DOM Level 3 Load and Save. Q.What Meaning Has Asp.net Ajax? Ans: ASP .NET Ajax is developed by Microsoft and it represent the free Ajax frame work used for creating applications that have a great amount of interactivity and is compatible with all the browsers. It gives us the possibility to choose our own way of using Ajax no matter if is Server-side, Client-side, the Query library or the Ajax Control Tool kit. Q.What Are The Browser Versions That Ajax Is Compatible With? Ans: From the version 0.3.0 Ajax is compatible with Internet Explorer 5.5, Mozilla Firefox 1.0, Safari 2+ and Opera 8.5+. Q.In What Way Are Proxyless Calls Different Than The Proxied Calls In Ajax? Ans: Proxyless calls can be possible using functions such as HTML_AJAX.replace() or HTML_AJAX.append(). This functions are JavaScript utilities. Proxied calls are possible by using limitations of PHP classes or stub objects in JavaScript. Q.How Can We Make A Mashup With Java By Accessing Other Domains Data? Ans: We can gain access to other domains data in our Java Script clients if the format of the data returned is in JSON format. In this way JavaScript client can be made which is running with the usage of another servers data, method called JSQN with Padding (JSQNP). This method has his doubts when it comes to security, because it functions by bringing data from outside our domain, but the execution is made inside. Not every type of data from outside can be accessed as JSON and sometimes we want more security. In Java a proxy can be given to outside services with the aid of what we called a servlet, which is used for communication management between outside and inside services and gives us the possibility of changing the format of the data we provide according to our wishes. For speed improvement data can be cached. QDoes Ajax Have The Same Meaning As Xmlhttprequest? Ans: Because XMLHttpRequest is just a piece of Ajax, the answer will be no. Ajax depends on many pieces like XMLHttpRequest, CSS, DOM, etc. XMLHttpRequest is the part responsible for asynchronous server communication. Q.In Ajax Does The Client Or The Sever Have The Control? Ans: Sometimes yes, sometimes no. It can be more like a server-side centralized component or controller or client-side controller. A centralized server-side controller is the case where we must assure that the client-side page data is synchronized with the server data. Many programs are preserving everything on the server and the updates are given to the client DOM through an easy Java Script controller. The case of client and server-side controllers uses a JavaScript for making each control that relates to presentation, each processing of events, each manipulation of pages and model data rendering on the client. The responsibility of business logic or giving the updated model data to a client is taken by the server-side. But this case doesn’t include specific information about the initial pages which is sent to the request of the client page. In certain use cases the whole Ajax application is possible to write in one page. If we chose this we must also remember about bookmarking and navigation. Q.We Used Asynchronous Server Communication For A Long Time, What New Thing Is Ajax Bringing? Ans: Ajax is bringing changes in the way we use interactive real-world web applications. Now it’s time to apply all this new technologies that have been in development for many years. Q.Is It True That The Ajax Application Are Much Better Than The Classical Internet Applications? Ans: Not really. What it is true is that Ajax has brought more flexibility. This flexibility also implies a higher degree of responsibility when we use Ajax for providing a better experience for the user. Q.What Is The Response Time When Using Ajax? Ans: Response time can also be named latency and it means the period of time that passes from the beginning of a request processing by the client to the sever until its end. Id the time is longer than normal then we say we had a delay, Delays usually appear when the XMLHttpRequest object is badly handled. Q.Which Is The Purpose For Using The Scriptmanager? Ans: ScriptManager is used for handling every ASP.NET Ajax resource and it makes links for the client libraries in ASP.NET Ajax. This means we will be able to use UpdatePanels, PageMethods and others. Also the page request Manager and Application objects are made, they are important in the client life cycle for raising events in the ASP.NET Ajax web pages. It is also good for making proxies for calling web services asynchronously. Q.What Is The Use Of Updatepanel? Ans: Updatepanel gives us the possibility to make ASP .NET applications Ajax compatible, to update the content of a page with the aid of Partial-Page rendering. This is useful for refreshing a section of the page without refreshing the entire page. Contact for more online training Dotet Online Training
Continue reading
C and C++ Interview Questions
C Interview Questions Q.Who invented C Language? Ans: Dennis Ritchie in 1972 developed a new language by inheriting the features of both BCPL and B and adding additional features. He named the language as just C Q.Who invented B Language? Ans: Ken Thomson at AT&T Bell Labs developed a language and named it B. Even the B language was found to have some short comings to support development of both business applications and system software. Q.Who invented BCPL Language? Ans: Basic Combined Programming Language (BCPL) was developed by Martin Richards, Cambridge university. Q.Why C Language? Ans: C is one of the high level languages. It is a general purpose language, which means it can be used to write programs of any sort. Q.What are the features of C Langauges? Ans: In C one can write programs like that of high level languages as in COBOL, BASIC, FORTRAN etc. as well as it permits very close interaction with the inner workings of the computer. It is a general purpose programming language. It is usually called system programming language but equally suited to writing a variety of applications. It supports various data types It follows the programming style based on fundamental control flow constructions for structured programming Functions may be pre–defined or user defined and they may return values of basic types, structures, unions or pointers. Q.What are the advantages of c language? Ans: Easy to write Rich set of operators and functions that are built–in Support for bit–wise operation Flexible use of pointers Direct control over the hardware Ability to access BIOS/DOS routines Interacting using Interrupts Ability to write TSR programs Ability to create .COM files Ability to create library files (.LIB) Ability to write interface programs Incorporating assembly language in C program Q.What are the disadvantages of c langauge? Ans: C is considered difficult to learn Because of its conciseness, the code can be difficult to follow It is not suited to applications that require a lot of report formatting and data file manipulation Q.What are the salient features of c languages? Ans: The following are the salient features of C language are : C is called a middle level language C supports structured design approach C is extensible C is rich in data types and operators C is portable Q.What is a header file? Ans: Header files provide the definitions and declarations for the library functions. Thus, each header file contains the library functions along with the necessary definitions and declarations. For example, stdio.h, math.h, stdlib.h, string.h etc. Q.What is character set? Ans: Character set is the set of characters allowed and supported in the programming language. Generally a program is a collection of instructions, which contain groups of characters. Only a limited set of characters is allowed to write instructions in the program. Q.What is C token? Ans: The smallest individual units of a C program are known as tokens. Q.List the different types of C tokens? Ans: Constants Identifiers Keywords Operators Special symbols Strings Q.What is a string? Ans: A string is a sequence of characters ending with NUL. It can be treated as a one–dimensional array of characters terminated by a NUL character. Q.What are qualifiers? Ans: Qualifiers or modifiers are identifiers that may precede the scalar data types (except float) to specify the number of bits used for representing the respective type of data in memory. The qualifiers in C are short, long, signed, and unsigned. Q.What is a function? Ans: A function is a set of statements to perform a specific task. Q.What is a constant? Ans: A constant is a value that does not change during the program execution. A constant used in C does not occupy memory. Q.What are the different types of constants? Ans: There are five types of constants. They are : Integer constants Floating point constants Character constants String literals Enumeration constants Q.What is variable? Ans: An identifier is used to identify and store some value. If the value of the identifier is changed during the execution of the program, then the identifier is known as variable. Q.What are the rules for the identifier? Ans: The first character must be an alphabet or underscore (_) Digits may be included in the variable The maximum number of characters in a word are 32 (It may vary depending upon the platform) No other special characters are allowed. Q.What are global variables? Ans: Global Variables are those, which are required to be acccessed by all the functions defined after their declaration. So, the variables declared before the main {) can be acccessed by all the functions, which follow their declaration. Q.What is a keyword? Ans: Keywords are those words of C which have predefined meaning assigned by the C language. They form a part of the database required by the C compiler. Q.What are the different types of c instructions? Ans: There are basically three types of instructions in C are : Type Declaration Instruction Arithmetic Instruction Control Instruction Q.What is an expression? Ans: Expression is defined as a combination of operands and operators to obtain some computation. Operands represent variables or values and The operator tells is what operation to be performed. Q.What are the types of data files? Ans: There are two types of data files : stream oriented or standard data files system oriented or low level data files Q.Why C is called a middle level language? Ans: C combines the features of both Assembly Level Languages (Low Level Languages) and Higher Level Languages. For this reason, C is referred to as a Middle Level Language. The feature of ALLs is that of enabling us to develop system level programs and the features of HLLs are those of higher degree of readability and machine independence. Q.How can variables be characterized? Ans: The variables can be categorized by storage class as well as by data type. The storage class specifies the portion of the program within which the variables are recognized. Q.Give the rules for variable declaration? Ans: The rules for variable declaration in C are given below : A variable name consists of alphabets, digits and the underscore (_) character The length of variable should be kept upto 8 characters though your system may allow upto 40 characters They must begin with an alphabet Some systems also recognize an underscore as the first character White space and commas are not allowed Any reserved word (keyword) cannot be used as a variable name. Q.What is the purpose of type declarations? Ans: The type declaration allow to create a synonym for other data types. Its syntax is typedef type identifier; The declaration typedef unsigned long int INTEGER Q.What is recursion? Ans: C language a function may call another function. When a function calls itself, it is referred to as recursive call and the process is known as recursion. C provides very good facilities for recursion. Q.What is data types? Ans: Data types refer to the classes of data that can be manipulated by C programs. The three fundamental data types supported by C are character, integer and real type. Q.What are the types of macro formats? Ans: There are two types of macro formats. There are Simple Parameterized Q.What are the different types of errors? Ans: Compile–Time Errors Linker Errors Runtime Errors Logical Errors Q.What is meant by errors and debugging? Ans: Errors may be made during program creation even by experienced programmers. Such type of errors are detected by the compiler. Debugging means removing the errors.. Q.What is the purpose of main() function? Ans: The function main() invokes other functions within it.It is the first function to be called when the program starts execution. It is the starting function. It returns an int value to the environment that called the program. Recursive call is allowed for main( ) also. It is a user-defined function. Q.What is meant by type casting? Ans: It is the explicit type conversion required for a number before carrying out processing or assigning to another variable. Q.What are the primitive data types in c? Ans: There are five different kinds of data types in C. Char Int Float Double Void Q.What is the use of typedef? Ans: The typedef help in easier modification when the programs are ported to another machine.A descriptive new name given to the existing data type may be easier to understand the code. Q.What is meant by type specifiers? Ans: Type specifiers decide the amount of memory space occupied by a variable. In the ease of integral types; it also explicitly states the range of values that the object can hold.. Q.What are the types of type specifiers? Ans: The available data type specifiers are : Short Long Signed Unsigned Q.What is masking? Ans: Masking is a process in which a given bit pattern is partly extracted into another bit pattern by means of a logical bitwise operation. Q.What is the difference between single charater constant and string constant? Ans: A single character constant consists of only one character and it is enclosed within a pair of single quotes. A string constant consists of one or more characters and it is enclosed within a pair of double quotes. Q.What is signed and unsigned? Ans: A numeric value, may have a positive or a negative sign. In the memory, for a variable, one bit is used exclusively to maintain the sign of the data. If we don't have sign, the sign bit also may be used for data. If the value is negative, the sign bit is 1, and if it is positive, it will be 0. Q.What are the different categories of functions in C? Ans: In C, the functions can be divided into the following categories : Functions with no arguments and no return values Functions having arguments but no return values Functions having arguments and return values also Q.What is this pointer? Ans: It is a pointer that points to the current object. This can be used to access the members of the current object with the help of the arrow operator Q.What is zero based addressing? Ans: The array subscripts always start at zero. The compiler makes use of subscript values to identify the elements in the array. Since subscripts start at 0, it is said that array uses zero-based addressing. Q.What is a loop? Ans: A loop is a process to do a job repeatedly with possibly different data each time. The statements executed each time constitute the loop body, and each pass is called iteration. A condition must be present to terminate the loop. Q.What are the types of data types and explain? Ans: There are five basic Data types in C. These are : void : means nothing i.e. no data involvement in an action char : to work with all types of characters used in computer operations int : to work with an integer type of data in any computational work float : to work with the real type of data or scientific numbers in the exponential form double : to work with double precision of numbers when the approximation is very Q.What is friend function? Ans: The function declaration should be preceded by the keyword friend.The function definitions does not use either the keyword or the scope operator ::. The functions that are declared with the keyword friend as friend function.Thus, a friend function is an ordinary function or a member of another class. Q.What is break statement? Ans: When a break is encountered inside a loop, the loop is terminated and the control passes to the statement following the body of the loop. Q.What is the use of getchar() function? Ans: It returns a character just entered from the standard input unit, that is, keyboard. The entered character can be either assigned to a character variable or echoed to the computer screen. Q.What is a pointer? Ans: A pointer is a variable that represents the location (rather than the value) of a data item, such as a variable or an array element. It is a variable that holds a memory address. This address is the location of another variable or an array element in memory. Q.How to declare pointer variables? Ans: If a variable is going to be a pointer, it must be declared as such. A pointer declaration consists of a base type, an *, and the variable name. The general form for declaring a pointer variable is data _type * var_ name; Q.What is the difference between fread buffer() and fwrite buffer()? Ans: Fread(), buffer is a pointer to an area of memory that will receive the data from the file. For fwrite(), buffer is a pointer to the information that will be written to the file. The value of count determines how many items are read or written, with each item being num_byte bytes in length. The size_t in both the formats is defined as some kind of unsigned integer. Finally, fp is a file pointer to a previously opened file. Q.What is macro? Ans: The second preprocessor function is macro definition. A macro is formal syntax that can be used to generate statements for use in a program. For the C language, the macro generates C statements. Q.What are the types of I/O functions? Ans: I/O functions are grouped into two categories : Unformatted I/O functions Formatted I/O functions Q.What is the difference b/w formatted&unformatted I/O functions? Ans: The formatted I/O functions allow programmers to specify the type of data and the way in which it should be read in or written out. On the other hand, unformatted I/O functions do not specify the type of data and the way is should be read or written. Q.How to declare pointer variables? Ans: If a variable is going to be a pointer, it must be declared as such. A pointer declaration consists of a base type, an *, and the variable name. The general form for declaring a pointer variable is data _type * var_ name; Q.What is the difference between c &c++? Ans: c++ is an object oriented programing but c is a procedure oriented programing.c is super set of c++. c can't suport inheritance,function overloading, method overloading etc. but c++ can do this.In c-programe the main function could not return a value but in the c++ the main function shuld return a value. Q.What is the use of putchar function? Ans: The putchar function displays one character on the display monitor. The character to be displayed is of type char. The syntax for putchar function is as given below :putchar (ch_var); Where ch_var is a previously declared character variable. Q.What is the use of getchar functions? Ans: The getchar function accepts a single character from the keyboard. The function does not require any arguments, though a pair of empty parentheses must follow the word getchar as a syntax. It returns a single character from a standard input device (typically a keyboard ) and it can be assigned to predeclared character variable. Q.What is character constants? Ans: A character constant is a single character, enclosed within the pair of single quotation mark (apostrophes). Q.What is string constants? Ans: A string constant or literal contains a sequence of zero or more characters or escape seauences enclosed in double Quotation marks. Q.What is integer constants? Ans: An integer constant is an integer-valued number. It can represent decimal, octal, or hexadecimal values. Q.What is floating point constants? Ans: Floating-point constants are numbers with decimal parts. A floating-point constants consists of : An integral part A decimal point A fractional part An exponent part An optional suffix Q.What is the difference between fread and fwrite function? Ans: The fread() function returns the number of items read. This value may be less than count if the end of the file is reached or an error occurs. The fwrite() function returns the number of items written. This value will equal count unless an error occurs. Q.What are the uses of a pointer? Ans: Pointer is used in the following cases It is used to access array elements It is used for dynamic memory allocation It is used in Call by reference It is used in data structures like trees, graph, linked list etc. Q.What are linker error? Ans: The Linker Errors occur during the linking process when the external symbols referred to by the program are not resolved. Q.What are runtime error? Ans: The Runtime Errors occur while a program is being run and hence the name. They occur due to both program internal and external factors. Q.When do we get logical errors? Ans: The Logical Errors occur if the solution procedure for the given problem itself is wrong. In this case, the outputs produced by the programs would be incorrect. Correcting the solution procedure itself by better understanding of the problem eliminates these errors. The Logical Errors (if any) are to be figured out by ourselves by verifying the outputs that are produced by the program. Q.Do character constants represent numerical values? Ans: Yes, each character constant associates an integer value with it. Q.What is the purpose of scanf() and printf() functions? Ans: The function scanf() is used for formatted input from the standard input and provides many of the conversion facilities. It is used for formatted output to standard output device, that is, screen. The format specification string and the data to be output, are the arguments (parameters) to the printf() function. Q.What is type qualifiers? Ans: Type qualifier adds properties to an identifier. Type qualifiers describe the manner in which the object will be modified. The application of qualifiers to an object does not affect the range or the arithmetic properties of the object. Q.What are the types of type qualifiers in c? Ans: The two type qualifiers provided by C are : const volatile Q.What is meant by inheritance? Ans: Inheritance is the process by which objects of one class acquire properties of objects of another class.. Q.Do string constants represent numerical values? Ans: No, the string constants donot have a corresponding numerical value. Q.What is meant by operator precedence? Ans: Operator precedence describes the order in which C evaluates different operators in a complex expression. Q.What is an Operator? Ans: An operator is a symbol, which instructs the computer to perform the specified manipulation over some data. The rich set of operators available in C enable us to write efficient and concise programs and this fact serves to set C apart from any other programming languages. Q.What are the types of operators in c? Ans: Assignment operator Arithmetic operators Relational operators Logical operators Increment/Decrement operators Shorthand arithmetic assignment operators Conditional operator Bitwise operators Sizeof() operator Comma operator Q.What is a ternary operator in C? Ans: Perhaps the most unusual operator in C language is one called the conditional expression operator. Unlike all other operators in C which are either unary or binary operators the conditional expression operator is a ternary operator; that is, it takes three operands. The two symbols that are used to denote this operator are the question mark (?) and the colon (:). The first operand is placed before the ?, the second between the ? and the and the third after the :. Q.What is assignment operator? Ans: An operator is a symbol that operates on a certain data type.In C, the ’=’ symbol is known as the assignment operator. It sots the value of the variable on the left hand side of it to that of the right hand side of it. Q.What are the types of assignment statements? Ans: C supports a variety of assignment statements. These are given below : Simple assignment statement Multiple assignment statement Arithmetic assignment statement Q.What is the sizeof () operator? Ans: Even though it looks like a keyword, sizeof( ) is an operator which is used to know the memory size of the data types and variables. This operator returns the number of bytes allocated for the variable (or) data type. The format of the sizeof() operator is as follows. sizeof (v); where v is a variable name / data type / value. Q.What is the use of bitwise operator? Ans: The bitwise operator performs the operation on bits (i.e. bit by bit). Using the bitwise operators we can set / reset / check any bit in the value of the variable. Q.What is the Difference between = and = = Operators? Ans: The two operators = and == are used for assignment and checking respectively. If not properly used, it causes many problems. The following program illustrates what will happen if we use = instead of = =. Q.What is unary operator? Ans: The operators that act upon a single operand to produce a new value are known as unary operators. Q.What are the types of unary operators? Ans: C support unary operators are : minus operator - increment operator + + decrement operator – size operator (type) operator Q.What is the difference between break and continue? Ans: The break statement is used to exit from all the loop constructs (while, do while and for) and switch.case statements, whereas the continue statement is used to skip all subsequent instructions and can control back to the loop control. The continue statement can be used for any loop construct. Q.What is storage class? Ans: The storage class in C provides the complete information about the location and visibility of variables. Scope of a variable means the portion of the program within which it can be referenced and lifetime means the time of its existence in the memory. Q.What are the different storage classes in C? Ans: There are four types of storage classes. Automatic : Variable used as a local variable. This is the default one. Initial value of variable is garbage value without initialization. Extern : Variable used as a local variable. Retains its value during next function call. Regiter : Variable used as a local variable. May be stored in register if possible. Default initial value is garbage value. Static : Variable used as a global variable. Q.What are the types of bitwise operator? Ans: There are three types of bitwise operator. Bitwise AND(&) Bitwise OR(|) Bitwise Exclusive OR(^) Q.What is difference between function overloading and operator overloading? Ans: A function is overloaded when same name is given to different function.While overloading a function, the return type of the functions need to be the same. Q.What is getche() function? Ans: It returns a character just entered from the standard input unit. The entered character is echoed (displayed) to the computer screen. It reads a single character the moment it is typed without waiting for the Enter key to be hit. Q.What is getch() function? Ans: It returns a character just entered from the standard input unit. The entered character is not echoed on the screen. It reads a single character the moment it is typed without waiting for the Enter key to be hit. Q.What is putchar() function? Ans: It prints the character constant or the character variable to the standard output device. The function putchar( ) has the following form : putchar (var name) Q.What is an arrays? Ans: Arrays can be defined as a collection of variables of the same type that are referred through a common name. Q.What are the advantages of the functions? Ans: It reduces the complexity in a program by reducing the code Function are easily understanding and reliability and execution is faster It also reduces the time to run a program.In other way, Its directly proportional to complexity Its easy to find-out the errors due to the blocks made as function definition outside the main function. Q.What are the characteristics of arrays in C? Ans: An array holds elements that have the same data type Array elements are stored in subsequent memory locations Two–dimensional array elements are stored row by row in subsequent memory locations Array name represents the address of the starting element Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable. Q.What is the difference between arrays and pointers? Ans: Array is collection of similar datatype. it is a static memory allocation means we can not increment and decrement the arry size once we allocated. and we can not increment the base address, reassign address. Pointer is a dynamic memory allocation. we can allocate the size as we want, assigning into another variable and base address incrementation is allowed. Q.What is else if ladder? Ans: The else if ladder helps select one out of many alternative blocks of statements for execution depending on the mutually exclusive conditions. Q.What is class? Ans: A class represents description of objects that share same attributes and actions. It defines the characteristics of the objects such as attributes and actions or behaviors. It is the blue print that describes objects. C++ Interview Questions Q.What is C++? Ans: C++ is an object oriented programming language. It was developed by Bjame Stroustrup in 1983 at the AT & T Bell Laboratories, Now Jersey, USA. It is basically a super set of C, which provided low level features. Q.What are the basic concepts of OOP? Ans: Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Passing Q.What is oops? Ans: An object oriented program is a collection of discrete objects, which are self contained collections of both data structures and functions that interact with other objects. Q.What are the characteristic of C++ language? Ans: It has the following characteristics : Reduces complexity while solving problems Correctness of results is ensured Affordable in terms of hardware and other resources Easier and cheaper for integrating existing software facilities and libraries Portable i.e. can be used on different types of computers with little or no change in the programs. Q.What are the types of character set? Ans: We have two character sets in C++. These are : Source characters Escape sequences /Execution characters Q.What are the elements of OBJECT ORIENTED PROGRAMMING? Ans: The main concepts of object oriented programming are : Data Abstraction Encapsulation Inheritance Polymorphism Q.What are the components of a class? Ans:A class consists of two components data members and methods. Q.What are methods? Ans: Methods are functions associated with the class. They are able to access even private data members. Q.What is the significance of class keyword in C++/Java? Ans: The keyword class (in C++ and Java) specifies an Abstract Data Type (ADT). ADTs expose operations that provide a higher level functionality, and the lower level implementation details are isolated and hidden from the users of the class. Q.What is the difference between source and escape sequences? The Ans: source text is created with the help of source characters. These are interpreted at execution time. The values of these characters are implementation defined. Q.What are tokens? Ans: The smallest individual units in a program are called tokens. Q.What are the types of tokens? Ans: C++ has the following tokens are : Keywords Identifiers Constants (literals) Punctuators (Separators) Operators Q.What is an object? Ans: An object is an instance of a class. It can be uniquely identified by its name and it defines a state, which is represented by the values of its attributes at a particular point in time. Q.What is class? Ans: A class is a collection of objects. A class may be defined as a group of objects with same operations and attributes. The class is a key word in C++ programming. The user deals with classes instead of dealing with various individual objects. Q.What is the difference between private and public class? Ans: The Private access means that only associated functions can only access the data. The Public access means that data can be accessed by other objects of the program. Q.What is a function? Ans: A function is a subprogram that acts on data and returns a value. A function can be invoked from the other parts of the program. Q.What are the types of function? Ans: Functions are of two types are : Built in functions User defined functions Q.What are class members? Ans: A class has members which consist of data members, the constructor, function, destructor functions and member functions. Q.What are the advantages of OOPs? Ans: Object Oriented Programming has the following advantages over conventional approaches : OOP provides a clear modular structure for programs which makes it good for defining abstract data types where implementation details are hidden and the unit has a clearly defined interface. OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones. OOP provides a good framework for code libraries where supplied software components can be easily adapted and modified by the programmer. This is particularly useful for developing graphical user interfaces. Q.What are the applications of OOP? Ans: Real time system Object oriented databases Neural network and parallel processing Q.What is the difference between class and objects? Ans: Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects. A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don’t change. Q.What is static class member? Ans: A static data member has a property that all instances of the containing class share this one data member. Q.What are methods and fields? Ans: A class can have members. Methods and fields are two important members of classes. Member functions are known as methods and data members are known as fields. Q.What is an array? Ans: An array is a collection of identical data objects which are stored in consecutive memory locations under a common heading or a variable name. In other words, an array is a group or a table of values referred to by the same variable name. The individual values in an array are called elements. Array elements are also variables Q.What is a character array? Ans: The procedure for declaring character array is almost the same as for other data types such as integer or floating point. One can declare the character array by means of alphanumeric characters. Q.Define Encapsulation? Ans: The wrapping up of data and functions into a single unit is known as data encapsulation. Encapsulation means combining data and related functions that use that data together and providing it as a logical entity. Q.What are access specifiers? Ans: Access specifiers determine the accessibility of a class member. In general, there are three important access specifiers : Public Private Protected Q.What is inheritance? Ans: The mechanism of deriving a new class (derived) from an old class (base class) is called inheritance. It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance is the process by which objects of one class acquire properties of objects of another class. Q.What is polymorphism? Ans: Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program.It allows us to have overloading of operators so that an operation can exhibit different behaviours in different instances. Q.What is abstraction? Ans: Abstraction means hiding internal implementation details. Q.What is function overloading? Ans: Function Overloading more than one method with the same name but different type of parameters and/or number of parameters can be defined. Depending on the actual number and/or static type of the parameters used, the compiler will resolve the call to the correct method. Q.What are the types of polymorphism? Ans: Polymorphism can be broadly classified as Compile time polymorphism Run time polymorphism Q.What is the difference between compile time and run time polymorphism? Ans: Function overloading, operator overloading,and parametric types (templates in C++ or generics in Java) are done at compile time. Dynamic binding (virtual functions) is runtime polymorphism. Q.What is the difference between an identifier and a keyword? Ans: Identifier : These are the fundamental building blocks of a program and are used to give names to variables, functions, arrays, objects, classes etc. Keyword : These words are reserved to do specific tasks and must not be used as normal identifier names. Q.What is meant by type conversion? Ans: The process in which one pre defined type of expressions is converted into another type is called conversion. Q.What is difference between C++ and Java? Ans: C++ has pointers Java does not Java is the platform independent as it works on any type of operating systems Java has no pointers where c ++ has pointers Java has garbage collection C++ does not. Q.What is the difference between division and modulus? Ans: Division(/) operator is used to divide the value and return the quotient value whereas Modulus(%) return the remainder value. Q.What is object composition? Ans: In composition, one class has an instance of another class as a data member. In OOP, this relationship is also known as a object composition. Q.What are frameworks? Ans: Frameworks provide domain specific inheritance hierarchies that are meant for rapid application development in that domain. Q.Define Message Passing? Ans: Objects communicate between each other by sending and receiving information known as messages. A message to an object is a request for execution of a procedure. Message passing involves specifying the name of the object, the name of the function and the information to be sent. Q.What are concrete classes? Ans: Concrete classes can be instantiated (in other words, objects can be created from concrete classes). These classes have no abstract methods. Concrete classes are a logical complement of abstract classes. Q.What is the use of scope resolution operator? Ans: A variable declared in an inner block cannot be accessed outside the block. To resolve this problem the scope resolution operator is used. It can be used to uncover a hidden variable. This operator allows access to the global version of the variable. Q.What are adaptor class? Ans: Adaptor classes modify the existing interface of an existing class and provide a new interface. In other words, an adapter class adapts a class for a specific purpose. Q.What are monomorphic and polymorphic classes? Ans: Classes that do not have any virtual functions (runtime polymorphism) are known as monomorphic classes. The classes that have virtual functions (or virtual base classes) and are designed for making use of runtime polymorphism are known as polymorphic classes. Q.What is namespace? Ans: The C++ language provides a single global namespace.Namespaces allow to group entities like classes, objects and functions under a name. Q.What is the use of default constructor? Ans: A constructors that accepts no parameters is called the default constructor.If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A(). This constructor is an inline public member of its class. The compiler will implicitly define A::A() when the compiler uses this constructor to create an object of type A. The constructor will have no constructor initializer and a null body. Q.What is the difference between c &c++? Ans: c++ ia an object oriented programing but c is a procedure oriented programing. c is super set of c++. c can’t suport inheritance,function overloading, method overloading etc. but c++ can do this. In c program the main function could not return a value but in the c++ the main function shuld return a value. Q.What are class libraries? Ans: A class library is a set of reusable classes meant for providing a specific functionality (such as utility, networking, or user-interface related classes) that can be readily used by the application. Q.What is a dangling pointer? Ans: A dangling pointer arises when we use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the dynamically allocated memory block after it is freed. Q.What is the difference between shallow and deep copy? Ans: Shallow copy involves bit wise copy of the contents of one object into another object of the same type. A copy constructor and assignment operator provided by the compiler by default does shallow copy. Shallow copies create a problem when there are fields of pointer or reference type. In this case, the addresses are directly copied to another object and thus two different objects have fields pointing to the same objects. When one object is destroyed, the pointers/references in the other object become dangling pointers/references, which is dangerous. Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of one object will not affect the other object. Typically, we provide our own copy constructor and assignment operator implementations for doing deep copy of objects. Q.What is a pointer? Ans: A pointer is a variable which holds a memory address within. Each variable is located at a particular position in the memory which is known as Address. The address can be stored in a pointer. A program accesses the value in the address stored in the pointer by using indirection operator. Q.What is an expression? Ans: An expression is any statement which is composed of one or more operands and returns a value. It may be combination of operators, variables and constants. Q.What are the types of expressions? Ans: There are three types of expressions are : Constant Expressions Integral Expressions Logical Expressions Q.What are the types of conversion? Ans: There are two types of conversion are : Implicit (Automatic) Conversion Explicit Conversion Q.What is the difference between implicit and explicit conversion? Ans: When data types are mixed in an expression, the conversion is performed automatically. This process of automatic conversion is called implicit conversion. Explicit Expressions are user defined expressions. C++ provides type casting facility. The expression can be converted into a specific type. Q.What are the advantages of pointer? Ans: The pointer has the following advantages. It allows to pass variables, arrays, functions, strings and structures as function arguments. A pointer allows to return structured variables from functions. It provides functions which can modify their calling arguments. It supports dynamic allocation and deallocation of memory segments. With the help of a pointer, variables can be swapped without physically moving them. It allows to establish links between data elements or objects for some complex data structures such as linked lists, stacks, queues, binary trees and graphs. A pointer improves the efficiency of certain routines. Q.What is pointer operator? Ans: A pointer operator can be represented by a combination of * (asterisk) with a variable. Q.What is meant by conditional expression? Ans: The conditional expressions are mainly used for decision making. In the subsequent sections, the various structures of the control statements and their expressions are explained. The following statements are used to perform the task of the conditional operations. if statement if else statement switch case statement Q.What are the types of comments? Ans: C++ allows us to add two types of comments are : Single line comments Multi line comments Q.What is the difference between single line and multiple line comments? Ans: A single line comment starts with the character sequence ("//"), i.e. the two forward slashes and ends with a newline character. A multi line comment starts with the character sequence ("/*"), i.e. a forward slash followed by an asterisk and ends with the character sequence ("*/"), i.e. an asterisk followed by a forward slash. Q.What is meant by two dimensional array? Ans: A two dimensional array may be visualized as a table consisting of ows and columns. Each cell of the table will denote an array element. Q.What is meant by multi dimensional array? Ans: Multidimensional arrays are arrays with more than one dimension. An array may consist of any number of dimensions, of course, subject to the restrictions put by a compiler implementation within the scope of language specifications. Q.What are the types of built in data types? Ans: The built in data types available in C++ are : Integral type Floating type Void Q.Define literals? Ans: Literals are often referred to as constants. A constant is an entity with a fixed value. Literals can be divided into characters, string, integer numbers and floating point numbers. Q.What are the types of literals in c++? Ans: C++ there are several types of literals : Integer constants Character constants Floating Point constants String constants Q.What is the use of sizeof() operator? Ans: The sizeof () operator is used to find the size of a variable or the sizeof a data type in terms of the number of bytes. Q.What is copy constructor? Ans: What is copy constructor? Q.What is default constructor? Ans: A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. Q.What is static variable? Ans: Static variables are defined within a function and they have the same scope rules of the automatic variables but in the case of static variables, the contents of the variables will be retained throughout the program. Q.What is register variable? Ans: Automatic variables are stored in the memory. As accessing a memory location takes time (much more time than accessing one of the machine's registers), one can make the computer to keep only a limited number of variables in their registers for fast processing. Whenever some variables are to be read or repeatedly used, they can be assigned as register variables. Q.What is the use of keyword register? Ans: The keyword register is used to declare that the storage class of the variable is a register type. Q.What is the difference between break and continue statement? The break statement is used to terminate the control from the loop statements of the case-switch structure. The break statement is normally used in the switch case loop and in each case condition, the break statement must be used. If not, the control will be transferred to the subsequent case condition also. The continue statement is used to repeat the same operations once again even checks the error. Q.What are the types of errors in c++? Ans: There are four types of errors are : Compiler errors Linker errors Runtime errors Logical errors Q.What is string? Ans: String is a series of characters. The string is enclosed within double quotes. A string is used to write or store messages. ″HELLO″ Q.What is the difference between errors and debugging? Ans: Errors may be made during program creation even by experienced programmers also. Such type of errors are detected by the Compiler. Debugging means removing the errors. Q.What is a scope resolution operator? Ans: The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same name in the local scope. Q.What is multiple inheritance? Ans: A class can inherit properties from more than one class which is known as multiple inheritance. Q.What is cast operator(())? Ans: The cast operator helps to force an expression to be of a specific type by using (} cast operator. Q.What is conditional operator( ?:)? Ans: The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Q.What is comma operator(,)? Ans: The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. Q.What is recursive function? Ans: A function which calls itself directly or indirectly again and again is known as the recursive function. Recursive functions are very useful while constructing the data structures like linked lists, double linked lists and trees. There is a distinct difference between normal and recursive functions. Q.What is the difference between goto and unconditional goto? Ans: The goto statement is used to alter the program execution sequence by transferring the control to some other part of the program. The unconditional goto statement is used just to transfer the control from one part of the program to the other part without checking any condition. Normally, a good programmer will not prefer to use the unconditional goto statement in his program as it may lead to a very complicated problem like a never ending process. Q.What is the difference between class and structure? Ans: By default, the members ot structures are public while that tor class is private. Structures doesn't provide something like data hiding which is provided by the classes. Structures contains only data while class bind both data and member functions. Q.What are design patterns? Ans: Design patterns are reusable, extensible solutions to common design problems faced by designers of object-oriented systems. Design patterns are language neutral and are of a higher level of abstraction than code. Q.What is the difference between the terms overloading and overriding? Ans: The term overriding refers to providing an alternative function definition of a virtual function in a derived class. Overriding is useful for runtime polymorphism. With overloading, more than one method definition with the same name (but with different types/number of arguments) are provided, whereas in overriding, the methods with the same name are provided with alternative definition in derived class. Q.What is friend function? Ans: The function declaration should be preceded by the keyword friend.The function definitions does not use either the keyword or the scope operator ::. The functions that are declared with the keyword friend as friend function.Thus, a friend function is an ordinary function or a member of another class. Q.What is a call by reference? Ans: A function call mechanism that passes arguments to a function by passing the addresses of the arguments. Q.What is the call by value? Ans: A function call mechanism that passes arguments to a function by passing a copy of the value of the arguments. Q.What is inheritance? Ans: The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as the base class and the new one is called the derived class or the sub class. Q.What are the types of inheritance? Ans: Single inheritance Multiple inheritance Multi level inheritance Hierarchical inheritance Hybrid inheritance Q.What is method overriding? Ans: Method overriding is a mechanism in which the sub class method overrides the base class method. If the same function name is present in both the base class and the sub class then the sub class method overrides the base class method. Q.What is inline function? Ans: Inline function is defined as a function definition such that each call to the function is in effect, replaced by the statements that define the function. It is expanded in line when it is invoked. Q.What are concrete classes? Ans: Concrete classes can be instantiated (in other words, objects can be created from concrete classes). These classes have no abstract methods. Concrete classes are a logical complement of abstract classes. Q.What is class cohesion? Ans: Cohesion indicates how closely the members are related to each other or how strongly the members depend on each other in a class. Highly cohesive classes or modules indicate good design. Q.What is class coupling? Ans: Coupling means how two (or more classes) are dependent or strongly related to each other. When two classes are tightly coupled, change in one class usually requires change in the other class. Therefore, tightly coupled classes are not recommended. Q.What is the difference between local and global variable? Ans: Local variables Identifiers declared as label, const, type, variables and functions in a block are said to belong to a particular block or function and these identifiers arc known as the local parameters or variables. Local variables are defined inside a function block or a compound statement. Global variables are variables defined outside the main function block. These variables are referred by the same data type and by the same name through out the program in both the calling portion of a program and in the function block. Whenever some of the variables are treated as constants in both the main and the function block, it is advisable to use global variables. Q.What are the types of type modifiers? Ans: There are four types of type modifiers are : Signed Long Unsigned Short Q.What do you mean by pure virtual functions? Ans: A pure virtual member function is a member function that the base class forces derived classes to provide. Any class containing any pure virtual function cannot be used to create object of its own type. Q.What is the types of storage class specifiers? Ans: There are four storage class specifiers supported by C++. They are : extern static register auto Q.What is STL? what are the components of stl? Ans: A collection of generic classes and functions is called as Standard Template Library (STL).The stl components are Containers Algorithm Iterators
Continue reading
Dotnet Interview Questions
Q.What is .Net Framework? Ans: NET Framework is an important integral component in .NET software. .NetFramework is a runtime environment,which we can use to run .net applications. Q.What is Visual Studio.Net? Ans: Visual Studio .NET is a Microsoft-integrated development environment (IDE) that can be used for developing console applications, Windows Applications, Web Applications, Windows Service, Web service.. And so on... Q.Difference between .Net Framework and VisualStudio.Net? Ans: .NET FRAMEWORK VISUAL STUDIO .NET 1. It is a run- time environment, which 1. It is a development environment, we can use to run applications. which we can use to develop applications. 2. It is required for .net developers and 2. It is required for only .net developers. .net application end users 3. It is a free ware which we can 3. It is not free way which we have to download from Microsoft Website. purchase from Microsoft. Q.What is CLR? Ans: CLR stands for Common Language Runtime, it is .net execution. CLR is a common execution engine for all .NET Languages that means every .NET language application has to execute with the help of CLR. Q.Explain .net application Execution process? Diagram for .net application execution process : Ans: .Net application Execution process can be divided into 2 steps: Step1. Converting HIGH level language code into MSIL (Microsoft Intermediate Language) with the help of language compilers because .Net execution engine (CLR) can understand only MSIL code. Step2. JIT (JUST-IN-TIME) compiler will convert MSIL code to NATIVE code because operating system can understand only NATIVE code or MACHINE code. Q.What is JIT Compiler? Ans: JIT (JUST-IN-TIME) Compiler will convert MSIL (Microsoft Intermediate Language) code to Native code because operating system can understand only Native code or machine code. Q.What is CLS? CLS (Common Language Specifications) is a set of common language standard defined by the Microsoft for all .NET Languages. Every .NET Language has to follow CLS Standards. Whenever a Programming Language wants to recognize as .NET Language then it has to follow CLS. Q.What is CTS? Ans: CTS (Common Type System) is a subset of CLS. It is a set of common based data types defined by Microsoft for all .NET Languages. Every .NET Language has to map their data types with CTS types. Q.What is MSIL Code? Ans: Microsoft Intermediate Language (MSIL), is one of the Core component of the .NET Framework. Any .NET source codes written in any .net supportive language (C#, VB.net etc), when compiled are converted to MSIL. This MSIL, when installed or at the Runtime, gets converted to machine code. The Runtime conversion of MSIL code to the machine code is handled by a component called as the Just In Time (JIT) Compiler. Q.Explain the role of Garbage collector? Ans: In .NET, MEMORY MANAGEMENT is handling by GARBAGE COLLECTOR (GC). GC is an integral part of CLR. To perform memory Management GC will do 2 duties. 1.Allocating the Memory ->When new object is created by application garbage collector will allocate memory for that object with in Managed heap. De-Allocating the Memory:- ->When an object is not using by the application garbage collector will recognize it as unused object..and garbage collector will destroy unused objects according to generation algorithm. Q.What is Managed Code and Unmanaged Code? .Net application may contain 2 types of codes. A) Managed Code B) Unmanaged Code Ans: Managed code: The code which is taking the help of CLR for execution is called as managed code. Example for Managed Code:- All .net languages code is managed code. VB.Net code, C#.Net code…etc Unmanaged code: - The code which is not taking the help of CLR for execution is called as Unmanaged code.. Example for Unmanaged Code:- In .net application non .net code is unmanaged code.. VB Code, VC++ Code… Note: - .net application can contain non .net code. C#.NET Q.Why C#.Net? Ans: To develop any type of application by using .NET we require one .NET LANGUAGE to write the business logic of that application. Q.Explain about primitive data types? Ans: In C#.NET, according to the type of the data and size of the data, data types are classified into 5 types. They are— Numerical Data types Signed Numerical data types: sbyte, short, int, long b.Unsigned Numerical data types;-byte, ushort, uint, ulong 2.Floating float, double, decimal 3.Character related Data types a) Char 4.Logical Data Types a) bool General data Types string object These data types are called as PRIMITIVE DATA TYPES. Q.What is the MaxValue and MinValue? Ans: MaxValue and MinValue are predefined constants, which are members of every primitive data type structure except bool. Using this Constant we can get the MINIMUM value and MAXIMUM value of a data type. Q.Difference between value types and Reference types? Ans: VALUE TYPES REFERENCE TYPES 1.In value types, data will storing in 1. In this, Data will be storing in HEAP STACK MEMORY MEMORY. 2. Value type variable can contain the 2. Reference type variable will contain actual data. the address of the data. 3. In primitive data types except General 3. In primitive data types only General data types are called VALUE TYPES. data types will come under They are Numerical, Floating, Character REFERENCE TYPE. and Logical. Ex: Int, Long, Char EX: String, Object 4. Structures and Enums are value types 4. Class, interface, delegates come under this. Q.When we will go for signed data types and when we will go for unsigned data types? For Example:- When we will go for sbyte When we will go for byte Ans: Whenever we want to allow both positive and negative values then we will go for signed data types. Whenever we want to allow only positive values then we will go for unsigned data types. Here sbtye is a signed data type and byte is an unsigned data type. Q.What is the output? static void Main (string args) { Char c='a'; int j=c; Console.WriteLine (j); Console.ReadLine (); } Output: 97 Q.Can I assign 1 or 0 into bool variable? static void Main(string args) { bool b = 1; Console.WriteLine(b); Console.ReadLine(); } Ans: No Q.What is the output ? static void Main(string args) { bool b = true; Console.WriteLine(b); Console.ReadLine(); } OUTPUT: True Q.Can we assign null value into value type variable? Ans: No. but we can assign null values into reference type variable. Q.How to assign null value into value type variable? Ans: We have to go for NULLABLE VALUE TYPES. Syntax: ? =NULL; Q.When we will declare particular variable as nullable type? Ans: Whenever an input is an optional that means not compulsory then we can declare particular variable as NULLABLE TYPES. Q.What is implicit typed variable when we will go for implicit typed variable? Ans: Using var keyword we can declare IMPLICIT TYPED VARIABLE. IMPLICIT TYPED VARIABLE can have any data type value and this variable will be converting into particular data type based on the value which is assigning. Whenever we r unable to expect the type of value which is going to assign. Q.What is the difference between GetType() and typeof()? Ans: typeof() GetType() 1. It will return the given data type 1. It will return the given variable base type data type base type 2. It is a operator 2. It is a method Q.What is the output? static void Main(string args) { var a = 10; var b = 10.5; Console.WriteLine(a.GetType()); Console.WriteLine(b.GetType()); Console.ReadLine(); } OUTPUT: System.Int32 System .Double Q.What is implicit type casting? When we will go for explicit type casing? Ans: IMPLICIT TYPE CASTING: - Converting from Smaller size data type to bigger size data type is called as IMPLICIT TYPE CASTING. When EXPLICIT TYPE CASTING: - The type casting which is not possible by using implicit type casting then we have to go for EXPLICIT TYPE CASTING. Q.Difference between Parsing and Converting? Parsing Converting 1. Using parsing we can convert from 2. Using converting we can convert only string data type to any other data from any data type to any other type except object data type. data type. Q.What is the output? static void Main(string args) { string s1 = "1234"; string s2 = "1234.5"; string s3 = "rama"; string s4 = null; string s5 = "12321321321323232132132332"; int res; res = int.Parse(s1); Console.WriteLine(s1); //res = int.Parse(s2); //res = int.Parse(s3); //res = int.Parse(s4); //res = int.Parse(s5); Console.ReadLine(); } OUTPUT: 1234 Q.Difference between int.Parse() and Convert.Toint32()? Ans: Int.Parse() Convert.ToInt32() 1.Using this we can convert from only 1.Using this we can convert from any STRING to INT. data type value into INT. 2.When we are parsing if the string 2.When we are converting if the string variable contains NULL value then this variable contains NULL value then it parsing technique will throw argument will convert that NULL as ZERO. NULL EXCEPTION. Q.What is Boxing and Unboxing? Ans: BOXING: - It is the process of converting from VALUE type to REFERENCE type. UNBOXING: -It is the process of converting from REFERENCE type to VALUE type. EX: converting from object to int. Q.What is the difference between Convert.ToString() and Tostring()? Ans: Convert.ToString() handles NULL values even if variable value become NULL. Tostring() will not handles NULL values it will throw a NULL reference exception error. Q.What is the difference between string and StringBuilder? Ans: STRING STRING BUILDER 1. When we implement modifications to 1. When we implement modifications to the existing String object within the existing StringBuilder object will not memory it will create a new object. create new copy of object instead of that Because string is IMMUTABLE. it will modify the existing object. Because StringBuilder is MUTABLE. 2. String will allocate a new memory 2. StringBuilder class will have a whenever we concatenate the string method Append() this method is used to Value insert the new value on the existing value. EX: String s1=‖sathya‖; so the usage of string builder is more S1=s1+‖Tech‖; efficient in case of large amount of Console.WriteLine(s1); string EX: StringBuilder s1=new StringBuilder(―sathya‖); S1.Append(―Tech‖); Console.WriteLine(s1); 3. It will occupy more memory, it will 3. It will occupy less memory, it will decrease the performance of improve the performance of applications. applications. For Example:- static void Main(string args) { string s1 = "Hydera"; Console.WriteLine(s1.GetHashCode()); s1 = s1 + "bad"; Console.WriteLine(s1.GetHashCode()); Console.WriteLine(s1); StringBuilder s2 = new StringBuilder("Hydera"); Console.WriteLine(s2.GetHashCode()); s2.Append("Bad"); Console.WriteLine(s2.GetHashCode()); Console.ReadLine(); } Q.What is Error, Bug and Defect? Ans: Error --> Which comes at the time of development. Bug --> Which comes at the time of testing. (Pre-Release) Defect --> Which comes in Production. (Post-Release) Q.Why class and object? Ans: CLASS: To achieve ENCAPSULATION, as well as for modularity OBJECT: To allocate memory for instance variables & to store the address of instance method. Q.When we will go for instance variable? Ans: Whenever we required a filed for multiple objects with the different values, then particular variable we will declare as INSTANCE VARAIBLE. Q.When we will go for static variable? Ans: According to the requirement whenever the value is common for all the objects then particular variable will declared as STATIC. Q.Difference between instance variable and static variable? Ans: INSTANCE VARIABLE STATIC VARIABLE (or) (or) NON-STATIC VARIABLE CLASS VARIABLE 1. A variable which is declared within 1. A variable which is declared inside the class and outside the method the class and outside the method by WITHOUT using STATIC keyword is using STATIC keyword is called as called as INSTANCE VARIABLE. STATIC VARIABLE. 2. Instance variable will create multiple 2. Static variable will create only once times for every object creation. when the class is loading. 3. Instance variable value will be 3.satic variable value will be same for differs from one object to another every object object. Q.When we will go for readonly? Ans: Whenever filed is required for every object with the different value, but the value not required change. Ex: - EmpNo Q.When we will go for static readonly? Difference between static variable and static read only? Ans: Whenever we want to have common value for every object and value should not be changed forever we will go for static readonly. STATIC VARIABLE STATIC READONLY 1. Value will be common for all objects 1. value be common for all objects but but value can be changed value can’t be changed Q.Difference between constant, static and read-only? Ans: CONSTANT STATIC VARIABLE READONLY 1.const keyword is used 1. static keyword 1.Readonly keyword 2. Its value cannot be 2. Its value can be 2.Its value cannot be changed changed modified 3. By default constant is 3. For static variable, 3.By default Non-static static that means we don’t programmer has to require to use any static declare as static keyword 4. Constant value should 4. Static variable can be 4. Readonly can be be initialized at the time initialized at the time of initialized at the time of of declaration which we declaration as well as we declaration or runtime cannot initialize in can initialize in runtime (only within the runtime. within the static constructor) constructor. Q.When the memory will be allocated for instance variable and static variable? Ans: STATIC VARIABLE: - At the time of class is loading, memory will be allocated for static variable. INSTANCE VARIABLE: - When the object is created the memory is allocated for instance variable. Q.What is the purpose of constructor and method? Ans: Purpose of Constructor: To initialize at the time of creating an object for Instance variable as well as at the time class is loading for static variable. Purpose of Method: To perform operations on state. Q.When we will go for instance method? Ans: To perform operations on Instance variables. Q.When will go for static method? Ans: While defining method if that method is not required to access instance variables we will define particular method as static method. Q.If a class is having one static constructor and one instance constructor which constructor will call first? Ans: First control will execute STATIC constructor because CLASS will load first then OBJECT will create. Q.Why static constructor is a parameter less constructor? Ans: Static constructor executes at the time of class loading. There is no need to pass values explicitly, so it doesn't have parameters. Q.What are the default access modifiers? Ans: Default access modifier of class members is private. Default access modifier of a class is internal. Q.What is the super class for all.net classes? Ans: OBJECT Class Q.When object class constructor is calling? Ans: When we call instance constructor first it will call object class constructor. Q.How constructor calling mechanism will work? Ans: Constructor is calling from BOTTOM to TOP, but it is executing TOP to BOTTOM. Q.What is this and base? Ans: this: It is a keyword which is representing current class object or instance. Using this we can invoke current class instance members. Base: It is a keyword which is representing the super class instance. Using base keyword we can access super class instance members from derived class or sub class. Q.How to invoke super class constructor? Ans: base() Q.How to invoke current class constructor? Ans: this() Q.What is constructor overloading? Ans: Implementing multiple constructors within a single class with different signature (Different no. of parameters or Type of parameters or Order of parameters) is called CONSTRUCTOR OVERLOADING. Q.What is constructor chaining? Ans: Whenever one class constructor is invoking another class constructor which is called as constructor chaining. For this we can use Base() Q.Why Main() is static? Ans: When we run the application CLR has to invoke the Main(). If the Main() is a instance method again it requires object. To overcome this Main() is defined as static method. Q.Main() and static constructor in same class which one will execute first? Ans: STATIC CONSTRUCTOR Q.What is passing parameter mechanism? How many types? Ans: Passing a value to a function is called as PASSING PARAMETER MECHANISM. C#.Net will support passing parameter mechanism in 3 ways. 1. Call by value (or) Pass by value Call by reference (or) pass by reference Call by Out (or) pass by out Q.When call by value, call by reference, call by out? Ans: CALL BY VALUE: Whenever we want to pass some value to a function and the modifications are not expecting to reflect back to actual parameter then we will pass it as CALL BY VALUE. CALL BY REFERENCE: Whenever we want to pass some value and we are expecting the modifications should be reflected back to actual paramer then we will pass it as CALL BY REFERENCE CALL BY OUT: Whenever we don’t want to pass any values but we are expecting back the modifications then we will pass particular parameter as CALL BY OUT. Q.Difference between call by ref and call by out? Ans: CALL BY REFERENCE CALL BY OUT 1.Ref keyword is used 1.Out keyword is used 2. Ref parameter should have some 2. Out parameter is not required to have value. value. 3. Whenever we want to pass some 3. Whenever we don’t want to pass any value and we are expecting the values but we are expecting back the modifications should be reflected back modifications then we will pass then we will pass it as CALL BY particular parameter as CALL BY OUT REFERENCE Q.What are oops principles? Ans: Encapsulation Abstraction Inheritance Polymorphism Q.What is Encapsulation? How can we achieve? Ans: Wrapping STATES and BEHAVIOURS are called as ENCAPSULATION. Or Binding VARIABLES and METHODS is called as ENCAPSULATION. By implementing class we can achieve ENCAPSULATION. 51) What is abstraction? How can we achieve? Abstraction means HIDING. Abstractions are 2 types. 1) data abstraction:- Hiding unwanted data is called as data abstraction 2) Method abstraction:- Invoking required method and hiding unwanted method is called as method abstraction. With the help of FUNCTION OVERLOADING we can achieve Method ABSTRACTION. Q.What is Inheritance? Types of Inheritance? Ans: Inheriting or deriving members from one class to another class is called as INHERITANCE. C#.Net will support 5 types of Inheritance. They are Single Inheritance Multi-level Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance. Q.Is C#.Net will support multiple Inheritance? Ans: In C#.NET multiple inheritances is not possible by using classes, which is possible with the help of INTERFACES. Q.What is sealed class? When we will go for sealed class? Ans: While defining a class, if we have used ―sealed‖ keyword then that class can be called as SEALED CLASS. It cannot be inherited. Whenever we want to restrict to inherit a class we can go for sealed class. Q.Difference between static class and sealed class? Ans: STATIC CLASS SEALED CLASS 1. It can contain only STATIC 1. It can contain both STATIC and members. INSTANCE members. 2. It cannot be instantiated. 2. It can be instantiated(we can create object for sealed class) 3. STATIC keyword is used. 3. SEALED keyword is used. 4.Can’t be inherited 4. Can’t be inherited. Difference between class and structure? Ans: CLASS STRUCTURE 1. It is reference type 1. It is value type 2. When we create an object for class it 2. When we create an object for will be allocated into HEAP structure it will be allocated into MEMEORY STACK MEMEORY 3.To define a CLASS, class keyword is 3. To define a STRUCTURE, struct used keyword is used 4. It will support inheritance 4. It will not support inheritance 5.Instance field intailzers are allowed 5. Instance field intializers are not allowed. 6.It can contain explicit default 6.It can’t contain explictit default constructor constructor 7. We can’t create an object for class 7. We can create an object for structure with out using new keyword. with out using new key word if it is not having instance varibles. 8. We can have static, abstract, sealed 8. We can’t have static, abstract, sealed class. structure. 9.We can implement overloading and 9. We can implement overloading with overrding with in class in structure, but we can’t implement overriding with in structure. Q.Why property? Ans: 1.To assign value to a class level variable after creating object to retrieve the value from class level variable individually. Property will provide SECURITY to variable data. Property will provide VALIDATION FACILITY for variable data at the time of Assigning. Q.Difference between constructor and property? Ans: CONSTRUCTOR PROPERTY 1. It is used to initialize the instance 1. It is used to assign value to class level variables at the time of creating an variables as well as can retrieve the object. value from class level variables. Q.What is polymorphism? Types of polymorphism? Ans: Polymorphism means one name many forms. Implementing multiple functionalities with the same name is called POLYMORPHISM. It is of 2 types: Static Polymorphism (or) Compile Time Polymorphism Dynamic Polymorphism (or) Runtime Polymorphism Q.What is static polymorphism and dynamic polymorphism? Ans: STATIC POLYMORPHISM: A method which will bind at compile time will execute in runtime is called as static polymorphism or early binding or compile time polymorphism DYNAMIC POLYMORPHISM: A method which will bind at compile time will not execute, instead of that a method which will bind at runtime will execute is called as RUNTIME POLYMORPHISM (or) DYNAMIC POLYMORPHISM is nothing but LATE BINDING. Q.What is function overloading? When we will go for function overloading? Ans: FUNCTION OVERLOADING: Having multiple methods with the same name but a different no. of arguments or different type of arguments or different order of arguments in a single class or in a combination of base and derived class. WHEN: Whenever we want to implement same method with the different functionalities then we have to go for FUNCTION OVERLOADING Q.Can we overload static methods? Ans: YES. Q.What is function overriding? When we will go for function overriding? Ans: FUNCTION OVERRIDING: Having multiple methods with the same name and with the same signature in a combination of base and derived class. WHEN: Whenever we want to implement a method in multiple classes with the different behavior we can go for method overloading. Q.What is method hiding? Ans: Hiding the SUPER CLASS method within the SUB CLASS by using new keyword as called as METHOD HIDING. Q.Can we override static methods? Ans: NO. We cannot define static method as VIRTUAL, OVERRIDE and ABSTRACT. Because FUNCTION OVERRIDING is depending on OBJECT or INSTANCE Q.What is the output? class bc { internal virtual void display() { Console.WriteLine("bc display"); } } class dc : bc { internal override void display() { Console.WriteLine("dc display"); } } class tc : bc { internal new void display() { Console.WriteLine("tc display"); } } class Program { static void Main(string args) { bc b = new dc(); b.display(); = new tc(); b.display(); Console.ReadLine(); } } OUTPUT: dc display bc display Q.Difference between function overloading and function overriding? Ans: FUNCTION OVERLOADING FUNCTION OVERRIDING 1. Multiple methods with the same name 1. Multiple methods with the same name and different signature. and same signature. 2. It can implement in a single class and 2. To implement override we should go combination of base and derived class. for base and derived class, we cannot implement in single class. 3. No keywords are used 3. virtual in base class and override in derived class 4. Both functions return types can be 4. Both functions return types should be same or differ. same. 5. It is a compile time polymorphism 5. It is a Run time polymorphism 6. We can overload static methods 6. We cannot override static methods 7. Constructors can be overload. 7. Constructors cannot be overload. Q.When we will go for abstract class? Ans: Whenever we want to implement some methods in current class and some methods we want declare in current class which we want to implement in future classes then we have to declare that class as abstract class. Q.When we will go for interface? Ans: Whenever we want to declare all the members in current class and want to implement all the members in future classes then we will declare particular class as interface. Q.Why we can’t create object for abstract class and interface? Ans: Not required Because is abstract class is a partial implemented class and interface has no implementation. Even though these abstract class abstract members and interface members should implement within the derived classes. Due to that reason we don’t required to create object for abstract class and interface. We will create an object for derived class and using that object we can access abstract members and interface members. Q.Difference between abstract class and interface? Ans: ABSTRACT CLASS INTERFACE 1. It is a collection of abstract members 1. It is collection of abstract members, and non-abstract members. that means by default interface members are abstract. 2. While defining an abstract class, 2. While defining an interface, interface abstract keyword is used. keyword is used. 3. It is partially implemented 3. No implementation 4.we can implement with in a method, 4. We can’t implement a property and property(Normal method or Normal method. property) 5.it can contain fields 5.it can’t contain fields 6.it can contain constructor 6.it can’t contain constructor 7. While implementing abstract class 7. While implementing interface members with in the derived class we members with in the derived class we have to use override keyword. don’t required to user override key word. Q.Benefits of oops? Ans: 1. Reusability Extensibility Re-implementation Modularity Easy to modify Easy to implement real world programming Security Q.What is an exception? Ans: Run time error is nothing but and exception. Q.Why exception handling mechanism? Ans: To handle runtime error, when a runtime error is occurred to avoid abnormal termination by displaying user-friendly error messages. Q.What code we will write within try, catch and finally blocks? Ans: TRY BLOCK: We have to write the statements which may throw an error. CATCH BLOCK: We will write the statements to display user friendly messages to the user to give more clarity to the user regarding error. FINALLY BLOCK: We will write ERROR FREE code or CLEAN UP code that means the statements which we want to execute irrespective of error occurrence. Q.Can we have multiple catch blocks and if yes when we will go for multiple catch blocks? Ans: Yes. Whenever we want to handle multiple errors we have to go for MULTIPLE CATCH BLOCKS. Q.What is super class for all .net exception classes? Ans: Exception class Q.What is a delegate? Types of delegates? Ans: It is similar like C++ function pointer. Delegate object can hold the address of a function and can invoke a function. Delegates are reference types. Delegates are of 2 types Single cast Delegate and Multi Cast Delegate Q.In C# which is called as type safe function pointers? Why? Ans: In C#.Net, DELEGATES are called as TYPE SAFE FUNCTION POINTERS because Delegate declaration should follow the method declaration which is holding by the delegate object. Q.What is language Independency? Is .NET language independent technology? Ans: .Net is supporting for multiple languages. While developing an application by using one .net language we can use another .net language component. For example:- While developing C#.Net application we can use vb.net component. As well as while developing VB.Net application we can use C#.Net component. Due to that reason we can say that .net is a language independent technology. Q.What is an assembly? Types of assemblies? Ans: An Assembly is a unit of code which provides versioning and deployment. Assemblies are of 2 types:- Private Assembly and 2. Shared Assembly Q.Difference between dll and exe? Ans: exe dll 1. exe stands for EXECUTABLE 1. dll stands for DYNAMIC LINK LIBRARY. 2.File extension will be .exe 2.File extension will be .dll Ex;-hello.exe Hello.dll 3.exe file will have an ENTRY point 3.dll file will not have an ENTRY point called main() called main() 4. exe is SELF EXECUTABLE. Exe 4. dll is not a self executable, it is itself is an application. reusable component. It will depend on some other application for execution for execution. 5. Collection of classes which has 5. Collection of classes which is not Main() will produce exe files. having Main() will produce dll files. Ex: .Net Console application Ex: .Net class library project. Q.Difference between private assembly and shared assembly? Ans: PRIVATE ASSEMBLY SHARED ASSEMBLY 1. An assembly which is providing 1. An assembly which is providing services to SINGLE client application at services to MULTIPLE client a time is called as application at a time is called as PRIVATE ASSEMBLY SHARED ASSEMBLY 2. It will create a local copy within 2. It will not create a local copy, it will every client application folder, that local provide services to multiple client copy will provide the services to application from a centralized shared concern client application. folder called GAC. Q.What is GAC? Ans: GAC stands for GLOBAL ASSEMBLY CACHE. IT is a residence for all SHARED ASSEMBLIES. When we install .NET software, GAC folder will create within the following path C:\Windows\Assembly Q.What is strong name? How to create strong name? Ans: It is one of the .NET Framework utility, which is representing with a file called sn.exe. Using this utility we can give a strong name or public key to the given assembly. Strong name or public key will give uniqueness to given assembly among collection of assemblies. Q.How to install an assembly into GAC? Ans: GAC UTILITY: It is represented with a file called GACutil.exe. Using this utility we can install an assembly into GAC folder Syntax:- D:\\gacutil – i (Press enter) Example:- D:\\gacutil – i myassembly.dll (Press enter) Here ―i‖ stands for INSTALLING The above command will install myassembly.dll into GAC folder. Q.What signing assembly? Ans: Informing about created strong name to the assembly is nothing but signing the assembly. Q.What is satellite assembly? Ans: An assembly which we can use to develop multi lingual applications in .net. Q.What are Multilingual applications? Ans: An application that supports for more than one human readable language is known as multilingual application. Q.What is Reflection? Ans: Reflection is used to get the information about an assembly programmatically by writing some code. Q.How to implement Reflection in .net? Ans: System.Reflection System.Type Q.What are smart arrays in C#.Net? Ans: In C#.Net, INDEXERS are called as SMART ARRAYS because accessing array with the help of indexers will be faster. Q.What is enum? What is the default data type of enum? Ans: Enum is a value type. It is a collection of constants that means it is a collection of string constants which are representing collection of integer constants. Int is the default data type of enum. Q.Why generics? Ans: Generics allow us to define type-safe data structures, without committing to actual data types. It means it allows the programmer to decide the type of parameter in RUNTIME or CONSUMPTION TIME. Q.What we are achieving by using generics? Ans: We can avoid function overloading in some level. Q.Can we create normal object for generic class? Ans: NO. We CANNOT create a normal object for Generic class. Q.Can we pass 2 different type values to generic function? Ans: YES. HOW : Class myclass { Internal static void print (Ta, Kb) { } } Class program { Void Main () { Myclass.print (10,‖sathya‖); Console.ReadLine (); } } Q.How many types of collections? Ans: Collections are of 2 types: 1. Normal Collection and Generic Collection Q.What is dictionary? Ans: 1.The Dictionary class is a generic class and can store any data types. 2. It is a collection of Pairs. Each pair will have 2 elements: 1. Key value and 2.Item Value. Every item should be represented with one unique key value. Q.How to add summary to a method? Ans: If we want to add a method comment you can just place your cursor on an empty line above one of your method and insert 3 slashes which will insert a comment block for you to fill out. Q.Can we call message box with in console application. Ans: Yes. Start a new project - File -> New Project -> Console Application -> OK. On Solution Explorer - right click on References and click Add Reference. Scroll down the list until you find "System.Windows.Forms", click it and then click OK Now under all the using _____’s add this to the code window: Now go to the main function MessageBox.Show ("Hello World"); Now go to Debug -> Start without Debugging. Q.what is partial class? Why partial class? Ans: 1. While defining a class, if we have used partial keyword which can be called as PARTIAL CLASS. Partial class will split into multiple class files but the class name will be same but class files names should be differ. WHY: According to the requirement, whenever multiple resources wants to work on single class then we can declare particular class as a PARTIAL CLASS. Ex:- In asp.net Webform1 is a partial class 1) Webform1.aspx:- Here we will write the business logic 2) Webform1.aspx.desgigner.cs:- Here we will write the designing logic. Q.what is a thread? Ans: Thread is an independent execution path, it able to run simultaneously with other execution paths. Q.what is the base class library for threading? Ans: System.Threading Q.How to create thread? Ans: Whenever we want to create a thread, we have to create an object for thread pre-defined class. Thread thr1=new Thread (); Q.How to invoke a thread? Ans: Using thr1.Start (); Start(): It is a pre-defined member method of thread class. Using this method we can invoke or start a thread. Q.What is threadstart()? Ans: 1. Threadstart() is a pre-defined delegate, which is a part of System.Threading base class library. We can initialize a method to thread with the help of ThreadStart(). Q.How to send a thread for sleep? Ans: Using Thread.sleep(), we can send a thread for sleep according to the given time. Sleep() method is used to Block the current thread for the specified number of milliseconds. In other words We can include specific time via thread.sleep() method like as: Thread.Sleep (TimeSpan.FromHours (1)); // sleep for 1 hour Thread.Sleep (1000); // sleep for 1000 milliseconds Q.How to suspend a thread? Ans: Using Suspend() we can suspend the targeted thread. When you call Thread.Suspend() on a thread, the system notes that a thread suspension has been requested and allows the thread to execute until it has reached a safe point before actually suspending the thread. A safe point for a thread is a point in its execution at which garbage collection can be performed. Once a safe point is reached, the runtime guarantees that the suspended thread will not make any further progress in managed code. A thread executing outside managed code is always safe for garbage collection, and its execution continues until it attempts to resume execution of managed code. Q.How to call back suspended thread? Ans: Suspended thread can be called back by using resume(). Q.How to terminate thread? Ans: The Thread.Abort() method is used to start the process of terminating the thread. we are calling this method usually terminates the thread. it raised a System.Threading.ThreadingAbortException in the thread on which it is invoked. Q.what is the scope of protected Internal? Ans: If we declare a class or class member access modifier as protected internal which can be accessed by all the classes of CURRENT PROJECT and DERIVED CLASSES of other projects within that application. Q.How to call Garabge collector? Ans: Using GC.Collect(); The garbage collection class provides the GC.Collect(); which you can use to give your application some direct control over the garbage collector. In general, you should avoid calling any of the collect methods and allow the garbage collector to run independently. Q.Difference between dispose() method and finalize() method? Ans: These are just like any other methods in the class and can be called explicitly but they have a special purpose of cleaning up the object. DISPOSE(): In the dispose method we write clean up code for the object. It is important that we freed up all the unmanaged recources in the dispose method like database connection, files etc. The class implementing dispose method should implement IDisposable interface. A Dispose method should call the GC.SuppressFinalize method for the object it is disposing if the class has desturctor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalize method. FINALIZE(): A Finalize method acts as a safeguard to clean up resources in the event that your Dispose method is not called. You should only implement a Finalize method to clean up unmanaged resources. You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically. Finalize method is called by the GC implicitly therefore you can not call it from your code. Note: In C#, Finalize method cannot be override, so you have to use destructor whose internal implementation will override the Finalize method in MSIL. But in the VB.NET, Finalize method can be override because it does support destructor method. Dotnet Interview Questions Dotnet Interview Questions and Answers ASP.NET Q.What is ASP.Net? Why asp.net? Ans: ASP.NET is a .NET web technology or Server side technology. WHY: To develop a web application by using .Net we have to use a .Net web technology called Asp.Net and a .Net language called C#.Net. Q.What do you mean by server side technology? Ans: 1. The code which is executing within the WEB SERVER is called as SERVER SIDE CODE. Server side code we can implement by using Server side technologies. Ex. ASP, ASP.NET, JSP, PHP and so on Using server side technology we can develop server side web pages. Q.What do you mean by client side technology? Ans: 1. The code which is executing within the WEB BROWSER is called as CLIENT SIDE CODE. Client side code we can implement by using client side technologies. 3. Ex: JavaScript, HTML, CSS Q.What are the programming techniques will be supporting by asp.net? Ans: Asp.net will support 2 Programming Techniques. They are-1. InPage Technique and CodeBehing Technique. Q.Can we convert client side control as a server side control? Can we convert server side control as client side control? Ans: Yes. We can convert Client side control as server side control by adding an ATTRIBUTE called runat=‖server‖. But we cannot convert server side control as client side control. Q.How can you pass values between ASP.NET pages? Ans: Different techniques to move data from one web form to another are: 1. Query string Cookies Session state Application state Cross page postback Context.Handler object Q.What is the difference between Response.Redirect() and Server.Transfer()? Ans: Response. Redirect(): It is used to navigate the user request between multiple web servers. It will not hide the Destination url address. Server. Transfer(): It is used to navigate the user request within the web server. It will hide the Destination url address. Q.Explain about validation controls in asp.net? Ans: There are 6 Validator Controls. They are 1. Requiredfield Control Compare validator Range validator Regular Expression validator Custom validator Validation summary Q.When we will go for custom validator control? Ans: Whenever our validation requirement is unable to achieve with the help of existing validation controls then we have to go for CUSTOM VALIDATOR CONTROL Q.How to invoke server side validation function and how to invoke client side validation function? Ans: Server side validation functions can be invoked by using ASP.NET and Client side validation function are invoked with the help of JavaScript and HTML. Q.How to access information about a user’s locale in ASP.NET? Ans: User’s locale information can be accessed through System.Web.UI.Page.Culture property. Q.What are the life cycle events of asp.net? Ans: Application level, Control level, Page level. Q.What are the Asp.Net page cycle stages? Ans: There are overall 8 stages available for any webpage that will undergo with in server at page life cycle. 1) Page Request 2) Start 3) Page Initialization 4) Load 5) Validation 6) PostBack Event Handling 7) Rendering 8) Unload Q.What are page life cycle events? Ans: 1. Page_PreInit Page_Ini Page_InitComplete, Page_PreLoad Page_Loa Page_LoadComplete Page_PreRender Page_PreRenderComplete, Page_Unload Q.In asp.net page life cycle events which will fire first? Ans: Page_PreInit Q.What is the difference between event and method? Ans: Event will execute for some action i.e called as event firing or event calling or event executing. Whereas method will contain some behavior or functionality. Q.What are the default events of controls Button and Textbox? Ans: Default events of: Button: CLICK Event TextBox: TEXTCHANGED Event Q.What do u mean by postback? Ans: When ever user request for a page for first time it is called First request. When ever user will interact the page by clicking button or selecting radiobutton e.t.c again one more request for the same page that is called postback request. Q.What is Ispostback? When we will use Not Ispostback? Ans: IsPostBack: It is the property of the Page class which is used to determine whether the page is posted back from the client. When: Whenever we don’t want to execute the code within the load event, when the page load event fires then we will use (!IsPostBack). Q.What is AutopostBack? when we will set Autopostback=true? Ans: Autopostback is the property of the control. If you want a control to postback automatically when an event is raised, you need to set the AutoPostBackproperty of the control to True. Q.Difference between web user control & custom control? Ans: WEB USER CONTROL CUSTOM CONTROL 1. It will provide services to single web 1. It will provide services to multiple applications. web applications. 2.Its file is represented with *.ascx 2.Its file is represented with *.dll file 3. If we want to develop a web user 3. If we want to develop a custom control we have to add a pre-defined control we have to use a class library template called web user control to the project. solution explorer of the application 4. Web user control we have to drag 4.Custom control we have to drag from from solution explorer window to web toolbox window to web page. page. Q.How to get the current date to textbox? Ans: TextBox1.Text = DateTime.Now.ToString(); Q.How to divide the page into different parts? Ans: By using div tag and panel control. Q.What is Rendering? Ans: Rendering is a process of converting complete server side code into client understable code. It will happen before page is submitting to the client. Q.What is the difference between ASP and ASP.Net? Ans: ASP ASP.NET 1. Asp is a classic server side 1. Asp.Net is a .Net advanced server technology before .NET side technology. 2. Asp will support only ONE 2. Asp.Net will support 2 programming programming technique called INPAGE techniques i.e INPAGE and TECHNIQUE(writing both CODEBEHIND technique (design/logic) code in the single file called NOTEPAD) 3.In Asp, its file extension is .asp 3.In Asp, its file extension is .aspx 4. Asp uses mostly VBScript, HTML 4. Asp.Net uses any .Net languages and JavaScript including VB.Net, C# but mostly C#.Net. 5. Asp has limited OOPs support. 5. ASP.NET uses languages which are fully object oriented languages like C# Q.What is the parent class for all asp.net web server controls? Ans: System.Web.UI.Control. Q.How many types of memories are there in .net? Ans: Two types of memories are there in.net. 1. Stack memory and Heap memory Q.D/B client side and server side scripting? Ans: Client Side Scripting Server Side Scripting 1. Scripting which will execute within 1. Scripting which will execute within the web browser can be called as client the web server can be called as client side scripting. side scripting. 2. Using this we can implement client 2. Using this we can implement server side validations. side validations. 3. Client side scripting we can 3. Server side scripting we can implement by using client side implement by using server side technologies called JavaScript, VB technologies called Asp.Net, JSP, PHP script and so on. and so on. Q.When we will go for gridview customization? Ans: Whenever we want to display the Gridview control according to our requirement then we will go for Gridview Customisation. Q.What is AutoGenerateColumns property? Ans: It is a Boolean property of gridview control. By default it is true. If we want to customize gridview control..we have to set it as false. Q.List out directories in Asp.Net? Ans: Page, Register, Master, Control Q.What are the major built in objects in asp.net? Ans: Application, Request, Response, Server, Session. Q.When we will go for master page? Ans: Whenever we want to have common header and common footer within multiple pages of a website then we can go for a Master Page. Q.When can we use xml control? Ans: Whenever we want to display the data from XML document to the user then we can use XML control. NOTE: To fetch the data from XML document, XML control will depend on XSLT(Extensible Style sheet Language Transformation) file. XSLT file will be acting as a mediator between XML control and XML document. Q.When can we use wizard control? Ans: Whenever we want to accept multiple inputs from the user in STEP by STEP process we can use WIZARD CONTROL. Q.When can we use adRotator control? Ans: Whenever we want to display the collection of images in a rotation manner one by one then we will go for Adrotator control. Q.How view and Multiview controls will work? Ans: View and multiview are container controls. Multiview control: It can contain collection of view controls but not a normal control. View Control: It can contain normal controls, but view control should be placed within the multiview. By implementing view and multiview control we can reduce the no. of pages. Q.What are the config files we have in asp.net? Ans: In ASP.NET we have 2 types of Configuration files. They are-1. Web.Config and Machine.config Q.What is web.config file? How many web.cofig can contain a single application? Ans: 1. Web.Config is one of the configuration files. It is a XML file. This file we can use to define the ASP.NET application configuration settings. We can have MULTIPLE Web.Config files within a single application. Q.Can we declare more than oneconnection string in web.config file? Ans: YES. But the connection string names must be different. Q.When we will go for multiple web.config files? Ans: Whenever we want to define some separate settings for couple of web pages, we will create a new folder and we will add that couple of web pages to that folder and we will add a new Web.config file to that new folder and we will define that separate settings within that Web.config. Q.What is the importance of machine.config? How many machine.config files? Ans: The Machine.Config file, which specifies the settings that are global to a particular machine. Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered. We can have only ONE machine.config files. Q.What is the Difference between Hyperlink button and Link Button Ans: Hyperlink: It will not PostBack the webpage to the server. Link Button: It will postback the webpage to the server. Q.What is State Management? Why? Ans: STATE MANAGEMENT: It is a process of maintaining the user’s information. WHY: Asp.Net web application is depending on HTTP protocol which is a STATELESS protocol that means it cannot remember previous user information. Solution for this problem is STATE MANAGEMENT. Q.How many types of state management? Ans: We can implement STATE MANAGEMENT in 2 ways. 1. Server Side State Management and Client Side State Management. Q.What is client side state management? How many types? Ans: Storing the user’s information within the WEB BROWSER memory or CLIENT MACHINE is called as Client Side State Management. Q.What is server side state management? How many types? Ans: Storing the user’s information within the WEB SERVER memory is called as Server Side State Management. Q.What is a session? How many types of sessions? Ans: Session is a temporary variable which will be used to maintain the user information. Based on the locations, sessions are of 4 types: Inproc session State server session Sql server session Custom session Q.What is the default type of session data? Ans: OBJECT. Q.What is the default life time of session variable? Ans: 20 Minutes. Q.Where we will define the session state type? Ans: Within the Web.config , under the TAG. Q.What is the Default Session state mode? Ans: The default Session state mode is INPROC. Q.How to set the life time of session variable? Ans: Using TimeOut property. Q.How to destroy session? Ans: Using Abondon(). i.e Session.Abondon() will destroy the session. Q.What are the advantages of inproc session and disadvantages? Ans: ADVANTAGES OF INPROC SESSION: Accessing the inproc session data will be faster. It is very much suitable for small web applications Disadvantages: It we restart the web server or if any crashes to the web server there is a chance of losing the session data. If the session data is increased there is a burden on the web server, it will affect the performance of web server and web application. It is not suitable for large web application models like webgarden and webfarm. Q.What are the advantages of state server session and disadvantages? Ans: ADVANTAGES OF STATE SERVER SESSION: State server session will provide more security because sessions are creating separately within the windows service. If we restart the web server or if any crashes to the web server but still session data will be safe. It is suitable for large web applications like webgarden and webfarm model. DISADVANTAGES OF STATE SERVER SESSION: Accessing the state server session will be slower compare with inproc session. It is not that much suitable for small web applications because maintaining the windows service is expensive. Always windows service should be ON. Q.Where inproc session data will store? Ans: Inproc sessions are creating within the Current App Domain, which is a part of Web Server. Q.Where state server session will store? Ans: State server session are creating within the state server which is nothing but Windows Service, this windows service is representing by a file called (AspNet_state.exe). Q.How to start windows service? Ans: We can start the Windows Service in 2 ways-1. By using control panel and By using Command prompt. Q.Where sql server session will store? Ans: Sql server sessions will be creating within the Sql Server Database. Q.What is the framework tool will user to create aspstate database with in sqlserver? Ans: aspnet_regsql Q.What are the session related events? Ans: There are 2 Types of Session events. 1. Session Start and Session End. Q.When we will go for session concept? Ans: Whenever we want to store user data within the server. Q.What is worker process? Ans: Worker process is nothing but Asp.Net execution engine or Asp.Net runtime. The role of Asp.Net runtime is executing the Asp.Net web page within the Web server. Q.What is appdomain? Ans: Every worker process will maintain a memory unit within the web server which is nothing but Appdomain. Q.What is application pool? Ans: It is part of web server or a unit of web server. Q.What is webgarden? Ans: An application pool which is having multiple WORKER PROCESS is called as WEB GARDEN. Q.What is webfarm? Ans: Deploying a website into multiple web servers is called Webfarm. Q.Why inproc session is not suitable for webgarden and webfarm model? Ans: Inproc sessions will create within the current App Domain due to that reason app domain data is not sharable due to that reason Inproc sessions are not suitable for WEB GARDEN and WEBFARM MODELS. Q.When we will go for application state? Ans: when ever we want to store the data in web server..which should be common for all users. For example: In youtube video number of views Q.What are application events? Ans: There are 3 application events. 1. Application Start Event Application End Event Application Error Event. Q.Difference between session state and application state? Ans: 1. Application state: It will be available to all users of the application. Application state variables are cleared, when the process hosting the application is restarted. Session state: It will only be available to a specific user of the ASP.net application. Session state variable are cleared, when the user session times out. The default is This is configurable in Web.Config. Q.What is global.asax file? Ans: This is a class file, which is coming with 1 user defined called Global and it has a super class called HTTPApplication. This file will contain all the application session related events. Q.What is a cookie? Ans: Cookie is a variable which we can use to store the user data. It will create within the client machine due to that reason which is called as client side state management. Q.What is the default life of cookie? Ans: 30 Minutes. Q.Types of cookies? Ans: Cookies can be broadly classified into 2 types Persistent cookies: Remain on the client computer, even after the browser is You can configure how long the cookies remain using the expires property of the Http Cookie object. Non-Persistent cookies: If you don't set the Expires property, then the cookie is called as a Non-Persistent cookie. Non-Persistent cookies only remain in memory until the browser is closed. Q.What is the Scope of Cookie? Ans: Throughout the website. Q.What is the Difference between Cookie and Session? Ans: COOKIE SESSION 1. Cookie is a client side state 1. Session is a server side state management technique. management technique. 2. Cookie is a variable which will create 2. Session is also a variable which will within the client machine. create within the Web server. 3. Default timeout of a cookie is 30 3. Default life time of session variable is minutes. 20 minutes. Q.What is querystring? What is the draw back? Ans: 1.QueryString is a way to forward the data from one web page to another. 2. QueryString is attached to the URL with "?". Drawbacks: 1. All the attributes and values are visible to the end user. Therefore, they are not secure. There is a limit to URL length of 255 characters. Q.What is Viewstate? What is the scope of view state? Ans: 1. Viewstate will maintain the user’s data among multiple postbacks requests. 2. View state will store the user’s data within client machine due to that reason it is called as CLIENT SIDE STATE MANGEMENT. The scope of the Viewstate is within that web form. Q.Is HTML controls will maintain Viewstate? Ans: NO. Because HTML controls are Client side controls. Q.What is Hiddenfield and what is the scope? Ans: 1. HiddenField is a Server side control, which can hold the user data but holding the data will not be visible because it is a INVISIBLE CONTROL. 2. To Implement HiddenField we can use Asp.Net server control called HiddenField. Q.What is caching? Ans: Caching is a process of storing the frequently used web page (or) frequently used part of the web page (or) frequently used data into some location for future access. Q.How many locations we can implement caching? Ans: According to the location caching is classified into 4 types. 1. Client caching Proxy caching Reverse caching Web server caching Q.What are types of caching techniques? Ans: Asp.Net will support 3 Caching Techniques. 1. Page Output Caching Fragment Output caching Data Caching Q.When we will go for page output caching? Ans: Whenever we want to store the frequently used web page into some location then we will go for PAGE OUTPUT CACHING. In general, we will implement page caching on startup page such as login and home page. Q.When we will go for fragment caching? Ans: Whenever we want to store the frequently used part of the web page into some location for future access then we will go for FRAGMENT CACHING. Fragment caching we will implement on a Web user control, which is accessing by multiple web pages. Q.When we will go for data caching? Ans: Whenever we want to store the frequently used data for future access into some location then we will go for DATA CACHING. Q.What is class we will use to access global connection string? Ans: ConfigurationManager class. Q.What is security? Ans: Security is a process of allowing the authenticated users and denying the unauthorized users when user is requested for restricted web page. Q.What is authorization? Ans: Authorization is a process of verifying the authentication ticket and supplying the web page based on authentication ticket. Q.What is Authentication? Ans: Authentication is a process of accepting the user credentials, when user will request for a restricted web page and generating the authentication ticket for the valid user. Q.How many types of authentications will support by asp.net? Ans: It will support 3 types of authentications. 1. Forms authentication Passport authentication Windows authentication Q.What is returnurl? Ans: it is querystring varible Q.What is the class we will use for forms authentication? Ans: FormsAuthentication Q.When we will go for forms authentication? Ans: Forms authentication is used for normal web applications. Q.When we will go for passport authentication? Ans: A group of websites which will allow the user with single user id and password will go for the passport authentication. Ex: If we have Gmail id with that we can access Gmail, Facebook, Youtube etc Q.When we will go for windows authentication? Ans: Whenever users are part of the same Windows domain as the server then the Windows Authentication is the preferred approach to authentication. In other words, whenever we have intranet web applications it is better to go with Windows Authentication. Q.List out Gridview events? Ans: 1. Row deleting and Row deleted Row editing Row updating and Row updated Row Cancelling edit Row command Row created Row DataBound Page index changing and page index changed Sorted and sorting. Q.What is the use of sqldata source control? Ans: SqlData Source will make the programmer task easy to communicate SqlServer Database. Q.When we will go for repeater control? Ans: Whenever we want to display the data as it is we can go for Repeater control, that means we don’t require to provide any Edit or Delete facilities. Ex: To display Bank Statements and Examination results. Q.When we will go for datalist control? Ans: Whenever we want to display the data in a repeating list format then we will go for Datalist control. Q.When we will go for formview and when we will go for details view? Ans: FORMVIEW: Whenever we want to display record by record in VERTICAL manner then we can go for Formview. Details View: Whenever we want to display record by record in HORIZONTAL manner then we can go for Details view. Q.What is the use of data pager control? Ans: Data pager control provides paging functionality for data bound controls. Q.Difference between listbox and dropdownlist? Ans: LISTBOX: It will allow the user to select one item or multiple items. DropDownList: It will allow the user to select only one item. Q.where is the viewstate information stored? Ans: Within the html hidden fields. Q.which are the 2 properties are on every validation control? Ans: 1.ControlToValidate and 2.ErrorMessage. Q.what is the use of @register directives? Ans: It informs the compiler of any custom server control added to the page. Q.what is the textbox property used for password textbox? Ans: TextMode Q.How to reduce the burden on the page? Ans: By implementing paging. AJAX Q.Why Ajax? Ans: To avoid full page postback,to implement partial page postback Using AJAX we can develops RICH USER INTERFACES web applications If we want to follow ASYNCHRONOUS REQUEST MODEL, while developing the web applications we have to use AJAX. To improve the PERFORMANCE of the web application and to reduce the NETWORK TRAFFIC we can use AJAX. We can avoid SCREEN FLICKER using AJAX. Q.What is partial post back? Ans: when ever user will interact the part of the page then sending postback request for only that part of the page Q.What is synchronous request model and what is asynchronous request model? Ans: Synchronous Request Model: In this model, every client request has to communicate the web server and every request has to process by the web server then only that request, response will be getting by the client. Asynchronous Request Model: In this model, between client and web server we will have a middleman called AJAX ENGINE. AJAX ENGINE: It is a part of web browser. The role of AJAX engine is to process the part of the web page or partial web page within the client side. Q.What is client centric and what is server centric? Ans: AJAX will support 2 programming models. They are: Server Centric programming model: In this model every client request will be processing by the web server that can be first request or postback request. Client Centric programming model: In this model, first request will be processing by the web server and postback request will be processing by the client. NOTE: While developing an AJAX web page we can implement only server centric programming model or client centric programming model or both within single web page. Q.Explain about extender controls? And non extender controls? Ans: AJAX Toolkit is providing 2 types of controls. EXTENDER CONTROLS: Extender controls are not individual controls i.e these controls will not provide any functionality individually. Extender controls will extend the functionalities of existing ASP.NET controls. Ex: Autocomplete extender, calendar extender, dropdown extender and so on.. NON-EXTENDER CONTROLS: Non – Extender controls are individual controls i.e every non-extender controls will provide some individual functionality. Non – Extender controls provides the extra controls in ASP.NET. Ex: Accordion and Accordion pane, Tab Container, Rating, Nobot. Q.What is the importance of script manager and update panel control in Ajax? Ans: IMPORTANCE OF SCRIPT MANAGER: In Ajax, Script Manager is the main important parent control. Whenever we are developing an Ajax web page first we have to drag and drop SCIRPT MANAGER Control. These control class will provide all the AJAX related METHODS and PROPERTIES. IMPORTANCE OF UPDATE PANEL: Update panel is one of the Ajax Container control. By default Asp.Net control follows Server Centric Programming Model Whatever controls we are adding to update panel will execute Client Centric Programming Model. Whenever we want to make Asp.Net controls to follow Client Centric Programming Model. We can drag and drop update panel, in that we can add Asp.Net controls and Ajax controls. ADO.NET Q.What is ADO.Net? Why Ado.net? Ans: ADO.NET : 1. It is an integral component in .NET framework, which was introduced by the Microsoft with .NET Framework 1.0 It is a Data Access Object, which allows communication between .NET application and Databases. WHY: 1. whenever .NET application wants to communicate Databases it has to take the help of Ado.Net. Ado.net acts like a mediator between .Net application and Database. Q.Difference between Connected Oriented Architecture (COA) and Disconnected Oriented Architecture (DOA)? Ans: COA DOA 1. Whenever we require a continuous 1. Whenever we doesn’t require a connection with the Database for continuous connection with the accessing the data we use COA Database for accessing the data we can use DOA. 2. In COA, SqlDataReader will fetch 2. In DOA, SqlDataAdapter will fetch the data from database and bind to the the data from database and store into Client application. the DATASET in the Client application. Q.What is the base class library used for ado.net? Ans: System.data To communicate Sql server database we have to import a Base Class Library called Using System.Data.SqlClient; Q.What are components required for connected oriented? Ans: The components required for Connected oriented architecture are: Connection Object Command Object DataReader Object Q.What are the components required for Disconnected oriented? Ans: The components required for Disconnected oriented architecture are: Connection Object Command Object DataAdapter Object Dataset Object Q.Difference between DataReader and DataAdapter? Ans: DATAREADER DATAADAPTER 1. It is used in Connected Oriented 1. It is used in Disconnected Oriented Architecture. Architecture. 2. DataReader is represents with a 2. DataAdapter is represented with a pre-defined class called pre-defined class called SqlDataReader. SqlDataAdapter. 3. DataReader is used to retrieve a 3. DataAdapter is used to retrieve data read-only, forward-only stream of from a data source and populate tables data from a database within a DataSet. Q.Difference between dataset and data table? Ans: DATASET DATA TABLE 1. Dataset is a collection of DATA 1. Data table represents a single table TABLES. i.e it is a collection of rows and columns. Q.Difference between data reader and dataset? Ans: DATAREADER DATASET 1. It is used in Connected Oriented 1. It is used in Disconnected Oriented Architecture. Architecture. 2. DataReader is directly accessing the 2. Dataset is a local database which is central database. not communicating the central database directly, between the central db and local db there will a mediator called DataAdapter for communication. 3. DataReader is represented at a time 3. Dataset can contain collection of single record. DataReader is Read tables because dataset itself is a local only, Forward only, connected recoed database. set. 4. DataReader we will use only when 4. We can use dataset for reading the we want to read the data from Central data, inserting, updating and deleting DataBase. the data. Q.When we will go for connected oriented architecture and when we will go for disconnected oriented architecture? Ans: Connected Oriented Architecture (COA): Whenever we require a continuous connection with the Database for accessing the data then we will go for COA. DISconnected Oriented Architecture (DOA): Whenever we doesn’t require a continuous connection with the Database for accessing the data then we will go for DOA. Q.How to bind the data to textbox? Ans: Txtbox1.Text=dr; Q.How to bind the data to grid view? Ans: Gridview1.datasource=dr; Gridview1.databind(); Q.How to bind the data to label? Ans: label1.Text=dr; Q.How to bind the data to dropdownlist? Ans: dropdownList1.datasource=dr; dropdowList1.DataTextField=dr; dropdownList1.DatavalueField=dr; dropdownList1.DataBind(); Q.Difference between ExecuteReader, ExecuteNonquery, ExecuteScalar? Ans: ExecuteReader(): It is apre-defined member method of SqlCommand class. This method will read or fetch the data from the central database and will return to DataReader object. ExecuteNonQuery(): This method will execute the Non-Query command of command object CRUD Operations like INSERT, UPDATE, DELETE, CREATE and so on. Then it will return the no. of records which are affected by the command. ExecuteScalar(): This method will executes the command object command till the first match. This method will avoid the unnecessary scanning of the table, which improves the performance of the application. Q.How to destroy connection object explicitly? Ans: conn.Dispose() Q.What is row command event? When we will go for row command event? Ans: Row Command event is one of the events of the Gridview control. This event will fire when user will click any button within the Gridview control. Q.Can I implement link button click event within gridview? Ans: Yes. Q.How to create delete, edit, select buttons with in gridview? Ans: By using PROPERTY BUTTON AutoGenerateDeleteButton For DELETE Button AutoGenerateEditButton For EDIT Button AutoGenerateSelectButton For SELECT Button Q.Which data bound control will support to create insert button by using property? Ans: Listview control Q.What is the data provider to communicate sql server data base? Ans: Every DataProvider is providing by the Microsoft as a Base class library (BCL). To communicate Sql server database we have to import a BCL called Using System.Data.SqlClient; Q.What is 3 tier? Ans: A software solution which is implemented by using 3 layers can be called as 3-Tier Architecture. In 3-Tier architecture, we have 3 layers I-Layer: It will contain the UI-Design and Validations Code is known as PRESENTATION LAYER (UI). II-Layer: It will contain the Business Logic layer code and is known as BUSINESS LOGIC LAYER (BLL). III-Layer: It will contain the Data Access Code and is known as DATA ACCESS LAYER (DAL). In 3-Tier Architecture, UI interacts with BLL only BLL will interacts with DAL DAL interacts with DATABASE. Q.What is windows service? Ans: 1. Windows service in one of the software application. It works only on windows operating system due to that reason windows service is called operating system dependent application. It will start when the windows OS is Booting. It will run till the windows OS is Running. It will stop when the OS is Shutdown. It can be start and stop manually also. Q.What is web service? Ans: 1. A unit of code which is providing the services to multiple client applications can be called as WEB SERVICE. An application which is receiving the services can be called as SERVICE RECEIVER or CLIENT APPLICATION. An application which is providing the services can be called as SERVICE PROVIDER or WEB SERVICE. Q.What is WPF? Ans: 1. WPF stands for Windows Presentation Foundation. It is a .Net advanced windows technology, introduced by Microsoft with .Net Framework 3.0 in 2006. Using WPF we can develop an advanced windows applications. WPF is integrated with 2D graphics, 3D graphics, animations and multimedia. Whenever we want to implement animations within a desktop application the best choice is WPF. Q.What is silverlight? Ans: SilverLight is an advanced web technology which we can use to implement animations, multimedia for asp.net web application Q.What is Jquery? Ans: 1. Jquery is an advanced technology of JavaScript that means jquery is next generation of JavaScript. It is a predefined JavaScript Library. It is a group of JavaScript predefined functions. It is a lightweight and more powerful API adding dynamic behavior for webpage. To implement JavaScript programmer has to write the multiline code. But using Jquery we can implement JavaScript. Q.What is Linq? Ans: Linq stands for Language Integrated Query. Linq is an advanced data access object for .net . Q.What is Crystal Reports? Ans: 1. Crystal Reports is one of the third party Reporting Tool. Using this tool, we can generate the reports. If we want to use Crystal reports in Visual studio 2010 then we have to install crystal reports software explicitly from the following site: WWW.sap.com Q.What is the base class library for crystal reports? Ans: CrystalDecisions.CrystalReports.Engine; Q.Can we run asp.net application without IIS? Ans: Yes. Using ASP.NET DEVELOPMENT SERVER which is the default server in ASP.NET. Q.Why virtual directory? Ans: to provide security for web application Q.What is the default server we will get with asp.net? Ans: ASP.NET DEVELOPMENT SERVER. Q.Why constraints? Ans: Constraint is a condition which we can assign on a single column or multiple columns. Constraints will maintain consistent data within the database. Q.What is the importance of primary key? Ans: To avoid duplicate values and null values in a column. Q.What is the importance of foreign key? Ans: 1. To establish relation between Parent table and Child table we require a common column , that column should be parent table primary key column. 2. To make that relation strong we require Foreign key constraint that means Foreign key constraint we should assign child table common column. Q.What is stored procedure? Ans: 1. Stored procedure is a pre-compiled Sql statements. That means stored procedure will contain sql statements like SELECT, UPDATE, DELETE and so on which is already compiled. Syntax: Create procedure procedurename () As Begin { } end Q.What is advantage of stored procedure? Ans: By implementing stored procedures we can avoid the multiple time compilation of Sqlcommands. contact for more on Dotnet Online Training
Continue reading
Go Language interview Questions
Q.What Is Go? Ans: Go is a general-purpose language designed with systems programming in mind.It was initially developed at Google in year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection and supports concurrent programming. Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. Q.What Are The Benefits Of Using Go Programming? Ans: Support for environment adopting patterns similar to dynamic languages. For example type inference (x := 0 is valid declaration of a variable x of type int). Compilation time is fast. InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement. Conciseness, Simplicity, and Safety. Support for Interfaces and Type embdding. Production of statically linked native binaries without external dependencies. Q.Does Go Support Type Inheritance? Ans: No support for type inheritance. Q.Does Go Support Operator Overloading? Ans: No support for operator overloading. Q.Does Go Support Method Overloading? Ans: No support for method overloading. Q.Does Go Support Pointer Arithmetics? Ans: No support for pointer arithmetic. Q.Does Go Support Generic Programming? Ans: No support for generic programming. Q.Is Go A Case Sensitive Language? Ans: Yes! Go is a case sensitive programming language. Q.What Is Static Type Declaration Of A Variable In Go? Ans: Static type variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program. Q.What Is Dynamic Type Declaration Of A Variable In Go? Ans: A dynamic type variable declaration requires compiler to interpret the type of variable based on value passed to it. Compiler don't need a variable to have type statically as a necessary requirement. Q.Can You Declared Multiple Types Of Variables In Single Declaration In Go? Ans: Yes Variables of different types can be declared in one go using type inference. var a, b, c = 3, 4, "foo" Q.How To Print Type Of A Variable In Go? Ans: Following code prints the type of a variable − var a, b, c = 3, 4, "foo" fmt.Printf("a is of type %Tn", a) Q.What Is A Pointer? Ans: It's a pointer variable which can hold the address of a variable. For example − var x = 5 var p *int p = &x fmt.Printf("x = %d", *p) Here x can be accessed by *p. Q.What Is The Purpose Of Break Statement? Ans: Break terminates the for loop or switch statement and transfers execution to the statement immediately following the for loop or switch. Q.What Is The Purpose Of Continue Statement? Ans: Continue causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Q.What Is The Purpose Of Goto Statement? Ans: goto transfers control to the labeled statement. Q.Explain The Syntax For 'for' Loop? Ans: The syntax of a for loop in Go programming language is − for { statement(s); } Here is the flow of control in a for loop − if condition is available, then for loop executes as long as condition is true. if for clause that is ( init; condition; increment ) is present then The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. if range is available, then for loop executes for each item in the range. Q.Explain The Syntax To Create A Function In Go? Ans: The general form of a function definition in Go programming language is as follows − func function_name( ) { body of the function } A function definition in Go programming language consists of a function header and a function body. Here are all the parts of a function − func func starts the declaration of a function. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Return Type − A function may return a list of values. The return_types is the list of data types of the values the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the not required. Function Body − The function body contains a collection of statements that define what the function does. Q.Can You Return Multiple Values From A Function? Ans: A Go function can return multiple values. For example − package main import "fmt" func swap(x, y string) (string, string) { return y, x } func main() { a, b := swap("Mahesh", "Kumar") fmt.Println(a, b) } Q.In How Many Ways You Can Pass Parameters To A Method? Ans: While calling a function, there are two ways that arguments can be passed to a function: Call by value: This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by reference:This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Q.What Is The Default Way Of Passing Parameters To A Function? Ans: By default, Go uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function while calling max() function used the same method. Q.What Do You Mean By Function As Value In Go? Ans: Go programming language provides flexibility to create functions on the fly and use them as values. We can set a variable with a function definition and use it as parameter to a function. Q.What Are The Function Closures? Ans: Functions closure are anonymous functions and can be used in dynamic programming. Q.What Are Methods In Go? Ans: Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call function using "." operator. Q.What Is Default Value Of A Local Variable In Go? Ans: A local variable has default value as it corresponding 0 value. Q.What Is Default Value Of A Global Variable In Go? Ans: A global variable has default value as it corresponding 0 value. Q.What Is Default Value Of A Pointer Variable In Go? Ans: Pointer is initialized to nil. Q.Explain The Purpose Of The Function Printf()? Ans: Prints the formatted output. Q.What Is Lvalue And Rvalue? Ans: The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a constant. Q.What Is The Difference Between Actual And Formal Parameters? Ans: The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters. Q.What Is The Difference Between Variable Declaration And Variable Definition? Ans: Declaration associates type to the variable whereas definition gives the value to the variable. Q.Explain Modular Programming? Ans: Dividing the program in to sub programs (modules/function) to achieve the given task is modular approach. More generic functions definition gives the ability to re-use the functions, such as built-in library functions. Q.What Is A Token? Ans: A Go program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. Q.Which Key Word Is Used To Perform Unconditional Branching? Ans: goto Q.What Is An Array? Ans: Array is collection of similar data items under a common name. Q.What Is A Nil Pointers In Go? Ans: Go compiler assign a Nil value to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned nil is called a nil pointer. The nil pointer is a constant with a value of zero defined in several standard libraries. Q.What Is A Pointer On Pointer? Ans: It's a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the data held by the designated pointer variable. var a int var ptr *int var pptr **int a = 3000 ptr = &a pptr = &ptr fmt.Printf("Value available at **pptr = %dn", **pptr) Therefore 'a' can be accessed by **pptr. Q.What Is Structure In Go? Ans: Structure is another user defined data type available in Go programming, which allows you to combine data items of different kinds. Q.How To Define A Structure In Go? Ans: To define a structure, you must use type and struct statements. The struct statement defines a new data type, with more than one member for your program. type statement binds a name with the type which is struct in our case. The format of the struct statement is this − type struct_variable_type struct { member definition; member definition; ... member definition; } Q.What Is Slice In Go? Ans: Go Slice is an abstraction over Go Array. As Go Array allows you to define type of variables that can hold several data items of the same kind but it do not provide any inbuilt method to increase size of it dynamically or get a sub-array of its own. Slices covers this limitation. It provides many utility functions required on Array and is widely used in Go programming. Q.How To Define A Slice In Go? Ans: To define a slice, you can declare it as an array without specifying size or use make function to create the one. var numbers int /* a slice of unspecified size */ /* numbers == int{0,0,0,0,0}*/ numbers = make(int,5,5) /* a slice of length 5 and capacity 5*/ Q.How To Get The Count Of Elements Present In A Slice? Ans: len() function returns the elements presents in the slice. Q.What Is The Difference Between Len() And Cap() Functions Of Slice In Go? Ans: len() function returns the elements presents in the slice where cap() function returns the capacity of slice as how many elements it can be accomodate. Q.How To Get A Sub-slice Of A Slice? Ans: Slice allows lower-bound and upper bound to be specified to get the subslice of it using. Q.What Is Range In Go? Ans: The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Q.What Are Maps In Go? Ans: Go provides another important data type map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can strore the value in a Map object. After value is stored, you can retrieve it by using its key. Q.How To Create A Map In Go? Ans: You must use make function to create a map. /* declare a variable, by default map will be nil*/ var map_variable mapvalue_data_type /* define the map as nil map can not be assigned any value*/ map_variable = make(mapvalue_data_type) Q.How To Delete An Entry From A Map In Go? Ans: delete() function is used to delete an entry from the map. It requires map and corresponding key which is to be deleted. Q.What Is Type Casting In Go? Ans: Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator as following: type_name(expression) Q.What Are Interfaces In Go? Ans: Go programming provides another data type called interfaces which represents a set of method signatures. struct data type implements these interfaces to have method definitions for the method signature of the interfaces. Contact for more on Go Language Online Training
Continue reading
Java Interview Questions
Q.How can you achieve Multiple Inheritance in Java? Ans: Java's interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations. Q.How To Replace the Characters in a String? Ans: Replace all occurrences of 'a' with 'o' String newString = string.replace('a', 'o'); Replacing Substrings in a String static String replace(String str, String pattern, String replace) { int s = 0; int e = 0; StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e+pattern.length(); } result.append(str.substring(s)); return result.toString(); } Converting a String to Upper or Lower Case Convert to upper case String upper = string.toUpperCase(); // Convert to lower case String lower = string.toLowerCase(); Converting a String to a Number int i = Integer.parseInt("123"); long l = Long.parseLong("123"); float f = Float.parseFloat("123.4"); double d = Double.parseDouble("123.4e10"); Breaking a String into Words String aString = "word1 word2 word3"; StringTokenizer parser = new StringTokenizer(aString); while (parser.hasMoreTokens()) { processWord(parser.nextToken()); Q.What is a transient variable? Ans: A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static. Q.What is the difference between Serializalble and Externalizable interface? Ans: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. Q.How many methods in the Externalizable interface? Ans: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). Q.How many methods in the Serializable interface? Ans: There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable. Q.How to make a class or a bean serializable? Ans: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable. Q.What is the serialization? Ans: The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage. Q.What are synchronized methods and synchronized statements? Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q.What is synchronization and why is it important? Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors. Q.What is the purpose of finalization? Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What happens when a thread cannot acquire a lock on an object? Ans: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. Q.What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Q.What restrictions are placed on method overloading? Ans: Two methods may not have the same name and argument list but different return types. Q.How does multithreading take place on a computer with a single CPU? Ans: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the ResourceBundle class? Ans: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.What is Serialization and deserialization? Ans: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. Q.What are the Object and Class classes used for? Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. Q.Can you write Java code for declaration of multiple inheritance in Java ? Ans: Class C extends A implements B { } Q.What do you mean by multiple inheritance in C++ ? Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student. Q.Write the Java code to declare any constant (say gravitational constant) and to get its value. Ans: Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT); } } Q.Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level. Ans: SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID AND Level.Level = "freshman" AND Student.Course = 3; Q.What do you mean by virtual methods? Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object. Q.What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A. Q.What do mean by polymorphism, inheritance, encapsulation? Ans: Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information. Q.What are the advantages of OOPL? Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful. Q.How many methods do u implement if implement the Serializable Interface? Ans: The Serializable interface is just a "marker" interface, with no methods of its own to implement. Q.Are there any other 'marker' interfaces? Ans: java.rmi.Remote java.util.EventListener Q.What is the difference between instanceof and isInstance? Ans: instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() determines if the specified object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is nonnull and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. Q.why do you create interfaces, and when MUST you use one? Ans: You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved. Q.What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why? Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of the object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with. Q.Discuss the differences between creating a new class, extending a class and implementing an interface; and when each would be appropriate. Ans: Creating a new class is simply creating a class with no extensions and no implementations. The signature is as follows public class MyClass() { Extending a class is when you want to use the functionality of another class or classes. The extended class inherits all of the functionality of the previous class. An example of this when you create your own applet class and extend from java.applet.Applet. This gives you all of the functionality of the java.applet.Applet class. The signature would look like this public class MyClass extends MyBaseClass { } Implementing an interface simply forces you to use the methods of the interface implemented. This gives you two advantages. This forces you to follow a standard(forces you to use certain methods) and in doing so gives you a channel for polymorphism. This isn’t the only way you can do polymorphism but this is one of the ways. public class Fish implements Animal { } Q.Name four methods every Java class will have. Ans: public String toString(); public Object clone(); public boolean equals(); public int hashCode(); Q.What does the "abstract" keyword mean in front of a method? A class? Ans: Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it, it is called abstract method.Abstract method has no body. It has only arguments and return type. Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. Q.Does Java have destructors? Ans: No garbage collector does the job working in the background Q.Are constructors inherited? Can a subclass call the parent's class constructor? When? Ans: You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language. QDoes Java have "goto"? Ans: No Q.What does the "final" keyword mean in front of a variable? A method? A class? Ans: FINAL for a variable : value is constant FINAL for a method : cannot be overridden FINAL for a class : cannot be derived Core Java Interview Questions and Answers Q.what is a transient variable? Ans: A transient variable is a variable that may not be serialized. Q.which containers use a border Layout as their default layout? Ans: The window, Frame and Dialog classes use a border layout as their default layout. Q.Why do threads block on I/O? Ans: Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed Q. How are Observer and Observable used? Ans: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. Q.What is synchronization and why is it important? Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. Q.Can a lock be acquired on a class? Ans: Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. Q.What's new with the stop(), suspend() and resume() methods in JDK 1.2? Ans: The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. Q.Is null a keyword? Ans: The null value is not a keyword. Q.What is the preferred size of a component? Ans: The preferred size of a component is the minimum component size that will allow the component to display normally. Q.What method is used to specify a container's layout? Ans: The setLayout() method is used to specify a container's layout. Q.Which containers use a FlowLayout as their default layout? Ans: The Panel and Applet classes use the FlowLayout as their default layout. Q.What state does a thread enter when it terminates its processing? Ans: When a thread terminates its processing, it enters the dead state. Q.What is the Collections API? Ans: The Collections API is a set of classes and interfaces that support operations on collections of objects. Q.Which characters may be used as the second character of an identifier, but not as the first character of an identifier? Ans: The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects. Q.How does Java handle integer overflows and underflows? Ans: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Q.What is the Vector class? Ans: The Vector class provides the capability to implement a growable array of objects Q.What modifiers may be used with an inner class that is a member of an outer class? Ans: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. Q.What is an Iterator interface? Ans: The Iterator interface is used to step through the elements of a Collection. Q.What is the difference between the >> and >>> operators? Ans: The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Q.Which method of the Component class is used to set the position and size of a component? Ans: setBounds() Q.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Ans: Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns. Q.What is the difference between yielding and sleeping? Ans: When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. Q.Which java.util classes and interfaces support event handling? Ans: The EventObject class and the EventListener interface support event processing. Q.Is sizeof a keyword? Ans:The sizeof operator is not a keyword Q.What are wrapped classes? Ans: Wrapped classes are classes that allow primitive types to be accessed as objects. Q.Does garbage collection guarantee that a program will not run out of memory? Ans: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection Q.What restrictions are placed on the location of a package statement within a source code file? Ans: A package statement must appear as the first line in a source code file (excluding blank lines and comments). Q.Can an object's finalize() method be invoked while it is reachable? Ans: An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. Q.What is the immediate superclass of the Applet class? Ans: Panel Q.What is the difference between preemptive scheduling and time slicing? Ans: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Q.Name three Component subclasses that support painting. Ans: The Canvas, Frame, Panel, and Applet classes support painting. Q.What value does readLine() return when it has reached the end of a file? Ans: The readLine() method returns null when it has reached the end of a file. Q.What is the immediate superclass of the Dialog class? Ans: Window Q.What is clipping? Ans: Clipping is the process of confining paint operations to a limited area or shape. Q.What is a native method? Ans: A native method is a method that is implemented in a language other than Java. Q.Can a for statement loop indefinitely? Ans: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; Q.What are order of precedence and associativity, and how are they used? Ans: Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left Q.When a thread blocks on I/O, what state does it enter? Ans: A thread enters the waiting state when it blocks on I/O. Q.To what value is a variable of the String type automatically initialized? Ans: The default value of an String type is null. Q.What is the catch or declare rule for method declarations? Ans: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. Q.What is the difference between a MenuItem and a CheckboxMenuItem? Ans: The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. Q.What is a task's priority and how is it used in scheduling? Ans: A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. Q.What class is the top of the AWT event hierarchy? Ans: The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. Q.When a thread is created and started, what is its initial state Ans: A thread is in the ready state after it has been created and started. Q.Can an anonymous class be declared as implementing an interface and extending a class? Ans: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Q.What is the range of the short type? Ans: The range of the short type is -(2^15) to 2^15 - 1. Q.What is the range of the char type? Ans: The range of the char type is 0 to 2^16 - 1. Q.In which package are most of the AWT events that support the event-delegation model defined? Ans: Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. Q.What is the immediate superclass of Menu? Ans: MenuItem Q.What is the purpose of finalization Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q.Which class is the immediate superclass of the MenuComponent class. Ans: Object Q.What invokes a thread's run() method? Ans: After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. Q.What is the difference between the Boolean & operator and the && operator? Ans: If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Q.Name three subclasses of the Component class. Ans: Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent Q.What is the GregorianCalendar class? Ans: The GregorianCalendar provides support for traditional Western calendars. Q.Which Container method is used to cause a container to be laid out and redisplayed? Ans: validate() Q.What is the purpose of the Runtime class? Ans: The purpose of the Runtime class is to provide access to the Java runtime system. Q.How many times may an object's finalize() method be invoked by the garbage collector? Ans: An object's finalize() method may only be invoked once by the garbage collector. Q.What is the purpose of the finally clause of a try-catch-finally statement? Ans: The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. Q.What is the argument type of a program's main() method? Ans: A program's main() method takes an argument of the String type. Q.Which Java operator is right associative? Ans: The = operator is right associative. Q.What is the Locale class? Ans: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Q.Can a double value be cast to a byte? Ans: Yes, a double value can be cast to a byte. Q.What is the difference between a break statement and a continue statement? Ans: A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. Q.What must a class do to implement an interface? Ans: It must provide all of the methods in the interface and identify the interface in its implements clause. Q.What method is invoked to cause an object to begin executing as a separate thread? Ans: The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. Q.Name two subclasses of the TextComponent class. Ans: TextField and TextArea Q.What is the advantage of the event-delegation model over the earlier event-inheritance model? Ans: The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Q.Which containers may have a MenuBar? Ans: Frame Q.How are commas used in the initialization and iteration parts of a for statement? Ans: Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Q.What is the purpose of the wait(), notify(), and notifyAll() methods? Ans: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. Q.What is an abstract method? Ans: An abstract method is a method whose implementation is deferred to a subclass. Q.How are Java source code files named Ans: A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension. Q.What is the relationship between the Canvas class and the Graphics class? Ans: A Canvas object provides access to a Graphics object via its paint() method. Q.What are the high-level thread states? Ans: The high-level thread states are ready, running, waiting, and dead. Q.What value does read() return when it has reached the end of a file? Ans: The read() method returns -1 when it has reached the end of a file. Q.Can a Byte object be cast to a double value? Ans: No, an object cannot be cast to a primitive value. Q.What is the difference between a static and a non-static inner class? Ans: A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances. Q.What is the difference between the String and StringBuffer classes? Ans: String objects are constants. StringBuffer objects are not. Q.If a variable is declared as private, where may the variable be accessed? Ans: A private variable may only be accessed within the class in which it is declared. Q.What is an object's lock and which object's have locks? Ans: An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. Q.What is the Dictionary class? Ans: The Dictionary class provides the capability to store key-value pairs. Q.How are the elements of a BorderLayout organized? Ans: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. Q.What is the % operator? Ans: It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. Q.When can an object reference be cast to an interface reference? Ans: An object reference be cast to an interface reference when the object implements the referenced interface. Q.What is the difference between a Window and a Frame? Ans: The Frame class extends Window to define a main application window that can have a menu bar. Q.Which class is extended by all other classes? Ans: The Object class is extended by all other classes. Q.Can an object be garbage collected while it is still reachable? Ans: A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. Q.Is the ternary operator written x : y ? z or x ? y : z ? Ans: It is written x ? y : z. Q.What is the difference between the Font and FontMetrics classes? Ans: The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. Q.How is rounding performed under integer division? Ans: The fractional part of the result is truncated. This is known as rounding toward zero. Q.What happens when a thread cannot acquire a lock on an object? Ans: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. Q.What is the difference between the Reader/Writer class hierarchy and the InputStream/ OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. Q.What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q.If a class is declared without any access modifiers, where may the class be accessed? Ans: A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. Q.What is the SimpleTimeZone class? Ans: The SimpleTimeZone class provides support for a Gregorian calendar. Q.What is the Map interface? Ans: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. Q.Does a class inherit the constructors of its superclass? Ans: A class does not inherit constructors from any of its superclasses. Q.For which statements does it make sense to use a label? Ans: The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. Q.What is the purpose of the System class? Ans: The purpose of the System class is to provide access to system resources. Q.Which TextComponent method is used to set a TextComponent to the read-only state? Ans: setEditable() Q.How are the elements of a CardLayout organized? Ans: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. Q.Is &&= a valid Java operator? Ans: No, it is not. Q.Name the eight primitive Java types. Ans: The eight primitive types are byte, char, short, int, long, float, double, and boolean. Q.Which class should you use to obtain design information about an object? Ans: The Class class is used to obtain information about an object's design. Q.What is the relationship between clipping and repainting? Ans: When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. Q.Is "abc" a primitive value? Ans: The String literal "abc" is not a primitive value. It is a String object. Q.What is the relationship between an event-listener interface and an event-adapter class? Ans: An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. Q.What restrictions are placed on the values of each case of a switch statement? Ans: During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. Q.What modifiers may be used with an interface declaration? Ans: An interface may be declared as public or abstract. Q.Is a class a subclass of itself? Ans: A class is a subclass of itself. Q.What is the highest-level event class of the event-delegation model? Ans: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. Q.What event results from the clicking of a button? Ans: The ActionEvent event is generated as the result of the clicking of a button. Q.How can a GUI component handle its own events? Ans: A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener. Q.What is the difference between a while statement and a do statement? Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. Q.How are the elements of a GridBagLayout organized? Ans: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Q.What advantage do Java's layout managers provide over traditional windowing systems? Ans: Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. Q.What is the Collection interface? Ans: The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. Q.What modifiers can be used with a local inner class? Ans: A local inner class may be final or abstract. Q.What is the difference between static and non-static variables? Ans: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. Q.What is the difference between the paint() and repaint() methods? Ans: The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. Q.What is the purpose of the File class? Ans: The File class is used to create objects that provide access to the files and directories of a local file system. Q.Can an exception be rethrown? Ans: Yes, an exception can be rethrown. Q.Which Math method is used to calculate the absolute value of a number? Ans: The abs() method is used to calculate absolute values. Q.How does multithreading take place on a computer with a single CPU? Ans: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. Q.When does the compiler supply a default constructor for a class? Ans: The compiler supplies a default constructor for a class if no other constructors are provided. Q.When is the finally clause of a try-catch-finally statement executed? Ans: The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. Q.Which class is the immediate superclass of the Container class? Ans: Component Q.If a method is declared as protected, where may the method be accessed? Ans: A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. Q.How can the Checkbox class be used to create a radio button? Ans: By associating Checkbox objects with a CheckboxGroup. Q.Which non-Unicode letter characters may be used as the first character of an identifier? Ans: The non-Unicode letter characters $ and _ may appear as the first character of an identifier Q.What restrictions are placed on method overloading? Ans:Two methods may not have the same name and argument list but different return types. Q.What happens when you invoke a thread's interrupt method while it is sleeping or waiting? Ans: When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. Q.What is casting? Ans: There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. Q.What is the return type of a program's main() method? Ans: A program's main() method has a void return type. Q.Name four Container classes. Ans: Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane Q.What is the difference between a Choice and a List? Ans: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. Q.What class of exceptions are generated by the Java run-time system? Ans: The Java runtime system generates RuntimeException and Error exceptions. Q.What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams. Q.What is the difference between a field variable and a local variable? Ans: A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. Q.Under what conditions is an object's finalize() method invoked by the garbage collector? Ans: The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. Q.How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q.What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? Ans: A method's throws clause must declare any checked exceptions that are not caught within the body of the method. Q.What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1? Ans: The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events. Q.How is it possible for two String objects with identical values not to be equal under the == operator? Ans: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. Q.Why are the methods of the Math class static? Ans: So they can be invoked as if they are a mathematical code library. Q.What Checkbox method allows you to tell if a Checkbox is checked? Ans: getState() Q.What state is a thread in when it is executing? Ans: An executing thread is in the running state. Q.What are the legal operands of the instanceof operator? Ans: The left operand is an object reference or null value and the right operand is a class, interface, or array type. Q.How are the elements of a GridLayout organized? Ans: The elements of a GridBad layout are of equal size and are laid out using the squares of a grid. Q.What an I/O filter? Ans: An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Q.If an object is garbage collected, can it become reachable again? Ans: Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. Q.What is the Set interface? Ans: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. Q.What classes of exceptions may be thrown by a throw statement? Ans: A throw statement may throw any expression that may be assigned to the Throwable type. Q.What are E and PI? Ans: E is the base of the natural logarithm and PI is mathematical value pi. Q.Are true and false keywords? Ans: The values true and false are not keywords. Q.What is a void return type? Ans: A void return type indicates that a method does not return a value. Q.What is the purpose of the enableEvents() method? Ans: The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods. Q.What is the difference between the File and RandomAccessFile classes? Ans: The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. Q.What happens when you add a double value to a String? Ans: The result is a String object. Q.What is your platform's default character encoding? Ans: If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.. Java Interview Questions Java Interview Questions and Answers Q.Which package is always imported by default? Ans: The java.lang package is always imported by default. Q.What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q.How are this and super used? Ans: this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. Q.What is the purpose of garbage collection? Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. Q.What is a compilation unit? Ans: A compilation unit is a Java source code file. Q.What interface is extended by AWT event listeners? Ans: All AWT event listeners extend the java.util.EventListener interface. Q.What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method. Q.How can a dead thread be restarted? Ans: A dead thread cannot be restarted. Q.What happens if an exception is not caught? Ans: An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. Q.What is a layout manager? Ans: A layout manager is an object that is used to organize components in a container. Q.Which arithmetic operations can result in the throwing of an ArithmeticException? Ans: Integer / and % can result in the throwing of an ArithmeticException. Q.What are three ways in which a thread can enter the waiting state? Ans: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Q.Can an abstract class be final? Ans: An abstract class may not be declared as final. Q.What is the ResourceBundle class? Ans: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. Q.What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement? Ans: The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. Q.What is numeric promotion? Ans: Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. Q.What is the difference between a Scrollbar and a ScrollPane? Ans: A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. Q.What is the difference between a public and a non-public class? Ans: A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. Q.To what value is a variable of the boolean type automatically initialized? Ans: The default value of the boolean type is false. Q.Can try statements be nested? Ans: Try statements may be tested. Q.What is the difference between the prefix and postfix forms of the ++ operator? Ans: The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. Q.What is the purpose of a statement block? Ans: A statement block is used to organize a sequence of statements as a single statement group. Q.What is a Java package and how is it used? Ans: A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. Q.What modifiers may be used with a top-level class? Ans: A top-level class may be public, abstract, or final. Q.What are the Object and Class classes used for? Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. Q.How does a try statement determine which catch clause should be used to handle an exception? Ans: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. Q.Can an unreachable object become reachable again? Ans: An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. Q.When is an object subject to garbage collection? Ans: An object is subject to garbage collection when it becomes unreachable to the program in which it is used. Q.What method must be implemented by all threads? Ans: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Q.What methods are used to get and set the text label displayed by a Button object? Ans: getLabel() and setLabel() Q.Which Component subclass is used for drawing and painting? Ans: Canvas Q.What are synchronized methods and synchronized statements? Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q.What are the two basic ways in which classes that can be run as threads may be defined? Ans: A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface. Q.What are the problems faced by Java programmers who don't use layout managers? Ans: Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system. Q.What is the difference between an if statement and a switch statement? Ans: The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. Q.What is the List interface? Ans: The List interface provides support for ordered collections of objects. Servlets and JSP Q.What are Servlets? Ans: Servlets are small program which execute on the web server. They run under web server environment exploiting the functionalities of the web server. Q.What are advantages of servlets over CGI? Ans: In CGI for every request there is a new process started which is quiet an overhead. In servlets JVM stays running and handles each request using a light weight thread. In CGI if there are 1000 request then 1000 CGI program is loaded in memory while in servlets there are 1000 thread and only one copy of the servlet class. Q.Can you explain Servlet life cycle? There are three methods which are very important in servlet life cycle i.e. "init”, "service" and "destroy". Server invokes "init ()" method when servlet is first loaded in to the web server memory. Servlet reads HTTP data provided in HTTP request in the "service ()" method. Once initialized servlet remains in memory to process subsequent request. So for every HTTP request "service ()" method of the servlet is called. Finally when server unloads the "servlet ()" from the memory it calls the "destroy" method which can be used to clean up any resource the servlet is consuming. Q.What are the two important API’s in for Servlets? Ans: Two important packages are required to build servlet "javax.servlet" and "javax.servlet.http". They form the core of Servlet API. Servlets are not part of core Java but are standard extensions provided by Tomcat. Q.Can you explain in detail “javax.servlet” package? Ans: javax.servlet package has interfaces and classes which define a framework in which servlets can operate. Let’s first make a walk through of all the interfaces and methods and its description. Interfaces in javax.servlet Servlet Interface This interface has the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. Following are the method in Servlet interface :- void destroy( ):- Executed when servlet is unloaded from the web server memory. ServletConfig getServletConfig() :- Returns back a ServletConfig object that contains initialization data. String getServletInfo( ):- Returns a string describing the servlet. init method :- Called for first time when the servlet is initialized by the web server. void service() method :- Called to process a request from a client. ServletConfig Interface This interface is implemented by the servlet container. Servlet can access any configuration data when its loaded. The methods declared by this interface are summarized here: Following are the methods in ServletConfig interface:- ServletContext getServletContext():- Gives the servlet context. String getInitParameter(String param):- Returns the value of the initialization parameter named param. Enumeration getInitParameterNames() :- Returns an enumeration of all initialization parameter names. String getServletName( ) :- Returns the name of the invoking servlet. Q.What’s the use of ServletContext? Ans: ServletContext Interface It gives information about the environment. It represents a Servlet's view of the Web Application.Using this interface servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects. Following are the methods defined in ServletContext Interface Object getAttribute(String attr) :- Returns the value of the server attribute named attr. String getMimeType(String file) :- Gives MIME type for a file. String getRealPath(String vpath) :- Gives the actual physical path for a virtual path. String getServerInfo( ) :- You can get the server information using this function. void log(String s) :- Used to write to server log. void log(String s, Throwable e) :- Writes s and the stack trace for e to the servlet log. void setAttribute(String attr, Object val) :- Sets the attribute specified by attr to the value passed in val. ServletRequest Interface The ServletRequest interface is implemented by the servlet container. It gives data regarding client request. Following are the methods defined in ServletRequest Interface Object getAttribute(String attr) :- Returns the value of the attribute named attr. String getCharacterEncoding( ) :- Returns the character encoding of the request. int getContentLength( ) :- Gives the size of the request. If no size is there then it returns -1. String getContentType( ) :- Returns the type of the request. A null value is returned if the type cannot be determined. ServletInputStream getInputStream( ) :- Returns a ServletInputStream that can be used to read binary data from the request. String getParameter(String pname) :- Returns the value of the parameter named pname. Enumeration getParameterNames( ) :- Returns an enumeration of the parameter names for this request. String getParameterValues(String name) :- Returns an array containing values associated with the parameter specified by name. String getProtocol( ) :- Gives back protocol description. BufferedReader getReader( ) :- Returns a buffered reader that can be used to read text from the request. String getRemoteAddr() :-Returns client IP address. String getRemoteHost() :- Returns client host name. String getScheme( ) :- Return what’s the transmission protocol HTTP , FTP etc. String getServerName() :- Returns the name of the server. int getServerPort() :- Returns the port number. ServletResponse Interface The ServletResponse interface is implemented by the servlet containerUsed to give response back to the client. Following are the methods defined in ServletResponse Interface String getCharacterEncoding() :- Returns back character encoding. ServletOutputStream getOutputStream() :- Returns a ServletOutputStream that can be used to write binary data to the response. PrintWriter getWriter() :- Returns a PrintWriter that can be used to write character data to the response. void setContentLength(int size) :- Sets the content length for the response to size. void setContentType(String type) :- Sets the content type for the response to type. GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. void log(String s) void log(String s, Throwable e) Here, s is the string to be appended to the log, and e is an exception that occurred. Now let’s revise through different classes. ServletInputStream Class This class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. int readLine(byte buffer, int offset, int size) :- Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered. ServletOutputStream Class The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the “print()” and “println()” methods, which output data to the stream. Servlet Exception Classes javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is unavailableException, which extends ServletException. It indicates that a servlet is unavailable. Q.What's the difference between GenericServlet and HttpServlet? Ans: HttpServlet class extends GenericServlet class which is an abstract class to provide HTTP protocol-specific functionalities. Most of the java application developers extend HttpServlet class as it provides more HTTP protocol-specific functionalities. You can see in HttpServlet class doGet (), doPOst () methods which are more targeted towards HTTP protocol specific functionalities. For instance we can inherit from GenericServlet class to make something like MobileServlet. So GenericServlet class should be used when we want to write protocol specific implementation which is not available. But when we know we are making an internet application where HTTP is the major protocol its better to use HttpServlet. Q.Can you explain in detail javax.servlet.http package? Ans: The javax.servlet.http package inherits from “javax.servlet” package and supplies HTTP protocol specific functionalities for JAVA developers. If you are aiming at developing HTTP application you will find “javax.servlet.HTTP” more comfortable than “javax.servlet”. So let’s revisit through the interfaces and methods HttpServletRequest Interface Below are the lists of methods in HttpServletRequest Interface:- String getAuthType( ):- Returns the type of authentication. Cookie getCookies( ) :- Returns the collection of cookies for the request. long getDateHeader(String field) :- Returns the value of the date header field named field. String getHeader(String field) :- Returns the value of the header field named field. Enumeration getHeaderNames( ) :- Returns an enumeration of the header names. int getIntHeader(String field) :- Returns the int equivalent of the header field named field. String getMethod( ) :- What type of method does this request have POST , GET etc. String getPathInfo( ) :- Returns any path information that is located after the servlet path and before a query string of the URL. String getPathTranslated( ) :- Returns any path information that is located after the servlet path and before a query string of the URL after translating it to a real path. String getQueryString( ) :- Returns any query string in the URL. String getRemoteUser( ) :- Returns the name of the user who issued this request. String getRequestedSessionId( ) :- Returns the ID of the session. String getRequestURI( ) :- Returns the URI. StringBuffer getRequestURL( ) :- Returns the URL. String getServletPath( ) :- Returns that part of the URL that identifies the servlet. HttpSession getSession( ) :- Returns the session for this request. If a session does not exist, one is created and then returned. HttpSession getSession(boolean new) :- If new is true and no session exists, creates and returns a session for this request. Otherwise, returns the existing session for this request. This section is explained in more detail in further questions. boolean isRequestedSessionIdFromCookie( ) :- Returns true if the cookie has the session id. boolean isRequestedSessionIdFromURL( ) :- Gives true if the URL has session id. boolean isRequestedSessionIdValid( ) :- Return true if the session is valid in the current context. HttpServletResponse Interface The HttpServletResponse interface is implemented by the servlet container. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. Below are the methods and functions for the interface void addCookie(Cookie cookie) :-Adds cookie to the HTTP response. String encodeURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs generated by a servlet should be processed by this method. String encodeRedirectURL(String url) :- Determines if the session ID must be encoded in the URL identified as url. If so, returns the modified version of URL. Otherwise, returns URL. All URLs passed to sendRedirect( ) should be processed by this method. void sendError(int c) :- Sends the error code c to the client. void sendError(int c, String s) :- Sends the error code c and message s to the client. void sendRedirect(String url) :- Redirects the client to url. void setDateHeader(String field, long msec) :- Adds field to the header with date value equal to msec (milliseconds since midnight, January 1, 1970, GMT). void setHeader(String field, String value) :- Adds field to the header with value equal to value. void setIntHeader(String field, int value) :- Adds field to the header with value equal to value. void setStatus(int code) :- Sets the status code for this response to code. HttpSession Interface HTTP protocol is a stateless protocol and this interface enables to maintain sessions between requests. Object getAttribute(String attr) :- Returns the value associated with the name passed in attr. Returns null if attr is not found. Enumeration getAttributeNames( ) :- Returns an enumeration of the attribute names associated with the session. long getCreationTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when this session was created. String getId( ) :- Returns the session ID. long getLastAccessedTime( ) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the client last made a request for this session. void invalidate() :- Invalidates this session and removes it from the context. boolean isNew( ) :- Returns true if the server created the session and it has not yet been accessed by the client. void removeAttribute(String attr) :- Removes the attribute specified by attr from the session. void setAttribute(String attr, Object val) :- Associates the value passed in val with the attribute name passed in attr. HttpSessionBindingListener The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound are void valueBound(HttpSessionBindingEvent e) voidvalueUnbound(HttpSessionBindingEvent e) Here, e is the event object that describes the binding. Cookie Class The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user's name, address, and other information. The user does not need to enter this data each time he or she visits the store. A servlet can write a cookie to a user's machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. The names and values of cookies are stored on the user's machine. Some of the information that is saved for each cookie includes name of the cookie, value of the cookie, expiration date of the cookie and domain/path of the cookie. The expiration date determines when this cookie is deleted from the user's machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user's machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here: Cookie(String name, String value) :- Here, the name and value of the cookie are supplied as arguments to the constructor. The methods of the Cookie class are Object clone( ) :- Returns a copy of this object. String getComment( ) :- Returns the comment. String getDomain( ) :- Returns the domain. int getMaxAge( ) :- Returns the maximum age (in seconds). String getName( ) :- Returns the name. String getPath( ) :- Returns the path. boolean getSecure( ) :- Returns true if the cookie is secure. Otherwise, returns false. String getValue( ) :- Returns the value. int getVersion( ) :- Returns the version. void setComment(String c) :- Sets the comment to c. void setDomain(String d) :- Sets the domain to d. void setMaxAge(int secs) :- Sets the maximum age of the cookie to secs. This is the number of seconds after which the cookie is deleted. void setPath(String p) :- Sets the path to p. void setSecure(boolean secure) :- Sets the security flag to secure. void setValue(String v) :- Sets the value to v. void setVersion(int v) :- Sets the version to v. HttpServlet Class The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP DELETE. void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP GET. void doOptions(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP OPTIONS. void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP POST. void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP PUT. void doTrace(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Handles an HTTP TRACE. long getLastModified(HttpServletRequest req) :- Returns the time (in milliseconds since midnight, January 1, 1970, GMT) when the requested resource was last modified. void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException :- Called by the server when an HTTP request arrives for this servlet. The arguments provide access to the HTTP request and response, respectively. HttpSessionEvent Class HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a change occurs to the session. HttpSession getSession( ) It returns the session in which the event occurred. The HttpSessionBindingEvent Class The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val) Here, session is the source of the event, and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in Val. String getName( ) :- The getName( ) method obtains the name that is being bound or unbound. Its constructor is shown here: HttpSession getSession( ) :- The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound: Object getValue( ) :- The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is shown here: Q.What’s the architecture of a Servlet package? Ans: In the previous questions we saw all the servlet packages. But the basic architecture of the servlet packages is as shown below. At the top of all is the main servlet interface which is implemented by the generic servlet. But generic servlet does not provide implementation specific to any protocol. HTTP servlet further inherits from the generic servlet and provides HTTP implementation like “Get” and “Post”. Finally comes our custom servlet which inherits from HTTP Servlet. Q.Why is HTTP protocol called as a stateless protocol? Ans: A protocol is stateless if it can remember difference between one client request and the other. HTTP is a stateless protocol because each request is executed independently without any knowledge of the requests that came before it. Above is a pictorial presentation of how a stateless protocol operates. User first sends “request1” and server responds with “response1”. When the same user comes back with “request2” server treats this as new user and has no idea that it’s the same user who has come with the request. In short every request is a new request for the HTTP protocol so it’s called as a stateless protocol. Q.What are the different ways we can maintain state between requests? Ans: Following are the different ways of maintaining state’s between stateless requests:- √ URL rewriting √ Cookies √ Hidden fields √ Sessions Q.What is URL rewriting? Ans: It’s based on the concept of attaching a unique ID (which is generated by the server) in the URL of response from the server. So the server attaches this unique ID in each URL. When the client sends a requests it sends back this ID with the request also which helps the server to identify the client uniquely. Below is a snippet which is extracted from the code which is provided in the CD. In this sample we have generated a unique ID using the random class of java. This unique ID is then sent in the query string (see step 3 of the above snippet) back to the client. When the client comes back to the server the server first gets the token value from the query string and thus identifying the client uniquely. Q.What’s the difference between getSession(true) and getSession(false) ? Ans: Session's can be considered as a series of related interactions between client and the server that take place over a period of time. Because HTTP is a stateless protocol these series of interactions are difficult to track. That’s where we can use HttpSession object to save in between of these interactions so that server can co-relate between interactions between clients. Above is the code snippet which displays session data. Step1 returns an HttpSession object from the request object. “true” parameter in the “getsession” function ensures that we get a session object if there is no current session object in request which ensures that we never get a null session object. In Step 2 we are using the “getattribute” function to return the session value. In step 3 we are setting the session value with “Name” key. Q.Which are the different ways you can communicate between servlets? Ans: Below are the different ways of communicating between servlets:- √Using RequestDispatcher object. √Sharing resource using “ServletContext ()” object. √Servlet chaining. Q.What are filters in JAVA? Ans: Filters are nothing but simple java classes which can manipulate request before it reaches the resource on the web server. Resource can be a HTML file, servlet class, JSP etc. It can also intercept responses sent back to client and thus can manipulate the response before they reach the client browser. Q.what’s the difference between Authentication and authorization? Ans: Authentication is the process the application identifies that you are who. For example when a user logs into an application with a username and password, application checks that the entered credentials against its user data store and responds with success or failure. Authorization, on the other hand, is when the application checks to see if you're allowed to do something. For instance are you allowed to do delete or modify a resource. Q.Explain in brief the directory structure of a web application? Ans: Below is the directory structure of a web application:- webapp/ WEB-INF/web.xml WEB-INF/classes WEB-INF/lib √The webapp directory contains the JSP files, images, and HTML files. The webapp directory can also contain subdirectories such as images or html or can be organized by function, such as public or private. √The WEB-INF/web.xml file is called the deployment descriptor for the Web application. This file contains configuration information for the Web application, including the mappings of URLs to servlets and filters. The web.xml file also contains configuration information for security, MIME type mapping, error pages, and locale settings √The WEB-INF/classes directory contains the class files for the servlets, JSP files, tag libraries, and any other utility classes that are used in the Web application. √The WEB-INF/lib directory contains JAR files for libraries that are used by the Web application. These are generally third-party libraries or classes for any tag libraries used by the Web application. Q.Can you explain JSP page life cycle? Ans: When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same. √JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation. √Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated. √When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes. Q.What is EL? Ans: EL stands for expression language. An expression language makes it possible to easily access application data.In the below expression amountofwine variable value will be rendered. There are ${amountofwine} litres of wine in the bottle. Q.how does EL search for an attribute? Ans: EL parser searches the attribute in following order: √Page √Request √Session (if it exists) √Application If no match is found for then it displays empty string. Q.What are the implicit EL objects in JSP? Ans: Following are the implicit EL objects:- PageContext: The context for the JSP page. Provides access to various objects for instance:- servletContext: The context for the JSP page's servlet and any web components contained in the same application. session: The session object for the client. request: The request triggering the execution of the JSP page. response: The response returned by the JSP page. See Constructing Responses. In addition, several implicit objects are available that allow easy access to the following objects: param: Maps a request parameter name to a single value paramValues: Maps a request parameter name to an array of values header: Maps a request header name to a single value headerValues: Maps a request header name to an array of values cookie: Maps a cookie name to a single cookie initParam: Maps a context initialization parameter name to a single value Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects. pageScope: Maps page-scoped variable names to their values requestScope: Maps request-scoped variable names to their values sessionScope: Maps session-scoped variable names to their values applicationScope: Maps application-scoped variable names to their values For instance the below snippet will indentify the browser used by the client. Browser: ${header} Q.How can we disable EL? Ans: You can disable using isELIgnored attribute of the page directive: Q.Can you explain in short what the different types of JSTL tags are? Ans: Tags are classified in to four groups:- √Core tags √ Formatting tags √ XML tags √SQL tags Core tags for conditional flow and for iteration ....... for selective flow between mutually exclusive code and for working with scoped variables for rendering the value of variables and expressions for working with Java exceptions for creating and working with URLs Formatting tags Used to format and display text, the date, the time, and numbers. Below are some frequently used tags:- : To render numerical value with specific precision or format : To render date and time values in a specific format (and according to international locale-specific conventions) : To display an internationalized message (for example, a message in a different language using a different character set) XML tags XML tags are meant to process XML data. It supports data-parsing, transforming XML, plus data and flow control based on XPath expressions. These tags are used only when you need to work directly, within the JSP, with XML data. SQL tags They are designed to work directly with SQL tags. But most of the time you will see they are used for prototyping and not for final product. Just before we move ahead with some other questions. Let’s how do we install JSTL so that everything works. Below are three installation steps:- √Unzip "jakarta-taglibs-standard-1.1.2.zip" and you will see two files jstl.jar and standard.jar in lib directory. √Copy both jstl.jar and standard.jar to "\webapps\ROOT\WEB-INF\lib" directory in tomcat. √Copy all tld files from the unzipped location to \webapps\ROOT\WEB-INF" directory. √Modify the web.xml file to include all TLD files. Below is snippet of some tld's included in web.xml file. http://java.sun.com/jstl/fmt /WEB-INF/fmt.tld http://java.sun.com/jstl/fmt-rt /WEB-INF/fmt-rt.tld http://java.sun.com/jstl/core /WEB-INF/c.tld http://java.sun.com/jstl/core-rt /WEB-INF/c-rt.tld http://java.sun.com/jstl/sql /WEB-INF/sql.tld http://java.sun.com/jstl/sql-rt /WEB-INF/sql-rt.tld http://java.sun.com/jstl/x /WEB-INF/x.tld http://java.sun.com/jstl/x-rt /WEB-INF/x-rt.tld Q.What are JSP directives? Ans: JSP directives do not produce any output. They are used to set global values like class declaration, content type etc. Directives have scope for entire JSP file. They start with . There are three main directives that can be used in JSP:- √page directive √ include directive √ taglib directive Q.what are Page directives? Ans: Page directive is used to define page attributes the JSP file. Below is a sample of the same:- To summarize some of the important page attributes:- import :- Comma separated list of packages or classes, just like import statements in usual Java code. session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable. buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value. isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet. errorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing. Q.what’s the difference between JavaBeans and taglib directives? Ans: JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:- √Taglib are for generating presentation elements while JavaBeans are good for storing information and state. √Use custom tags to implement actions and JavaBeans to present information. Q.what are the different scopes an object can have in a JSP page? Ans: There are four scope which an object can have in a JSP page:- Page Scope Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's a vailable to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application. Q.what are different Authentication Options available in servlets? Ans: There are four ways of authentication:- √ HTTP basic authentication √ HTTP digest authentication √ HTTPS client authentication √ Form-based authentication Let’s try to understand how the above four ways work. HTTP basic authentication In HTTP basic authentication the server uses the username and password send by the client. The password is sent using simple base64 encoding but it’s not encrypted. HTTP digest authentication HTTP digest authentication is same as HTTP basic authentication but the biggest difference is password is encrypted and transmitted using SHA or MD5. HTTPS client authentication HTTPS client authentication is based on HTTP over SSL. It requires that the end client should possess a PKC (Public Key Certificate). This verifies the browsers identity. Form-based authentication In FORM-based the web container invokes a login page. The invoked login page is used to collect username and password. Q.What is the difference between Servletcontext and ServletConfig ? Ans: ServletConfig contains configuration data for the servlet in the form of name and value pairs.Using the ServletConfigwe get reference to the ServletContext object. ServletContext gives the servlet access to information about its runtime environment such as web server logging facilities, version info, URL details, web server attributes etc. Q.How do we prevent browser from caching output of my JSP pages? Ans: You can prevent pages from caching JSP pages output using the below code snippet. Q.Can we explicitly destroy a servlet object? Ans: No we can not destroy a servlet explicitly its all done by the container. Even if you try calling the destroy method container does not respond to it. contact for more on Java Online Training
Continue reading
PHP Interview Questions
Q.What's PHP? Ans: The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. Q.What Is a Session? Ans: A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor. Q.What is meant by PEAR in php? Answer1: PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages" Answer2: PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide: A structured library of open-sourced code for PHP users A system for code distribution and package maintenance A standard style for code written in PHP The PHP Foundation Classes (PFC), The PHP Extension Community Library (PECL), A web site, mailing lists and download mirrors to support the PHP/PEAR community PEAR is a community-driven project with the PEAR Group as the governing body. The project has been founded by Stig S. Bakken in 1999 and quite a lot of people have joined the project since then. Q.How can we know the number of days between two given dates using PHP? Ans: Simple arithmetic: $date1 = date('Y-m-d'); $date2 = '2006-07-01'; $days = (strtotime() - strtotime()) / (60 * 60 * 24); echo "Number of days since '2006-07-01': $days"; Q.How can we repair a MySQL table? Ans: The syntex for repairing a mysql table is: REPAIR TABLE tablename REPAIR TABLE tablename QUICK REPAIR TABLE tablename EXTENDED This command will repair the table specified. If QUICK is given, MySQL will do a repair of only the index tree. If EXTENDED is given, it will create index row by row. Q.What is the difference between $message and $$message? Anwser 1: $message is a simple variable whereas $$message is a reference variable. Example: $user = 'bob' is equivalent to $holder = 'user'; $$holder = 'bob'; Anwser 2: They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var. Q.What Is a Persistent Cookie? Ans: A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences: Temporary cookies can not be used for tracking long-term information. Persistent cookies can be used for tracking long-term information. Temporary cookies are safer because no programs other than the browser can access them. Persistent cookies are less secure because users can open cookie files see the cookie values. Q.What does a special set of tags do in PHP? Ans: What does a special set of tags do in PHP? The output is displayed directly to the browser. Q.How do you define a constant? Ans: Via define() directive, like define ("MYCONSTANT", 100); Q.What are the differences between require and include, include_once? Anwser 1: require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again. But require() and include() will do it as many times they are asked to do. Anwser 2: The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. The major difference between include() and require() is that in failure include() produces a warning message whereas require() produces a fatal errors. Anwser 3: All three are used to an include file into the current page. If the file is not present, require(), calls a fatal error, while in include() does not. The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists. Anwser 4: File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc. Q.What is meant by urlencode and urldecode? Anwser 1: urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25". URL encoded strings are safe to be used as part of URLs. urldecode() returns the URL decoded version of the given string. Anwser 2: string urlencode(str) - Returns the URL encoded version of the input string. String values to be used in URL query string need to be URL encoded. In the URL encoded version: Alphanumeric characters are maintained as is. Space characters are converted to "+" characters. Other non-alphanumeric characters are converted "%" followed by two hex digits representing the converted character. string urldecode(str) - Returns the original string of the input URL encoded string. For example: $discount ="10.00%"; $url = "http://domain.com/submit.php?disc=".urlencode($discount); echo $url; You will get "http://domain.com/submit.php?disc=10%2E00%25". Q.How To Get the Uploaded File Information in the Receiving Script? Ans: Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as: $_FILES - The Original file name on the browser system. $_FILES - The file type determined by the browser. $_FILES - The Number of bytes of the file content. $_FILES - The temporary filename of the file in which the uploaded file was stored on the server. $_FILES - The error code associated with this file upload. The $fieldName is the name used in the . Q.What is the difference between mysql_fetch_object and mysql_fetch_array? Ans: MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array Q.How can I execute a PHP script using command line? Ans: Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program. Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment. Q.I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem? Ans: PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems. Q.Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example? Ans: In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces. Q.What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the following syntax: create table employee(eno int(2),ename varchar(10))? Ans: Total 5 types of tables we can create 1. MyISAM 2. Heap 3. Merge 4. INNO DB 5. ISAM MyISAM is the default storage engine as of MySQL 3.23. When you fire the above create query MySQL will create a MyISAM table. Q.How To Create a Table? Ans: If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script: Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this: Table fyi_links created. Q.How can we encrypt the username and password using PHP? Answer1 You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password"); Answer2 You can use the MySQL PASSWORD() function to encrypt username and password. For example, INSERT into user (password, ...) VALUES (PASSWORD($password”)), ...); Q.How do you pass a variable by value? Ans: Just like in C++, put an ampersand in front of it, like $a = &$b Q.WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()? Ans: string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive. stristr() is idential to strstr() except that it is case insensitive. Q.When are you supposed to use endif to end the conditional statement? Ans: When the original if was followed by : and then the code block without braces. Q.How can we send mail using JavaScript? Ans: No. There is no way to send emails directly using JavaScript. But you can use JavaScript to execute a client side email program send the email using the "mailto" code. Here is an example: function myfunction(form) { tdata=document.myform.tbox1.value; location="mailto:mailid@domain.com?subject=..."; return true; } Q.What is the functionality of the function strstr and stristr? Ans: strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr("user@example.com","@") will return "@example.com". stristr() is idential to strstr() except that it is case insensitive. Q.What is the difference between ereg_replace() and eregi_replace()? Ans: eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters. Q.How do I find out the number of parameters passed into function9. ? func_num_args() function returns the number of parameters passed in. Q.What is the purpose of the following files having extensions: frm, myd, and myi? What these files contain? Ans: In MySQL, the default table type is MyISAM. Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. The '.frm' file stores the table definition. The data file has a '.MYD' (MYData) extension. The index file has a '.MYI' (MYIndex) extension, Q.If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? Ans: 5, it’s a reference to existing variable. Q.Write a query for the following question Ans: The table tbl_sites contains the following data: --------------------------------------- Userid sitename country --------------------------------------- 1 sureshbabu indian 2 PHPprogrammer andhra 3 PHP.net usa 4 PHPtalk.com germany 5 MySQL.com usa 6 sureshbabu canada 7 PHPbuddy.com pakistan 8. PHPtalk.com austria 9. PHPfreaks.com sourthafrica 10. PHPsupport.net russia 11. sureshbabu australia 12. sureshbabu nepal 13. PHPtalk.com italy Q.Write a select query that will be displayed the duplicated site name and how many times it is duplicated? Ans: SELECT sitename, COUNT(*) AS NumOccurrences FROM tbl_sites GROUP BY sitename HAVING COUNT(*) > 1 Q.How To Protect Special Characters in Query String? Ans: If you want to include special characters like spaces in the query string, you need to protect them by applying the urlencode() translation function. The script below shows how to use urlencode(): print(""); print(" Please click the links below" ." to submit comments about FYICenter.com: "); $comment = 'I want to say: "It\'s a good site! :->"'; $comment = urlencode($comment); print(" " ."" ."It's an excellent site! "); $comment = 'This visitor said: "It\'s an average site! :-("'; $comment = urlencode($comment); print(" " .'' ."It's an average site. "); print(""); ?> Q.Are objects passed by value or by reference? Ans: Everything is passed by value. Q.What are the differences between DROP a table and TRUNCATE a table? Ans: DROP TABLE table_name - This will delete the table and its data. TRUNCATE TABLE table_name - This will delete the data of the table, but not the table definition. Q.What are the differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods? Anwser 1: When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn't display these values. Anwser 2: When you want to send short or small data, not containing ASCII characters, then you can use GET” Method. But for long data sending, say more then 100 character you can use POST method. Once most important difference is when you are sending the form with GET method. You can see the output which you are sending in the address bar. Whereas if you send the form with POST” method then user can not see that information. Anwser 3: What are "GET" and "POST"? GET and POST are methods used to send data to the server: With the GET method, the browser appends the data onto the URL. With the Post method, the data is sent as "standard input." Major Difference In simple words, in POST method data is sent by standard input (nothing shown in URL when posting while in GET method data is sent through query string. Ex: Assume we are logging in with username and password. GET: we are submitting a form to login.php, when we do submit or similar action, values are sent through visible query string (notice ./login.php?username=...&password=... as URL when executing the script login.php) and is retrieved by login.php by $_GET and $_GET. POST: we are submitting a form to login.php, when we do submit or similar action, values are sent through invisible standard input (notice ./login.php) and is retrieved by login.php by $_POST and $_POST. POST is assumed more secure and we can send lot more data than that of GET method is limited (they say Internet Explorer can take care of maximum 2083 character as a query string). Anwser 4: In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method. Anwser 5: When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn't display value with URL. It passes value in the form of Object and we can submit large data from the form. Anwser 6: On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method. On the browser side, the difference is that data submitted by the GET method will be displayed in the browser’s address field. Data submitted by the POST method will not be displayed anywhere on the browser. GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data. Q.How do you call a constructor for a parent class? Ans: parent::constructor($value) Q.WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP? Ans: Here are three basic types of runtime errors in PHP: 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior. 2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination. 3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place. Internally, these variations are represented by twelve different error types Q.What’s the special meaning of __sleep and __wakeup? Ans: __sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them. Q.How can we submit a form without a submit button? Ans: If you don't want to use the Submit button to submit a form, you can use normal hyper links to submit a form. But you need to use some JavaScript code in the URL of the link. For example: Submit Me Q.Why doesn’t the following code print the newline properly? Ans: Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters - \ and n. Q.Would you initialize your strings with single quotes or double quotes? Ans: Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution. Q.How can we extract string 'abc.com ' from a string http://info@abc.com using regular expression of php? Ans: We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern. For example: preg_match("/.*@(.*)$/","http://info@abc.com",$data);echo $data; Q.What is the difference between the functions unlink and unset? Ans: unlink() is a function for file system handling. It will simply delete the file in context. unset() is a function for variable management. It will make a variable undefined. Q.How come the code works, but doesn’t for two-dimensional array of mine? Ans: Any time you have an array with more than one dimension, complex parsing syntax is required. print "Contents: {$arr}" would’ve worked. Q.How can we register the variables into a session? Ans: session_register($session_var); $_SESSION = 'value'; Q.What is the difference between characters \023 and \x23? Ans: The first one is octal 23, the second is hex 23. Q.How can we submit form without a submit button? Ans: We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example: Q.How can we create a database using PHP and mysql? Ans: We can create MySQL database with the use of mysql_create_db($databaseName) to create a database. Q.How many ways we can retrieve the date in result set of mysql using php? Ans: As individual objects so single record or as a set or arrays. Q.Can we use include ("abc.php") two times in a php page "makeit.php"? Ans: Yes. Q.For printing out strings, there are echo, print and printf. Explain the differences. Ans: echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like: and it will output the string "Welcome to fyicenter!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf. Q.I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP? Ans: On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split(). Q.What’s the output of the ucwords function in this example? Ans: $formatted = ucwords("FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS"); print $formatted; What will be printed is FYICENTER IS COLLECTION OF INTERVIEW QUESTIONS. ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first. Q.What’s the difference between htmlentities() and htmlspecialchars()? Ans: htmlspecialchars only takes care of , single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML. Q.How can we extract string "abc.com" from a string "mailto:info@abc.com?subject=Feedback" using regular expression of PHP? Ans: $text = "mailto:info@abc.com?subject=Feedback"; preg_match('|.*@(*)|', $text, $output); echo $output; Note that the second index of $output, $output, gives the match, not the first one, $output. Q.So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()? Ans: Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required. Q.How can we destroy the session, how can we unset the variable of a session? Ans: session_unregister() - Unregister a global variable from the current session session_unset() - Free all session variables Q.What are the different functions in sorting an array? Ans: Sorting functions in PHP: asort() arsort() ksort() krsort() uksort() sort() natsort() rsort() Q.How can we know the count/number of elements of an array? Ans: 2 ways: a) sizeof($array) - This function is an alias of count() b) count($urarray) - This function returns the number of elements in an array. Interestingly if you just pass a simple var instead of an array, count() will return 1. Q.How many ways we can pass the variable through the navigation between the pages? Ans: At least 3 ways: 1. Put the variable into session in the first page, and get it back from session in the next page. 2. Put the variable into cookie in the first page, and get it back from the cookie in the next page. 3. Put the variable into a hidden form field, and get it back from the form in the next page. Q.What is the maximum length of a table name, a database name, or a field name in MySQL? Ans: Database name: 64 characters Table name: 64 characters Column name: 64 characters Q.How many values can the SET function of MySQL take? Ans: MySQL SET function can take zero or more values, but at the maximum it can take 64 values. Q.What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command? Ans: DESCRIBE table_name; Q.How can we find the number of rows in a table using MySQL? Ans: Use this for MySQL SELECT COUNT(*) FROM table_name; Q.What’s the difference between md5(), crc32() and sha1() crypto on PHP? Ans: The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions. Q.How can we find the number of rows in a result set using PHP? Ans: Here is how can you find the number of rows in a result set in PHP: $result = mysql_query($any_valid_sql, $database_link); $num_rows = mysql_num_rows($result); echo "$num_rows rows found"; Q.How many ways we can we find the current date using MySQL? Ans: SELECT CURDATE(); SELECT CURRENT_DATE(); SELECT CURTIME(); SELECT CURRENT_TIME(); Q.Give the syntax of GRANT commands? Ans: The generic syntax for GRANT is as following GRANT on TO IDENTIFIED BY Now rights can be: a) ALL privilages b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name. Q.Give the syntax of REVOKE commands? Ans: The generic syntax for revoke is as following REVOKE on FROM Now rights can be: a) ALL privilages b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc. We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name. Q.What is the difference between CHAR and VARCHAR data types? Ans: CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, "Hello!" will be stored as "Hello! " in CHAR(10) column. VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) column. Q.How can we encrypt and decrypt a data present in a mysql table using mysql? Ans: AES_ENCRYPT() and AES_DECRYPT() Q.Will comparison of string "10" and integer 11 work in PHP? Ans: Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared. Q.What is the functionality of MD5 function in PHP? Ans: string md5(string) It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number. Q.How can I load data from a text file into a table? Ans: The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that: a) Data must be delimited b) Data fields must match table columns correctly Q.How can we know the number of days between two given dates using MySQL? Ans: Use DATEDIFF() SELECT DATEDIFF(NOW(),'2006-07-01'); Q.How can we change the name of a column of a table? Ans: This will change the name of column: ALTER TABLE table_name CHANGE old_colm_name new_colm_name Q.How can we change the data type of a column of a table? Ans: This will change the data type of a column: ALTER TABLE table_name CHANGE colm_name same_colm_name Q.What is the difference between GROUP BY and ORDER BY in SQL? Ans: To sort a result, use an ORDER BY clause. The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any). ORDER BY ,,...; Tells DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on. GROUP BY ,,...; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average. Q.What is meant by MIME? Answer 1: MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image) Some examples of MIME types: audio/x-ms-wmp image/png aplication/x-shockwave-flash Answer 2: Multipurpose Internet Mail Extensions. WWW's ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. … Q.How can we know that a session is started or not? Ans: A session starts by session_start() function. This session_start() is always declared in header portion. it always declares first. then we write session_register(). Q.What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()? Answer 1: mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array. mysql_fetch_object() -> Fetch a result row as an object. mysql_fetch_row() -> Fetch a result set as a regular array(). Answer 2: The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row, $row, etc.), while the latter returns a the results an array containing both numeric and associative keys ($row, $row, etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.). Q.If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why? Ans: Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser. Q.What are the MySQL database files stored in system ? Ans: Data is stored in name.myd Table structure is stored in name.frm Index is stored in name.myi Q.What is the difference between PHP4 and PHP5? Ans: PHP4 cannot support oops concepts and Zend engine 1 is used. PHP5 supports oops concepts and Zend engine 2 is used. Error supporting is increased in PHP5. XML and SQLLite will is increased in PHP5. Q.Can we use include(abc.PHP) two times in a PHP page makeit.PHP”? Ans: Yes we can include that many times we want, but here are some things to make sure of: (including abc.PHP, the file names are case-sensitive) there shouldn't be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php Q.What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()? Ans: mysql_fetch_array - Fetch a result row as an associative array and a numeric array. mysql_fetch_object - Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows mysql_fetch_row() - Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. Q.What is meant by nl2br()? Anwser1: nl2br() inserts a HTML tag before all new line characters \n in a string. echo nl2br("god bless \n you"); output: god bless you Q.How can we encrypt and decrypt a data presented in a table using MySQL? Ans: You can use functions: AES_ENCRYPT() and AES_DECRYPT() like: AES_ENCRYPT(str, key_str) AES_DECRYPT(crypt_str, key_str) Q.How can I retrieve values from one database server and store them in other database server using PHP? Ans: For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database. Q.WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT VERSION OF PHP AND MYSQL? Ans: Rasmus Lerdorf. PHP 5.1. Beta MySQL 5.0 Q.IN HOW MANY WAYS WE CAN RETRIEVE DATA IN THE RESULT SET OF MYSQL USING PHP? Ans: mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both mysql_fetch_assoc - Fetch a result row as an associative array mysql_fetch_object - Fetch a result row as an object mysql_fetch_row —- Get a result row as an enumerated array Q.What are the functions for IMAP? Ans: imap_body - Read the message body imap_check - Check current mailbox imap_delete - Mark a message for deletion from current mailbox imap_mail - Send an email message Q.What are encryption functions in PHP? Ans: CRYPT() MD5() Q.What is the difference between htmlentities() and htmlspecialchars()? Ans: htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely used) htmlentities() - Convert ALL special characters to HTML entities Q.What is the functionality of the function htmlentities? Ans: htmlentities() - Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. Q.How can we get the properties (size, type, width, height) of an image using php image functions? Ans: To know the image size use getimagesize() function To know the image width use imagesx() function To know the image height use imagesy() function Q.How can we increase the execution time of a php script? Ans: By the use of void set_time_limit(int seconds) Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed. When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out. Q.HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT? Answer 1: Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir The full backup file is just a set of SQL statements, so restoring it is very easy: shell> mysql "."Executed"; Answer 2: To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory ’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory mysqldump: Dumping Table Structure and Data Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table. -t, no-create-info Don't write table creation information (the CREATE TABLE statement). -d, no-data Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table! Q.How to set cookies? Ans: setcookie('variable','value','time'); variable - name of the cookie variable value - value of the cookie variable time - expiry time Example: setcookie('Test',$i,time()+3600); Test - cookie variable name $i - value of the variable 'Test' time()+3600 - denotes that the cookie will expire after an one hour Q.How to reset/destroy a cookie Ans: Reset a cookie by specifying expire time in the past: Example: setcookie('Test',$i,time()-3600); // already expired time Reset a cookie by specifying its name only Example: setcookie('Test'); Q.WHAT TYPES OF IMAGES THAT PHP SUPPORTS? Ans: Using imagetypes() function to find out what types of images are supported in your PHP engine. imagetypes() - Returns the image types supported. This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. Q.CHECK IF A VARIABLE IS AN INTEGER IN JAVASCRIPT ? Ans: var myValue =9.8; if(parseInt(myValue)== myValue) alert('Integer'); else alert('Not an integer'); Tools used for drawing ER diagrams. Case Studio Smart Draw Q.How can I know that a variable is a number or not using a JavaScript? Answer 1: bool is_numeric( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise. Answer 2: Definition and Usage The isNaN() function is used to check if a value is not a number. Syntax isNaN(number) Parameter Description number Required. The value to be tested Q.How can we submit from without a submit button? Ans: Trigger the JavaScript code on any event ( like onSelect of drop down list box, onfocus, etc ) document.myform.submit(); This will submit the form. Q.How many ways can we get the value of current session id? Ans: session_id() returns the session id for the current session. Q.How can we destroy the cookie? Ans: Set the cookie with a past expiration time. Q.What are the current versions of Apache, PHP, and MySQL? Ans: PHP: PHP 5.1.2 MySQL: MySQL 5.1 Apache: Apache 2.1 Q.What are the reasons for selecting LAMP (Linux, Apache, MySQL, Php) instead of combination of other software programs, servers and operating systems? Ans: All of those are open source resource. Security of linux is very very more than windows. Apache is a better server that IIS both in functionality and security. Mysql is world most popular open source database. Php is more faster that asp or any other scripting language. Q.What are the features and advantages of OBJECT ORIENTED PROGRAMMING? Ans: One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system. Q.What is the use of friend function? Ans: Friend functions Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match. class mylinkage { private: mylinkage * prev; mylinkage * next; protected: friend void set_prev(mylinkage* L, mylinkage* N); void set_next(mylinkage* L); public: mylinkage * succ(); mylinkage * pred(); mylinkage(); }; void mylinkage::set_next(mylinkage* L) { next = L; } void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; } Friends in other classes It is possible to specify a member function of another class as a friend as follows: class C { friend int B::f1(); }; class B { int f1(); }; It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend. class A { friend class B; }; Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading. Q.How can we get second of the current time using date function? Ans: $second = date("s"); Q.What is the maximum size of a file that can be uploaded using PHP and how can we change this? Ans: You can change maximum size of a file set upload_max_filesize variable in php.ini file Q.How can I make a script that can be bilingual (supports English, German)? Ans: You can change charset variable in above line in the script to support bilanguage. Q.What are the difference between abstract class and interface? Ans: Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class. Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be define by its implemented class. Q.What are the advantages of stored procedures, triggers, indexes? Ans: A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side. Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted. Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks. Q.What is maximum size of a database in mysql? Ans: If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint. The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the number of tables in a database. If the time required to open a file in the directory increases significantly as the number of files increases, database performance can be adversely affected. The amount of available disk space limits the number of tables. MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes (2567 – 1 bytes). With this larger allowed table size, the maximum effective table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits. The InnoDB storage engine maintains InnoDB tables within a tablespace that can be created from several files. This allows a table to exceed the maximum individual file size. The tablespace can include raw disk partitions, which allows extremely large tables. The maximum tablespace size is 64TB. The following table lists some examples of operating system file-size limits. This is only a rough guide and is not intended to be definitive. For the most up-to-date information, be sure to check the documentation specific to your operating system. Operating System File-size Limit Linux 2.2-Intel 32-bit 2GB (LFS: 4GB) Linux 2.4+ (using ext3 filesystem) 4TB Solaris 9/10 16TB NetWare w/NSS filesystem 8TB Win32 w/ FAT/FAT32 2GB/4GB Win32 w/ NTFS 2TB (possibly larger) MacOS X w/ HFS+ 2TB Q.Explain normalization concept? Ans: The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed). First Normal Form The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic). Second Normal Form Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form. Third Normal Form I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table Q.What’s the difference between accessing a class method via -> and via ::? :: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization. Q.What are the advantages and disadvantages of CASCADE STYLE SHEETS? Ans: External Style Sheets Advantages Can control styles for multiple documents at once Classes can be created for use on multiple HTML element types in many documents Selector and grouping methods can be used to apply styles under complex contexts Disadvantages An extra download is required to import style information for each document The rendering of the document may be delayed until the external style sheet is loaded Becomes slightly unwieldy for small quantities of style definitions Embedded Style Sheets Advantages Classes can be created for use on multiple tag types in the document Selector and grouping methods can be used to apply styles under complex contexts No additional downloads necessary to receive style information Disadvantage This method can not control styles for multiple documents at once Inline Styles Advantages Useful for small quantities of style definitions Can override other style specification methods at the local level so only exceptions need to be listed in conjunction with other style methods Disadvantages Does not distance style information from content (a main goal of SGML/HTML) Can not control styles for multiple documents at once Author can not create or control classes of elements to control multiple element types within the document Selector grouping methods can not be used to create complex element addressing scenarios Q.What type of inheritance that php supports? Ans: In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'. Q.How can increase the performance of MySQL select query? Ans: We can use LIMIT to stop MySql for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables. Q.How can we change the name of a column of a table? Ans: MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name or, ALTER TABLE tableName CHANGE OldName newName. Q.When you want to show some part of a text displayed on an HTML page in red font color? What different possibilities are there to do this? What are the advantages/disadvantages of these methods? Ans: There are 2 ways to show some part of a text in red: 1. Using HTML tag 2. Using HTML tag Q.When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)? Ans: When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder. A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML document. For example: Q.What are the different ways to login to a remote server? Explain the means, advantages and disadvantages? Ans: There is at least 3 ways to logon to a remote server: Use ssh or telnet if you concern with security You can also use rlogin to logon to a remote server. Q.Please give a regular expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag. Ans: Try this: /href="(*)"/i Q.How can I use the COM components in php? Ans: The COM class provides a framework to integrate (D)COM components into your PHP scripts. string COM::COM( string module_name ]) - COM class constructor. Parameters: module_name: name or class-id of the requested component. server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini. codepage - specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8. Usage: $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff $word->Selection->TypeText("This is a test…"); $word->Documents->SaveAs("Useless test.doc"); //closing word $word->Quit(); //free the object $word->Release(); $word = null; Q.How many ways we can give the output to a browser? Ans: HTML output PHP, ASP, JSP, Servlet Function Script Language output Function Different Type of embedded Package to output to a browser Q.What is the default session time in php and how can I change it? Ans: The default session time in php is until closing of browser Q.What changes I have to do in php.ini file for file uploading? Ans: Make the following line uncomment like: ; Whether to allow HTTP file uploads. file_uploads = On ; Temporary directory for HTTP uploaded files (will use system default if not ; specified). upload_tmp_dir = C:\apache2triad\temp ; Maximum allowed size for uploaded files. upload_max_filesize = 2M Q.How can I set a cron and how can I execute it in Unix, Linux, and windows? Ans: Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it's called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time. The easiest way to use crontab is via the crontab command. # crontab This command 'edits' the crontab. Upon employing this command, you will be able to enter the commands that you wish to run. My version of Linux uses the text editor vi. You can find information on using vi here. The syntax of this file is very important – if you get it wrong, your crontab will not function properly. The syntax of the file should be as follows: minutes hours day_of_month month day_of_week command All the variables, with the exception of the command itself, are numerical constants. In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows: Minutes: 0-59 Hours: 0-23 Day_of_month: 1-31 Month: 1-12 Weekday: 0-6 We can also include multiple values for each entry, simply by separating each value with a comma. command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file. So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line: 15 8 * * 2 /path/to/scriptname This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content. For our purposes, I'll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell. If you're using an RPM-based system (e.g. Redhat or Mandrake), type the following: # wget help If you are greeted with a wget package identification, it is installed in your system. You could execute the PHP by invoking wget on the URL to the page, like so: # wget http://www.example.com/file.php Now, let's go back to the mailstock.php file we created in the first part of this article. We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I'm located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value. This is what my crontab will look like: 0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php Q.Steps for the payment gateway processing? Ans: An online payment gateway is the interface between your merchant account and your Web site. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer's credit card directly from your Web site. It then passes the transaction off to your merchant bank for processing, commonly referred to as transaction batching Q.How many ways I can redirect a PHP page? Ans: Here are the possible ways of php page redirection. 1. Using Java script: '; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } } redirect('http://maosjb.com'); ?> 2. Using php function: header("Location:http://maosjb.com "); Q.List out different arguments in PHP header function? Ans: void header ( string string ]) Q.What type of headers have to be added in the mail function to attach a file? Ans: $boundary = '--' . md5( uniqid ( rand() ) ); $headers = "From: \"Me\"\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\""; Q.How to store the uploaded file to the final location? Ans: move_uploaded_file ( string filename, string destination) This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination. If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE. If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued. Q.What is the difference between Reply-to and Return-path in the headers of a mail function? Ans: Reply-to: Reply-to is where to delivery the reply of the mail. Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification. Q.Explain about Type Juggling in php? Ans: PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer. An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated. $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) If the last two examples above seem odd, see String conversion to numbers. If you wish to change the type of a variable, see settype(). If you would like to test any of the examples in this section, you can use the var_dump() function. Note: The behavior of an automatic conversion to array is currently undefined. Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above: Q.How can I embed a java programme in php file and what changes have to be done in php.ini file? Ans: There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension. The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process. Example Code: getProperty('java.version') . ''; echo 'Java vendor=' . $system->getProperty('java.vendor') . ''; echo 'OS=' . $system->getProperty('os.name') . ' ' . $system->getProperty('os.version') . ' on ' . $system->getProperty('os.arch') . ' '; // java.util.Date example $formatter = new Java('java.text.SimpleDateFormat', "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz"); echo $formatter->format(new Java('java.util.Date')); ?> The behaviour of these functions is affected by settings in php.ini. Table 1. Java configuration options Name Default Changeable java.class.path NULL PHP_INI_ALL Name Default Changeable java.home NULL PHP_INI_ALL java.library.path NULL PHP_INI_ALL java.library JAVALIB PHP_INI_ALL Q.How To Turn On the Session Support? Ans: The session support can be turned on automatically at the site level, or manually in each PHP page script: Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini. Turning on session support manually in each page script: Call session_start() funtion. Q.Explain the ternary conditional operator in PHP? Ans: Expression preceding the ? is evaluated, if it’s true, then the expression preceding the : is executed, otherwise, the expression following : is executed. Q.What’s the difference between include and require? Ans: It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue. Q.How many ways can we get the value of current session id? Ans: session_id() returns the session id for the current session. Q.How can we destroy the cookie? Ans: Set the cookie in past. Q.How To Read the Entire File into a Single String? Ans: If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents(): This script will print: Size of the file: 7116 Contact for more on PHP Online Training
Continue reading
Python Interview Questions
Q.What is Python? Ans: Python is an interpreted, interactive, object- oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2. Q.Why can't I use an assignment in an expression? Ans: Many people used to C or Perl complain that they want to use this C idiom: while (line = readline(f)) { ...do something with line... } where in Python you're forced to write this: while True: line = f.readline() if not line: break ...do something with line... The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct: if (x = 0) { ...error handling... } else { ...code that only works for nonzero x... } The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended. Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct. An interesting phenomenon is that most experienced Python programmers recognize the "while True" idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language. There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution: line = f.readline() while line: ...do something with line... line = f.readline() The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop. The best approach is to use iterators, making it possible to loop through objects using the for statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply: for line in f: ... do something with line... Q.Is there a tool to help find bugs or perform static analysis? Ans: Yes. PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature. Q.How do you set a global variable in a function? Ans: Did you do something like this? x = 1 # make a global def f(): print x # try to print the global ... for j in range(100): if q>3: x=4 Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the print x attempts to print an uninitialized local variable and will trigger a NameError. The solution is to insert an explicit global declaration at the start of the function: def f(): global x print x # try to print the global ... for j in range(100): if q>3: x=4 In this case, all references to x are interpreted as references to the x from the module namespace. Q.What are the rules for local and global variables in Python? Ans: In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'. Though a bit surprising at first, a moment's consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you'd be using global all the time. You'd have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects. Q.How do I share global variables across modules? Ans: The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: config.py: x = 0 # Default value of the 'x' configuration setting mod.py: import config config.x = 1 main.py: import config import mod print config.x Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason. Q.How can I pass optional or keyword parameters from one function to another? Ans: Collect the arguments using the * and ** specifier in the function's parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **: def f(x, *tup, **kwargs): ... kwargs='14.3c' ... g(x, *tup, **kwargs) In the unlikely case that you care about Python versions older than 2.0, use 'apply': def f(x, *tup, **kwargs): ... kwargs='14.3c' ... apply(g, (x,)+tup, kwargs) Q.How do you make a higher order function in Python? Ans: You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes: def linear(a,b): def result(x): return a*x + b return result Or using a callable object: class linear: def __init__(self, a, b): self.a, self.b = a,b def __call__(self, x): return self.a * x + self.b In both cases: taxes = linear(0.3,2) gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2. The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance: class exponential(linear): # __init__ inherited def __call__(self, x): return self.a * (x ** self.b) Object can encapsulate state for several methods: class counter: value = 0 def set(self, x): self.value = x def up(self): self.value=self.value+1 def down(self): self.value=self.value-1 count = counter() inc, dec, reset = count.up, count.down, count.set Here inc(), dec() and reset() act like functions which share the same counting variable. Q.How do I copy an object in Python? Ans: In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can. Some objects can be copied more easily. Dictionaries have a copy() method: newdict = olddict.copy() Sequences can be copied by slicing: new_l = l Q.How can I find the methods or attributes of an object? Ans: For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. Q.How do I convert a string to a number? Ans: For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0. By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError. int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python's rules: a leading '0' indicates octal, and '0x' indicates a hex number. Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory. eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python regards numbers starting with '0' as octal (base 8). Q.How can my code discover the name of an object? Ans: Generally speaking, it can't, because objects don't really have names. Essentially, assignment always binds a name to a value; The same is true of def and class statements, but in that case the value is a callable. Consider the following code: class A: pass B = A a = B() b = a print b print a Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance's name is a or b, since both names are bound to the same value. Generally speaking it should not be necessary for your code to "know the names" of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question: The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)... ....and don't be surprised if you'll find that it's known by many names, or no name at all! Q.Is there an equivalent of C's "?:" ternary operator? Ans: No. Q.How do I convert a number to a string? Ans: To convert, e.g., the number 144 to the string '144', use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. "%04d" % 144 yields '0144' and "%.3f" % (1/3.0) yields '0.333'. See the library reference manual for details. Q.How do I modify a string in place? Ans: You can't, because strings are immutable. If you need an object with this ability, try converting the string to a list or use the array module: s = "Hello, world" a = list(s) >>>print a a = list("there!") >>>''.join(a) 'Hello, there!' import array a = array.array('c', s) print a array('c', 'Hello, world') a = 'y' ; print a array('c', 'yello world') tostring() 'yello, world' Q.How do I use strings to call functions/methods? Ans: There are various techniques. The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct: def a(): pass def b(): pass dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs dispatch() # Note trailing parens to call function * Use the built-in function getattr(): import foo getattr(foo, 'bar')() Note that getattr() works on any object, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this: class Foo: def do_foo(self): ... def do_bar(self): ... f = getattr(foo_instance, 'do_' + opname) f() * Use locals() or eval() to resolve the function name: def myFunc(): print "hello" fname = "myFunc" f = locals() f() f = eval(fname) f() Note: Using eval() is slow and dangerous. If you don't have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed. Q.Is there an equivalent to Perl's chomp() for removing trailing newlines from strings? Ans: Starting with Python 2.2, you can use S.rstrip("\r\n") to remove all occurences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed: lines = ("line 1 \r\n" ... "\r\n" ... "\r\n") rstrip("\n\r") "line 1 " Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well. For older versions of Python, There are two partial substitutes: If you want to remove all trailing whitespace, use the rstrip() method of string objects. This removes all trailing whitespace, not just a single newline. Otherwise, if there is only one line in the string S, use S.splitlines(). Q.Is there a scanf() or sscanf() equivalent? Ans: Not as such. For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task. Q.Is there a scanf() or sscanf() equivalent? Ans: Not as such. For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional "sep" parameter which is useful if the line uses something other than whitespace as a separator. For more complicated input parsing, regular expressions more powerful than C's sscanf() and better suited for the task. 1.3.9 What does 'UnicodeError: ASCII error: ordinal not in range(128)' mean? This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or work around the problem. If your programs must handle data in arbitrary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For example, a program that handles email or web input will typically find character set encoding information in Content- Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by value is encoded as UTF-8: value = unicode(value, "utf-8") will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError exception. If you only want strings converted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: try: x = unicode(value, "ascii") except UnicodeError: value = unicode(value, "utf-8") else: value was valid ASCII data pass It's possible to set a default encoding in a file called sitecustomize.py that's part of the Python library. However, this isn't recommended because changing the Python-wide default encoding may cause third-party extension modules to fail. Note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. Q.How do I convert between tuples and lists? Ans: The function tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order. For example, tuple() yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren't sure that an object is already a tuple. The function list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields and list('abc') yields . If the argument is a list, it makes a copy just like seq would. Q.What's a negative index? Ans: Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq as the same as seq. Using negative indices can be very convenient. For example S is all of the string except for its last character, which is useful for removing the trailing newline from a string. Q.How do I iterate over a sequence in reverse order? Ans: If it is a list, the fastest solution is list.reverse() try: for x in list: "do something with x" finally: list.reverse() This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don't like this, you can make a copy. This appears expensive but is actually faster than other solutions: rev = list rev.reverse() for x in rev: If it's not a list, a more general but slower solution is: for i in range(len(sequence)-1, -1, -1): x = sequence A more elegant solution, is to define a class which acts as a sequence and yields the elements in reverse order (solution due to Steve Majewski): class Rev: def __init__(self, seq): self.forw = seq def __len__(self): return len(self.forw) def __getitem__(self, i): return self.forw You can now simply write: for x in Rev(list): Unfortunately, this solution is slowest of all, due to the method call overhead. With Python 2.3, you can use an extended slice syntax: for x in sequence: Q.How do you remove duplicates from a list? Ans: If you don't mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go: if List: List.sort() last = List for i in range(len(List)-2, -1, -1): if last==List: del List else: last=List If all elements of the list may be used as dictionary keys (i.e. they are all hash able) this is often faster d = {} for x in List: d=x List = d.values() Q.How do you make an array in Python? Ans: Use a list: Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types. The array module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well. To get Lisp-style linked lists, you can emulate cons cells using tuples: lisp_list = ("like", ("this", ("example", None) ) ) If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is lisp_list and the analogue of cdr is lisp_list. Only do this if you're sure you really need to, because it's usually a lot slower than using Python lists. Q.How do I create a multidimensional list? Ans: You probably tried to make a multidimensional array like this: A = * 2] * 3 This looks correct if you print it: >>> A , , ] But when you assign a value, it shows up in multiple places: A = 5 A , , ] The reason is that replicating a list with * doesn't create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want. The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list: A = *3 for i in range(3): A = * 2 This generates a list containing 3 different lists of length two. You can also use a list comprehension: w,h = 2,3 A = [ *w for i in range(h) ] Or, you can use an extension that provides a matrix datatype; Numeric Python is the best known. Q.How do I apply a method to a sequence of objects? Ans: Use a list comprehension: result = More generically, you can try the following function: def method_map(objects, method, arguments): """method_map(, "meth", (1,2)) gives """ nobjects = len(objects) methods = map(getattr, objects, *nobjects) return map(apply, methods, *nobjects) Q.I want to do a complicated sort: can you do a Schwartzman Transform in Python? Ans: Yes, it's quite simple with list comprehensions. The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its "sort value". To sort a list of strings by their uppercase values: tmp1 = # Schwartzman transform tmp1.sort() Usorted = [ x for x in tmp1 ] To sort by the integer value of a subfield extending from positions 10-15 in each string: tmp2 = ), s) for s in L ] # Schwartzman transform tmp2.sort() Isorted = [ x for x in tmp2 ] Note that Isorted may also be computed by def intfield(s): return int(s) def Icmp(s1, s2): return cmp(intfield(s1), intfield(s2)) Isorted = L Isorted.sort(Icmp) but since this method calls intfield() many times for each element of L, it is slower than the Schwartzman Transform. Q.How can I sort one list by values from another list? Ans: Merge them into a single list of tuples, sort the resulting list, and then pick out the element you want. list1 = list2 = pairs = zip(list1, list2) pairs >>> pairs.sort() result = [ x for x in pairs ] result An alternative for the last step is: result = for p in pairs: result.append(p) If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? First, the append() operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs quite a bit. Second, the expression "result.append" requires an extra attribute lookup, and third, there's a speed reduction from having to make all those function calls. Q.What is a class? Ans: A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype. A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats. Q.What is a method? Ans: A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition: class C: def meth (self, arg): return arg*2 + self.attribute Q.What is self? Ans: Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c). Q.How do I check if an object is an instance of a given class or of a subclass of it? Ans: Use the built-in function isinstance(obj, cls). You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, ...)), and can also check whether an object is one of Python's built-in types, e.g. isinstance(obj, str) or isinstance(obj, (int, long, float, complex)). Note that most programs do not use isinstance() on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object's class and doing a different thing based on what class it is. For example, if you have a function that does something: def search (obj): if isinstance(obj, Mailbox): ... code to search a mailbox elif isinstance(obj, Document): ... code to search a document elif ... A better approach is to define a search() method on all the classes and just call it: class Mailbox: def search(self): # ... code to search a mailbox class Document: def search(self): # ... code to search a document obj.search() Q.What is delegation? Ans: Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behavior of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x. Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase: class UpperOut: def __init__(self, outfile): self.__outfile = outfile def write(self, s): self.__outfile.write(s.upper()) def __getattr__(self, name): return getattr(self.__outfile, name) Here the UpperOut class redefines the write() method to convert the argument string to uppercase before calling the underlying self.__outfile.write() method. All other methods are delegated to the underlying self.__outfile object. The delegation is accomplished via the __getattr__ method; consult the language reference for more information about controlling attribute access. Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a __settattr__ method too, and it must do so carefully. The basic implementation of __setattr__ is roughly equivalent to the following: class X: ... def __setattr__(self, name, value): self.__dict__ = value ... Most __setattr__ implementations must modify self.__dict__ to store local state for self without causing an infinite recursion. Q.How do I call a method defined in a base class from a derived class that overrides it? Ans: If you're using new-style classes, use the built-in super() function: class Derived(Base): def meth (self): super(Derived, self).meth() If you're using classic classes: For a class definition such as class Derived(Base): ... you can call method meth() defined in Base (or one of Base's base classes) as Base.meth(self, arguments...). Here, Base.meth is an unbound method, so you need to provide the self argument. Q.How can I organize my code to make it easier to change the base class? Ans: You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example: BaseAlias = class Derived(BaseAlias): def meth(self): BaseAlias.meth(self) Q.How do I create static class data and static class methods? Ans: Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are not supported directly. For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment: class C: count = 0 # number of times C.__init__ called def __init__(self): C.count = C.count + 1 def getcount(self): return C.count # or return self.count c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C. Caution: within a method of C, an assignment like self.count = 42 creates a new and unrelated instance vrbl named "count" in self's own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not: C.count = 314 Static methods are possible when you're using new-style classes: class C: def static(arg1, arg2, arg3): No 'self' parameter! ... static = staticmethod(static) However, a far more straightforward way to get the effect of a static method is via a simple module-level function: def getcount(): return C.count If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation. Q.How can I overload constructors (or methods) in Python? Ans: This answer actually applies to all methods, but the question usually comes up first in the context of constructors. In C++ you'd write class C { C() { cout >> c.__class__ >>> cls.C Q.Where is the math.py (socket.py, regex.py, etc.) source file? Ans: There are (at least) three kinds of modules in Python: modules written in Python (.py); modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc); modules written in C and linked with the interpreter; to get a list of these, type: import sys print sys.builtin_module_names Q.How do I make a Python script executable on Unix? Ans: You need to do two things: the script file's mode must be executable and the first line must begin with #! followed by the path of the Python interpreter. The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile. The second can be done in a number of ways. The most straightforward way is to write #!/usr/local/bin/python as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform. If you would like the script to be independent of where the Python interpreter lives, you can use the "env" program. Almost all Unix variants support the following, assuming the python interpreter is in a directory on the user's $PATH: #! /usr/bin/env python Don't do this for CGI scripts. The $PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter. Occasionally, a user's environment is so full that the /usr/bin/env program fails; or there's no env program at all. In that case, you can try the following hack (due to Alex Rezinsky): #! /bin/sh """:" exec python $0 ${1+"$@"} """ The minor disadvantage is that this defines the script's __doc__ string. However, you can fix that by adding __doc__ = """...Whatever...""" Q.Why don't my signal handlers work? Ans: The most common problem is that the signal handler is declared with the wrong argument list. It is called as handler(signum, frame) so it should be declared with two arguments: def handler(signum, frame): ... Q.How do I test a Python program or component? Ans: Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring. The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks. For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods -- and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do. The "global main logic" of your program may be as simple as if __name__=="__main__": main_logic() at the bottom of the main module of your program. Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite can be associated with each module which automates a sequence of tests. This sounds like a lot of work, but since Python is so terse and flexible it's surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier. "Support modules" that are not intended to be the main module of a program may include a self-test of the module. if __name__ == "__main__": self_test() Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python. None of my threads seem to run: why? As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work. A simple fix is to add a sleep to the end of the program that's long enough for all the threads to finish: import threading, time def thread_task(name, n): for i in range(n): print name, i for i in range(10): = threading.Thread(target=thread_task, args=(str(i), i)) T.start() time.sleep(10) # ' in the format string forces big-endian data; the letter 'h' reads one "short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the string. Q.How do I run a subprocess with pipes connected to both input and output? Ans: Use the popen2 module. For example: import popen2 fromchild, tochild = popen2.popen2("command") tochild.write("input\n") tochild.flush() output = fromchild.readline() Q.How can I mimic CGI form submission (METHOD=POST)? Ans: I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily? Yes. Here's a simple example that uses httplib: #!/usr/local/bin/python import httplib, sys, time ### build the query string qs = "First=Josephine&MI=Q&Last=Public" ### connect and send the server a path httpobj = httplib.HTTP('www.some-server.out-there', 80) httpobj.putrequest('POST', '/cgi-bin/some-cgi-script') now generate the rest of the HTTP headers... httpobj.putheader('Accept', '*/*') httpobj.putheader('Connection', 'Keep-Alive') httpobj.putheader('Content-type', 'application/x-www-form-urlencoded') httpobj.putheader('Content-length', '%d' % len(qs)) httpobj.endheaders() httpobj.send(qs) find out what the server said in response... reply, msg, hdrs = httpobj.getreply() if reply != 200: sys.stdout.write(httpobj.getfile().read()) Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote(). For example to send name="Guy Steele, Jr.": from urllib import quote x = quote("Guy Steele, Jr.") x 'Guy%20Steele,%20Jr.' query_string = "name="+x query_string 'name=Guy%20Steele,%20Jr.' Q.How do I send mail from a Python script? Ans: Use the standard library module smtplib. Here's a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener. import sys, smtplib fromaddr = raw_input("From: ") toaddrs = raw_input("To: ").split(',') print "Enter message, end with ^D:" msg = '' while 1: line = sys.stdin.readline() if not line: break msg = msg + line # The actual mail send server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg) server.quit() A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual page will help you out. Here's some sample code: SENDMAIL = "/usr/sbin/sendmail" # sendmail location import os p = os.popen("%s -t -i" % SENDMAIL, "w") p.write("To: receiver@example.com\n") p.write("Subject: test\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write("some more text\n") sts = p.close() if sts != 0: print "Sendmail exit status", sts Q.How do I avoid blocking in the connect() method of a socket? Ans: The select module is commonly used to help with asynchronous I/O on sockets. Q.Are there any interfaces to database packages in Python? Ans: Yes. Python 2.3 includes the bsddb package which provides an interface to the BerkeleyDB library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python. Q.How do I generate random numbers in Python? Ans: The standard module random implements a random number generator. Usage is simple: import random random.random() This returns a random floating point number in the range [0, 1). Q.Can I create my own functions in C? Ans: Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C. Q.Can I create my own functions in C++? Ans: Yes, using the C compatibility features found in C++. Place extern "C" { ... } around the Python include files and put extern "C" before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea. Q.How can I execute arbitrary Python statements from C? Ans: The highest-level function to do this is PyRun_SimpleString() which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including SyntaxError). If you want more control, use PyRun_String(); see the source for PyRun_SimpleString() in Python/pythonrun.c. Q.How can I evaluate an arbitrary Python expression from C? Ans: Call the function PyRun_String() from the previous question with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value. Q.How do I extract C values from a Python object? Ans: That depends on the object's type. If it's a tuple, PyTupleSize(o) returns its length and PyTuple_GetItem(o, i) returns its i'th item. Lists have similar functions, PyListSize(o) and PyList_GetItem(o, i). For strings, PyString_Size(o) returns its length and PyString_AsString(o) a pointer to its value. Note that Python strings may contain null bytes so C's strlen() should not be used. To test the type of an object, first make sure it isn't NULL, and then use PyString_Check(o), PyTuple_Check(o), PyList_Check(o), etc. There is also a high-level API to Python objects which is provided by the so-called 'abstract' interface -- read Include/abstract.h for further details. It allows interfacing with any kind of Python sequence using calls like PySequence_Length(), PySequence_GetItem(), etc.) as well as many other useful protocols. Q.How do I call an object's method from C? Ans: The PyObject_CallMethod() function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with Py_BuildValue(), and the argument values: PyObject * PyObject_CallMethod(PyObject *object, char *method_name, char *arg_format, ...); This works for any object that has methods -- whether built-in or user-defined. You are responsible for eventually Py_DECREF'ing the return value. To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the file object pointer is "f"): res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0); if (res == NULL) { ... an exception occurred ... } else { Py_DECREF(res); } Note that since PyObject_CallObject() always wants a tuple for the argument list, to call a function without arguments, pass "()" for the format, and to call a function with one argument, surround the argument in parentheses, e.g. "(i)". Q.How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)? Ans: In Python code, define an object that supports the write() method. Assign this object to sys.stdout and sys.stderr. Call print_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your write() method sends it. The easiest way to do this is to use the StringIO class in the standard library. Sample code and use for catching stdout: class StdoutCatcher: ... def __init__(self): ... self.data = '' ... def write(self, stuff): ... self.data = self.data + stuff ... import sys stdout = StdoutCatcher() print 'foo' print 'hello world!' stderr.write(sys.stdout.data) foo hello world! Q.How do I access a module written in Python from C? Ans: You can get a pointer to the module object as follows: module = PyImport_ImportModule(""); If the module hasn't been imported yet (i.e. it is not yet present in sys.modules), this initializes the module; otherwise it simply returns the value of sys.modules. Note that it doesn't enter the module into any namespace -- it only ensures it has been initialized and is stored in sys.modules. You can then access the module's attributes (i.e. any name defined in the module) as follows: attr = PyObject_GetAttrString(module, ""); Calling PyObject_SetAttrString() to assign to variables in the module also works. Q.How do I interface to C++ objects from Python? Ans: Depending on your requirements, there are many approaches. To do this manually, begin by reading the "Extending and Embedding" document. Realize that for the Python run-time system, there isn't a whole lot of difference between C and C++ -- so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects. Q.How do I tell "incomplete input" from "invalid input"? Ans: Sometimes you want to emulate the Python interactive interpreter's behavior, where it gives you a continuation prompt when the input is incomplete (e.g. you typed the start of an "if" statement or you didn't close your parentheses or triple string quotes), but it gives you a syntax error message immediately when the input is invalid. In Python you can use the codeop module, which approximates the parser's behavior sufficiently. IDLE uses this, for example. The easiest way to do it in C is to call PyRun_InteractiveLoop() (perhaps in a separate thread) and let the Python interpreter handle the input for you. You can also set the PyOS_ReadlineFunctionPointer to point at your custom input function. See Modules/readline.c and Parser/myreadline.c for more hints. However sometimes you have to run the embedded Python interpreter in the same thread as your rest application and you can't allow the PyRun_InteractiveLoop() to stop while waiting for user input. The one solution then is to call PyParser_ParseString() and test for e.error equal to E_EOF, which means the input is incomplete). Here's a sample code fragment, untested, inspired by code from Alex Farber: #include #include #include #include #include #include int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, &_PyParser_Grammar, Py_file_input, &e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } Another solution is trying to compile the received string with Py_CompileString(). If it compiles without errors, try to execute the returned code object by calling PyEval_EvalCode(). Otherwise save the input for later. If the compilation fails, find out if it's an error or just more input is required - by extracting the message string from the exception tuple and comparing it to the string "unexpected EOF while parsing". Here is a complete example using the GNU readline library (you may want to ignore SIGINT while calling readline()): #include #include #include #include #include #include int main (int argc, char* argv) { int i, j, done = 0; /* lengths of line, code */ char ps1 = ">>> "; char ps2 = "... "; char *prompt = ps1; char *msg, *line, *code = NULL; PyObject *src, *glb, *loc; PyObject *exc, *val, *trb, *obj, *dum; Py_Initialize (); loc = PyDict_New (); glb = PyDict_New (); PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ()); while (!done) { line = readline (prompt); if (NULL == line) /* CTRL-D pressed */ { done = 1; } else { i = strlen (line); if (i > 0) add_history (line); /* save non-empty lines */ if (NULL == code) /* nothing in code yet */ j = 0; else j = strlen (code); code = realloc (code, i + j + 2); if (NULL == code) /* out of memory */ exit (1); if (0 == j) /* code was empty, so */ code = '\0'; /* keep strncat happy */ strncat (code, line, i); /* append line to code */ code = '\n'; /* append '\n' to code */ code = '\0'; src = Py_CompileString (code, " ", Py_single_input); if (NULL != src) /* compiled just fine - */ { if (ps1 == prompt || /* ">>> " or */ '\n' == code) /* "... " and double '\n' */ { /* so execute it */ dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc); Py_XDECREF (dum); Py_XDECREF (src); free (code); code = NULL; if (PyErr_Occurred ()) PyErr_Print (); prompt = ps1; } } /* syntax error or E_EOF? */ else if (PyErr_ExceptionMatches (PyExc_SyntaxError)) { PyErr_Fetch (&exc, &val, &trb); /* clears exception! */ if (PyArg_ParseTuple (val, "sO", &msg, &obj) && !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */ { Py_XDECREF (exc); Py_XDECREF (val); Py_XDECREF (trb); prompt = ps2; } else /* some other syntax error */ { PyErr_Restore (exc, val, trb); PyErr_Print (); free (code); code = NULL; prompt = ps1; } } else /* some non-syntax error */ { PyErr_Print (); free (code); code = NULL; prompt = ps1; } free (line); } } Py_XDECREF(glb); Py_XDECREF(loc); Py_Finalize(); exit(0); } Q.How do I run a Python program under Windows? Ans: This is not necessarily a straightforward question. If you are already familiar with running programs from the Windows command line then everything will seem obvious; otherwise, you might need a little more guidance. There are also differences between Windows 95, 98, NT, ME, 2000 and XP which can add to the confusion. Unless you use some sort of integrated development environment, you will end up typing Windows commands into what is variously referred to as a "DOS window" or "Command prompt window". Usually you can create such a window from your Start menu; under Windows 2000 the menu selection is "Start | Programs | Accessories | Command Prompt". You should be able to recognize when you have started such a window because you will see a Windows "command prompt", which usually looks like this: C:\> The letter may be different, and there might be other things after it, so you might just as easily see something like: D:\Steve\Projects\Python> depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs. You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python? First, you need to make sure that your command window recognises the word "python" as an instruction to start the interpreter. If you have opened a command window, you should try entering the command python and hitting return. You should then see something like: Python 2.2 (#28, Dec 21 2001, 12:21:22) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> You have started the interpreter in "interactive mode". That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python's strongest features. Check it by entering a few expressions of your choice and seeing the results: print "Hello" Hello "Hello" * 3 HelloHelloHello Many people use the interactive mode as a convenient yet highly programmable calculator. When you want to end your interactive Python session, hold the Ctrl key down while you enter a Z, then hit the "Enter" key to get back to your Windows command prompt. You may also find that you have a Start-menu entry such as "Start | Programs | Python 2.2 | Python (command line)" that results in you seeing the >>> prompt in a new window. If so, the window will disappear after you enter the Ctrl-Z character; Windows is running a single "python" command in the window, and closes it when you terminate the interpreter. If the python command, instead of displaying the interpreter prompt >>>, gives you a message like: 'python' is not recognized as an internal or external command, operable program or batch file. or: Bad command or filename then you need to make sure that your computer knows where to find the Python interpreter. To do this you will have to modify a setting called PATH, which is a list of directories where Windows will look for programs. You should arrange for Python's installation directory to be added to the PATH of every command window as it starts. If you installed Python fairly recently then the command dir C:\py* will probably tell you where it is installed; the usual location is something like C:\Python23. Otherwise you will be reduced to a search of your whole disk ... use "Tools | Find" or hit the "Search" button and look for "python.exe". Supposing you discover that Python is installed in the C:\Python23 directory (the default at the time of writing), you should make sure that entering the command c:\Python23\python starts up the interpreter as above (and don't forget you'll need a "CTRL-Z" and an "Enter" to get out of it). Once you have verified the directory, you need to add it to the start-up routines your computer goes through. For older versions of Windows the easiest way to do this is to edit the C:\AUTOEXEC.BAT file. You would want to add a line like the following to AUTOEXEC.BAT: PATH C:\Python23;%PATH% For Windows NT, 2000 and (I assume) XP, you will need to add a string such as ;C:\Python23 to the current setting for the PATH environment variable, which you will find in the properties window of "My Computer" under the "Advanced" tab. Note that if you have sufficient privilege you might get a choice of installing the settings either for the Current User or for System. The latter is preferred if you want everybody to be able to run Python on the machine. If you aren't confident doing any of these manipulations yourself, ask for help! At this stage you may want to reboot your system to make absolutely sure the new setting has taken effect. You probably won't need to reboot for Windows NT, XP or 2000. You can also avoid it in earlier versions by editing the file C:\WINDOWS\COMMAND\CMDINIT.BAT instead of AUTOEXEC.BAT. You should now be able to start a new command window, enter python at the C:> (or whatever) prompt, and see the >>> prompt that indicates the Python interpreter is reading interactive commands. Let's suppose you have a program called pytest.py in directory C:\Steve\Projects\Python. A session to run that program might look like this: C:\> cd \Steve\Projects\Python C:\Steve\Projects\Python> python pytest.py Because you added a file name to the command to start the interpreter, when it starts up it reads the Python script in the named file, compiles it, executes it, and terminates, so you see another C:\> prompt. You might also have entered C:\> python \Steve\Projects\Python\pytest.py if you hadn't wanted to change your current directory. Under NT, 2000 and XP you may well find that the installation process has also arranged that the command pytest.py (or, if the file isn't in the current directory, C:\Steve\Projects\Python\pytest.py) will automatically recognize the ".py" extension and run the Python interpreter on the named file. Using this feature is fine, but some versions of Windows have bugs which mean that this form isn't exactly equivalent to using the interpreter explicitly, so be careful. The important things to remember are: Start Python from the Start Menu, or make sure the PATH is set correctly so Windows can find the Python interpreter. python should give you a '>>>" prompt from the Python interpreter. Don't forget the CTRL-Z and ENTER to terminate the interpreter (and, if you started the window from the Start Menu, make the window disappear). Once this works, you run programs with commands: python {program-file} When you know the commands to use you can build Windows shortcuts to run the Python interpreter on any of your scripts, naming particular working directories, and adding them to your menus. Take a look at python --help if your needs are complex. Interactive mode (where you see the >>> prompt) is best used for checking that individual statements and expressions do what you think they will, and for developing code by experiment. Q.How do I make python scripts executable? Ans: On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as 'foo.py'. If you'd rather be able to execute the script by simple typing 'foo' with no extension you need to add .py to the PATHEXT environment variable. On Windows NT, the steps taken by the installer as described above allow you to run a script with 'foo.py', but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important. The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line: @setlocal enableextensions & python -x %~f0 %* & goto :EOF Q.How do I debug an extension? When using GDB with dynamically loaded extensions, you can't set a breakpoint in your extension until your extension is loaded. In your .gdbinit file (or interactively), add the command: br _PyImport_LoadDynamicModule Then, when you run GDB: gdb /local/bin/python gdb) run myscript.py gdb) continue # repeat until your extension is loaded gdb) finish # so that your extension is loaded gdb) br myfunction.c:50 gdb) continue Q.Where is Freeze for Windows? Ans: "Freeze" is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don't run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU. Q.Is a *.pyd file the same as a DLL? Ans: Yes, . Q.How can I embed Python into a Windows application? Ans: Embedding the Python interpreter in a Windows app can be summarized as follows: Do _not_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL's. (This is the first key undocumented fact.) Instead, link to pythonNN.dll; it is typically installed in C:\Windows\System. NN is the Python version, a number such as "23" for Python 2.3. You can link to Python statically or dynamically. Linking statically means linking against pythonNN.lib, while dynamically linking means linking against pythonNN.dll. The drawback to dynamic linking is that your app won't run if pythonNN.dll does not exist on your system. (General note: pythonNN.lib is the so-called "import lib" corresponding to python.dll. It merely defines symbols for the linker.) Linking dynamically greatly simplifies link options; everything happens at run time. Your code must load pythonNN.dll using the Windows LoadLibraryEx() routine. The code must also use access routines and data in pythonNN.dll (that is, Python's C API's) using pointers obtained by the Windows GetProcAddress() routine. Macros can make using these pointers transparent to any C code that calls routines in Python's C API. Borland note: convert pythonNN.lib to OMF format using Coff2Omf.exe first. If you use SWIG, it is easy to create a Python "extension module" that will make the app's data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link into your .exe file (!) You do _not_ have to create a DLL file, and this also simplifies linking. SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class. The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.) In short, you can use the following code to initialize the Python interpreter with your extension module. #include "python.h" ... Py_Initialize(); // Initialize Python. initmyAppc(); // Initialize (import) the helper class. PyRun_SimpleString("import myApp") ; // Import the shadow class. There are two problems with Python's C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll. Problem 1: The so-called "Very High Level" functions that take FILE * arguments will not work in a multi-compiler environment because each compiler's notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions. Problem 2: SWIG generates the following code when generating wrappers to void functions: Py_INCREF(Py_None); _resultobj = Py_None; return _resultobj; Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by: return Py_BuildValue(""); It may be possible to use SWIG's %typemap command to make the change automatically, though I have not been able to get this to work (I'm a complete SWIG newbie). Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app's windowing system. Rather, you (or the wxPythonWindow class) should create a "native" interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python's i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods. Q.How do I use Python for CGI? Ans: On the Microsoft IIS server or on the Win95 MS Personal Web Server you set up Python in the same way that you would set up any other scripting engine. Run regedt32 and go to: KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W3SVC\Parameters\ScriptMap and enter the following line (making any specific changes that your system may need): .py :REG_SZ: c:\\python.exe -u %s %s This line will allow you to call your script with a simple reference like: http://yourserver/scripts/yourscript.py provided "scripts" is an "executable" directory for your server (which it usually is by default). The "-u" flag specifies unbuffered and binary mode for stdin - needed when working with binary data. In addition, it is recommended that using ".py" may not be a good idea for the file extensions when used in this context (you might want to reserve *.py for support modules and use *.cgi or *.cgp for "main program" scripts). In order to set up Internet Information Services 5 to use Python for CGI processing, please see the following links: http://www.e-coli.net/pyiis_server.html (for Win2k Server) http://www.e-coli.net/pyiis.html (for Win2k pro) Configuring Apache is much simpler. In the Apache configuration file httpd.conf, add the following line at the end of the file: ScriptInterpreterSource Registry Then, give your Python CGI-scripts the extension .py and put them in the cgi-bin directory. Q.How do I emulate os.kill() in Windows? Ans: Use win32api: def kill(pid): """kill function for Win32""" import win32api handle = win32api.OpenProcess(1, 0, pid) return (0 != win32api.TerminateProcess(handle, 0)) Q.Why does os.path.isdir() fail on NT shared directories? Ans: The solution appears to be always append the "\" on the end of shared drives. >>> import os >>>os.path.isdir( '\\\\rorschach\\public') 0 >>>os.path.isdir( '\\\\rorschach\\public\\') 1 It helps to think of share points as being like drive letters. Example: is not a directory k:\ is a directory k:\media is a directory k:\media\ is not a directory The same rules apply if you substitute "k:" with "\conkyfoo": \\conky\foo is not a directory \\conky\foo\ is a directory \\conky\foo\media is a directory \\conky\foo\media\ is not a directory Web Python Some host providers only let you run CGI scripts in a certain directory, often named cgi-bin. In this case all you have to do to run the script is to call it like this: http://my_server.tld/cgi-bin/my_script.py The script will have to be made executable by "others". Give it a 755 permission or check the executable boxes if there is a graphical FTP interface. Some hosts let you run CGI scripts in any directory. In some of these hosts you don't have to do anything do configure the directories. In others you will have to add these lines to a file named .htaccess in the directory you want to run CGI scripts from: Options +ExecCGI AddHandler cgi-script .py If the file does not exist create it. All directories below a directory with a .htaccess file will inherit the configurations. So if you want to be able to run CGI scripts from all directories create this file in the document root. To run a script saved at the root: http://my_server.tld/my_script.py If it was saved in some directory: http://my_server.tld/some_dir/some_subdir/my_script.py Make sure all text files you upload to the server are uploaded as text (not binary), specially if you are in Windows, otherwise you will have problems. Q.How to Debugging in python? Ans: Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server. For a nice exceptions report there is the cgitb module. It will show a traceback inside a context. The default output is sent to standard output as HTML: #!/usr/bin/env python print "Content-Type: text/html" print import cgitb; cgitb.enable() print 1/0 The handler() method can be used to handle only the catched exceptions: #!/usr/bin/env python print "Content-Type: text/html" print import cgitb try: f = open('non-existent-file.txt', 'r') except: cgitb.handler() There is also the option for a crude approach making the header "text/plain" and setting the standard error to standard out: #!/usr/bin/env python print "Content-Type: text/plain" print import sys sys.stderr = sys.stdout = open('non-existent-file.txt', 'r') Will output this: Traceback (most recent call last): File "/var/www/html/teste/cgi-bin/text_error.py", line 6, in ? f = open('non-existent-file.txt', 'r') IOError: No such file or directory: 'non-existent-file.txt' Warning: These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable it. Q.How to make Forms in python? Ans: The FieldStorage class of the cgi module has all that is needed to handle submited forms. import cgi form = cgi.FieldStorage() # instantiate only once! It is transparent to the programmer if the data was submited by GET or by POST. The interface is exactly the same. * Unique field names : Suppose we have this HTML form which submits a field named name to a python CGI script named process_form.py: Name: This is the process_form.py script: #!/usr/bin/env python import cgi form = cgi.FieldStorage() # instantiate only once! name = form.getfirst('name', 'empty') Avoid script injection escaping the user input name = cgi.escape(name) print """\ Content-Type: text/html\n The submited name was "%s" """ % name The getfirst() method returns the first value of the named field or a default or None if no field with that name was submited or if it is empty. If there is more than one field with the same name only the first will be returned. If you change the HTML form method from get to post the process_form.py script will be the same. * Multiple field names: If there is more than one field with the same name like in HTML input check boxes then the method to be used is getlist(). It will return a list containing as many items (the values) as checked boxes. If no check box was checked the list will be empty. Sample HTML with check boxes: Red Green And the corresponding process_check.py script: #!/usr/bin/env python import cgi form = cgi.FieldStorage() getlist() returns a list containing the values of the fields with the given name colors = form.getlist('color') print "Content-Type: text/html\n" print '' print 'The colors list:', colors for color in colors: print ' ', cgi.escape(color), ' ' print '' * File Upload; To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a "Browse" button. File: The getfirst() and getlist() methods will only return the file(s) content. To also get the filename it is necessary to access a nested FieldStorage instance by its index in the top FieldStorage instance. #!/usr/bin/env python import cgi form = cgi.FieldStorage() A nested FieldStorage instance holds the file fileitem = form Test if the file was uploaded if fileitem.filename: open('files/' + fileitem.filename, 'w').write(fileitem.file.read()) message = 'The file "' + fileitem.filename + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html\n %s """ % (message,) The Apache user must have write permission on the directory where the file will be saved. * Big File Upload To handle big files without using all the available memory a generator can be used. The generator will return the file in small chunks: #!/usr/bin/env python import cgi form = cgi.FieldStorage() Generator to buffer file chunks def fbuffer(f, chunk_size=10000): while True: chunk = f.read(chunk_size) if not chunk: break yield chunk A nested FieldStorage instance holds the file fileitem = form Test if the file was uploaded if fileitem.filename: f = open('files/' + fileitem.filename, 'w') # Read the file in chunks for chunk in fbuffer(fileitem.file): f.write(chunk) f.close() message = 'The file "' + fileitem.filename + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html\n %s """ % (message,) Q.How to use Cookies for Web python ? Ans: HTTP is said to be a stateless protocol. What this means for web programmers is that every time a user loads a page it is the first time for the server. The server can't say whether this user has ever visited that site, if is he in the middle of a buying transaction, if he has already authenticated, etc. A cookie is a tag that can be placed on the user's computer. Whenever the user loads a page from a site the site's script can send him a cookie. The cookie can contain anything the site needs to identify that user. Then within the next request the user does for a new page there goes back the cookie with all the pertinent information to be read by the script. * Set the Cookie; There are two basic cookie operations. The first is to set the cookie as an HTTP header to be sent to the client. The second is to read the cookie returned from the client also as an HTTP header. This script will do the first one placing a cookie on the client's browser: #!/usr/bin/env python import time This is the message that contains the cookie and will be sent in the HTTP header to the client print 'Set-Cookie: lastvisit=' + str(time.time()); To save one line of code we replaced the print command with a '\n' print 'Content-Type: text/html\n' # End of HTTP header print '' print 'Server time is', time.asctime(time.localtime()) print '' The Set-Cookie header contains the cookie. Save and run this code from your browser and take a look at the cookie saved there. Search for the cookie name, lastvisit, or for the domain name, or the server IP like 10.1.1.1 or 127.0.0.1. The Cookie Object The Cookie module can save us a lot of coding and errors and the next pages will use it in all cookie operations. #!/usr/bin/env python import time, Cookie Instantiate a SimpleCookie object cookie = Cookie.SimpleCookie() The SimpleCookie instance is a mapping cookie = str(time.time()) Output the HTTP message containing the cookie print cookie print 'Content-Type: text/html\n' print '' print 'Server time is', time.asctime(time.localtime()) print '' It does not seem as much for this extremely simple code, but wait until it gets complex and the Cookie module will be your friend. * Retrieve the Cookie; The returned cookie will be available as a string in the os.environ dictionary with the key 'HTTP_COOKIE': cookie_string = os.environ.get('HTTP_COOKIE') The load() method of the SimpleCookie object will parse that string rebuilding the object's mapping: cookie.load(cookie_string) Complete code: #!/usr/bin/env python import Cookie, os, time cookie = Cookie.SimpleCookie() cookie = str(time.time()) print cookie print 'Content-Type: text/html\n' print '' print ' Server time is', time.asctime(time.localtime()), ' ' The returned cookie is available in the os.environ dictionary cookie_string = os.environ.get('HTTP_COOKIE') The first time the page is run there will be no cookies if not cookie_string: print ' First visit or cookies disabled ' else: # Run the page twice to retrieve the cookie print ' The returned cookie string was "' + cookie_string + '" ' load() parses the cookie string cookie.load(cookie_string) Use the value attribute of the cookie to get it lastvisit = float(cookie.value) print ' Your last visit was at', print time.asctime(time.localtime(lastvisit)), ' ' print '' When the client first loads the page there will be no cookie in the client's computer to be returned. The second time the page is requested then the cookie saved in the last run will be sent to the server. * Morsels In the previous cookie retrieve program the lastvisit cookie value was retrieved through its value attribute: lastvisit = float(cookie.value) When a new key is set for a SimpleCookie object a Morsel instance is created: import Cookie import time cookie = Cookie.SimpleCookie() cookie >>> cookie = str(time.time()) cookie >>> cookie.value '1159535133.33' Each cookie, a Morsel instance, can only have a predefined set of keys: expires, path, commnent, domain, max-age, secure and version. Any other key will raise an exception. #!/usr/bin/env python import Cookie, time cookie = Cookie.SimpleCookie() name/value pair cookie = str(time.time()) expires in x seconds after the cookie is output. the default is to expire when the browser is closed cookie = 30 * 24 * 60 * 60 path in which the cookie is valid. if set to '/' it will valid in the whole domain. the default is the script's path. cookie = '/cgi-bin' the purpose of the cookie to be inspected by the user cookie = 'holds the last user\'s visit date' domain in which the cookie is valid. always stars with a dot. to make it available in all subdomains specify only the domain like .my_site.com cookie = '.www.my_site.com' discard in x seconds after the cookie is output not supported in most browsers cookie = 30 * 24 * 60 * 60 secure has no value. If set directs the user agent to use only (unspecified) secure means to contact the origin server whenever it sends back this cookie cookie = '' a decimal integer, identifies to which version of the state management specification the cookie conforms. cookie = 1 print 'Content-Type: text/html\n' print ' ', cookie, ' ' for morsel in cookie: print ' ', morsel, '=', cookie.value print ' ' for key in cookie: print key, '=', cookie, ' ' print ' Notice that print cookie automatically formats the expire date. How to use Sessions for Web python ? Sessions are the server side version of cookies. While a cookie persists data (or state) at the client, sessions do it at the server. Sessions have the advantage that the data do not travel the network thus making it both safer and faster although this not entirely true as shown in the next paragraph The session state is kept in a file or in a database at the server side. Each session is identified by an id or session id (SID). To make it possible to the client to identify himself to the server the SID must be created by the server and sent to the client and then sent back to the server whenever the client makes a request. There is still data going through the net, the SID. The server can send the SID to the client in a link's query string or in a hidden form field or as a Set-Cookie header. The SID can be sent back from the client to the server as a query string parameter or in the body of the HTTP message if the post method is used or in a Cookie HTTP header. If a cookie is not used to store the SID then the session will only last until the browser is closed, or the user goes to another site breaking the POST or query string transmission, or in other words, the session will last only until the user leaves the site. * Cookie Based SID: A cookie based session has the advantage that it lasts until the cookie expires and, as only the SID travels the net, it is faster and safer. The disadvantage is that the client must have cookies enabled. The only particularity with the cookie used to set a session is its value: The sid will be a hash of the server time sid = sha.new(repr(time.time())).hexdigest() The hash of the server time makes an unique SID for each session. #!/usr/bin/env python import sha, time, Cookie, os cookie = Cookie.SimpleCookie() string_cookie = os.environ.get('HTTP_COOKIE') # If new session if not string_cookie: The sid will be a hash of the server time sid = sha.new(repr(time.time())).hexdigest() Set the sid in the cookie cookie = sid # Will expire in a year cookie = 12 * 30 * 24 * 60 * 60 If already existent session else: cookie.load(string_cookie) sid = cookie.value print cookie print 'Content-Type: text/html\n' print '' if string_cookie: print ' Already existent session ' else: print ' New session ' print ' SID =', sid, ' ' print '' In every page the existence of the cookie must be tested. If it does not exist then redirect to a login page or just create it if a login or a previous state is not required. Query String SID; Query string based session: #!/usr/bin/env python import sha, time, cgi, os sid = cgi.FieldStorage().getfirst('sid') if sid: # If session exists message = 'Already existent session' else: # New session The sid will be a hash of the server time sid = sha.new(repr(time.time())).hexdigest() message = 'New session' qs = 'sid=' + sid print """\ Content-Type: text/html\n %s SID = %s reload """ % (message, sid, sid) To mantain a session you will have to append the query string to all the links in the page. Save this file as set_sid_qs.py and run it two or more times. Try to close the browser and call the page again. The session is gone. The same happens if the page address is typed in the address bar. * Hidden Field SID; The hidden form field SID is almost the same as the query string based one, sharing the same problems. #!/usr/bin/env python import sha, time, cgi, os sid = cgi.FieldStorage().getfirst('sid') if sid: # If session exists message = 'Already existent session' else: # New session The sid will be a hash of the server time sid = sha.new(repr(time.time())).hexdigest() message = 'New session' qs = 'sid=' + sid print """\ Content-Type: text/html\n %s SID = %s """ % (message, sid, sid) * The shelve module; Having a SID is not enough. It is necessary to save the session state in a file or in a database. To save it into a file the shelve module is used. The shelve module opens a file and returns a dictionary like object which is readable and writable as a dictionary. The shelve module will persist the session data and expose it as a dictionary session = shelve.open('/tmp/.session/sess_' + sid, writeback=True) The SID is part of file name making it a unique file. The apache user must have read and write permission on the file's directory. 660 would be ok. The values of the dictionary can be any Python object. The keys must be immutable objects. Save the current time in the session session = repr(time.time()) Retrieve last visit time from the session lastvisit = session.get('lastvisit') The dictionary like object must be closed as any other file should be: session.close() * Cookie and Shelve; A sample of how to make cookies and shelve work together keeping session state at the server side: #!/usr/bin/env python import sha, time, Cookie, os, shelve cookie = Cookie.SimpleCookie() string_cookie = os.environ.get('HTTP_COOKIE') if not string_cookie: sid = sha.new(repr(time.time())).hexdigest() cookie = sid message = 'New session' else: cookie.load(string_cookie) sid = cookie.value cookie = 12 * 30 * 24 * 60 * 60 The shelve module will persist the session data and expose it as a dictionary session = shelve.open('/tmp/.session/sess_' + sid, writeback=True) Retrieve last visit time from the session lastvisit = session.get('lastvisit') if lastvisit: message = 'Welcome back. Your last visit was at ' + \ time.asctime(time.gmtime(float(lastvisit))) Save the current time in the session session = repr(time.time()) print """\ %s Content-Type: text/html\n %s SID = %s % (cookie, message, sid) session.close() It first checks if there is a cookie already set. If not it creates a SID and attributes it to the cookie value. An expiration time of one year is established. The lastvisit data is what is maintained in the session. Python interview questions Tags python interview questions and answers, python online training, python interview questions, python online training, python training, python training institute, latest python interview questions, best python interview questions 2019, top 100 python interview questions,sample python interview questions, python interview questions technical, best python interview tips, best python interview basics For online training videos
Continue reading
R Programming Interview Questions
Q.Explain The Data Import In R Language.? Ans: R provides to import data in R language. To begin with the R commander GUI, user should type the commands in the command Rcmdr into the console. Data can be imported in R language in 3 ways such as: Select the data set in the dialog box or enter the name of the data set as required. Data is entered directly using the editor of R Commander via Data->New Data Set. This works good only when the data set is not too large. Data can also be imported from a URL or from plain text file (ASCII), or from any statistical package or from the clipboard. Q.Explain How To Communicate The Outputs Of Data Analysis Using R Language.? Ans: Combine the data, code and analysis results in a single document using knitr for Reproducible research done. Helps to verify the findings, add to them and engage in conversations. Reproducible research makes it easy to redo the experiments by inserting new data values and applying it to different various problems. Q.What Is R? Ans: R is a programming language which is used for developing statistical software and data analysis. Q.How R Commands Are Written? Ans: By using # at the starting of the line of code like #division commands are written. Q.What Is T-tests() In R? Ans: It is used to determine that the means of two groups are equal or not by using t.test() function. Q.What Are The Disadvantages Of R Programming? Ans: The disadvantages are:- Lack of standard GUI Not good for big data. Does not provide spreadsheet view of data. Q.What Is The Use Of With () And By () Function In R? Ans: with() function applies an expression to a dataset. #with(data,expression) By() function applies a function t each level of a factors. #by(data,factorlist,function) Q.In R Programming, How Missing Values Are Represented? Ans: In R missing values are represented by NA which should be in capital letters. Q.What Is The Use Of Subset() And Sample() Function In R? Ans: Subset() is used to select the variables and observations and sample() function is used to generate a random sample of the size n from a dataset. Q.Explain What Is Transpose.? Ans: Transpose is used for reshaping of the data which is used for analysis. Transpose is performed by t() function. Q.What Are The Advantages Of R? Ans: The advantages are:- It is used for managing and manipulating of data. No license restrictions Free and open source software. Graphical capabilities of R are good. Runs on many Operating system and different hardware and also run on 32 & 64 bit processors etc. Q.What Is The Function Used For Adding Datasets In R? Ans: For adding two datasets rbind() function is used but the column of two datasets must be same. Syntax: rbind(x1,x2……) where x1,x2: vector, matrix, data frames. Q.How You Can Produce Co-relations And Covariances? Ans: Cor-relations is produced by cor() and covariances is produced by cov() function. Q.What Is Difference Between Matrix And Dataframes? Ans: Dataframe can contain different type of data but matrix can contain only similar type of data. Q.What Is Difference Between Lapply And Sapply? Ans: lapply is used to show the output in the form of list whereas sapply is used to show the output in the form of vector or data frame. Q.What Is The Difference Between Seq(4) And Seq_along(4)? Ans: Seq(4) means vector from 1 to 4 (c(1,2,3,4)) whereas seq_along(4) means a vector of the length(4) or 1(c(1)). Q.Explain How You Can Start The R Commander Gui.? Ans: rcmdr command is used to start the R commander GUI. Q.What Is The Memory Limit Of R? Ans: In 32 bit system memory limit is 3Gb but most versions limited to 2Gb and in 64 bit system memory limit is 8Tb. Q.How Many Data Structures R Has? Ans: There are 5 data structure in R i.e. vector, matrix, array which are of homogenous type and other two are list and data frame which are heterogeneous. Q.Explain How Data Is Aggregated In R.? Ans: There are two methods that is collapsing data by using one or more BY variable and other is aggregate() function in which BY variable should be in list. Q.How Many Sorting Algorithms Are Available? Ans: There are 5 types of sorting algorithms are used which are:- Bubble Sort Selection Sort Merge Sort Quick Sort Bucket Sort Q.How To Create New Variable In R Programming? Ans: For creating new variable assignment operator ‘
Continue reading