Professional Documents
Culture Documents
Untitled Document 1
Untitled Document 1
Businesses Musicians Artists & Designers Teachers + all categories Most Followed Popular Books - Fiction Books - Non-fiction Health & Medicine Brochures/Catalogs Government Docs How-To Guides/Manuals Magazines/Newspapers Recipes/Menus School Work + all categories Featured Recent
* gghhjjkk1213 o View Public Profile o My Documents o My Collections o My Shelf o Messages o Notifications o Account o Help o Log Out * Embed Doc * Copy Link * Readcast * Collections * CommentsGo Back
Download 2 Marks and 16 MarksUNIT-IPART-A 1.What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common toall objects of a certain kind. 2.What is a object? An object is a software bundle of variables and related methods.An instance of a classdepicting the state and behavior at that particular time in real world. 3.What is a method? Encapsulation of a functionality which can be called to perform specific tasks. 4.What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of theobject . Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessibl e via theinterface of the object 5.What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inh erit properties and methods from another class of objects. 6.What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language\'s ability to process objects differently depending on their data type or class . Morespecifically, it is the ability to redefine methods for derived classes. F or example, given a base class shape, polymorphism enables the programmer to def ine different area methodsfor any number of derived classes, such as circles, re ctangles and triangles. No matter what shape an object is, applying the area met hod to it will return the correct results.Polymorphism is considered to be a req uirement of any true object-oriented programminglanguage 7.Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java. 8.What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM) 9.What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public,protected and private . Other are final and stati c.10. What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private , and the default one if noidentifier is specified is called friendly, but progr ammer cannot specify the friendlyidentifier explicitly.11. What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object12 . What is a static variable and static method? What\'s the difference between two? The modifier static can be used with a variable and method. When declared as sta ticvariable, there is only one variable no matter how instances are created, thi s variable isinitialized when the class is loaded. Static method do not need a c lass to be instantiated to be called, also a non-static method cannot be called
from static method.13. What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objectsthat cannot be referenced anymore.14. What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, a classhas to be declared abstract if it has one or more abstract methods.15. What is meant by final class, methods and variables? This modifier can be applied to class, method and variable. When declared as fin al classthe class cannot be extended. When declared as final variable, its value cannot bechanged if is primitive value, if it is a reference to the object it w ill always refer to thesame object, internal attributes of the object can be cha nged.16. What is interface? Interface is a contact that can be implemented by a class , it has method that n eedimplementation.17. What is method overloading? Overloading is declaring multiple methods with the same name, but with different argument list.18. What is singleton class? Singleton class means that any given time only one instance of the class is pres ent, in oneJVM. 20.What is the difference between an array and a vector? Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically. 21.What is a constructor? In Java, the class designer can guarantee initialization of every object by prov iding aspecial method called a constructor. If a class has a constructor, Java a utomatically callsthat constructor when an object is created, before users can e ven get their hands on it. Soinitialization is guaranteed. 22.What is casting? Conversion of one type of data to another when appropriate. Casting makes explic itlyconverting of data.1. What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain beha viorsexplained above. And finally is used as one of the loop in the try catch bl ocks, It is usedto hold code that needs to be executed whether or not the except ion occurs in the trycatch block. Java provides a method called finalize( ) that can be defined in the class.When the garbage collector is ready to release the storage ed for your object, it will firstcall finalize( ), and only on the next garbage-collection pass will it reclaim the objectsmemory. So finalize( ), gives you the ability to perform some important cleanup at thetime of garbage collect ion. 24.What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from allother kinds of objects. Abstraction provides crisply-defined conceptu al boundariesrelative to the perspective of the viewer. Its the process of focus sing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the objectmodel. 25.What is meant by Encapsulation? Encapsulation is the process of compartmentalising the elements of an abtraction thatdefines the structure and behaviour. Encapsulation helps to separate the co ntractualinterface of an abstraction and implementation. 26.What is meant by Inheritance? Inheritance is a relationship among classes, wherein one class shares the struct ure or behaviour defined in another class. This is called Single Inheritance. I
f a class shares thestructure or behaviour from multiple classes, then it is cal led Multiple Inheritance.Inheritance defines \"is-a\" hierarchy among classes in which one subclass inherits fromone or more generalised superclasses. 27.What is meant by Polymorphism? Polymorphism literally means taking more than one form. Polymorphism is acharact eristic of being able to assign a different behavior or value in a subclass, tos omething that was declared in a parent class. 28.What is an Abstract Class? Abstract class is a class that has no instances. An abstract class is written wi th theexpectation that its concrete subclasses will add to its structure and beh aviour, typically by implementing its abstract operations. 29. What is an Interface? Interface is an outside view of a class or object which emphaizes its abstractio n whilehiding its structure and secrets of its behaviour. PART-B 1.Explain in detail about Java Buzzwords (or) Java features (or) characteristics .2.Explain in detail about Control Structures available in java.3.Explain method overloading with an example program4.Explain in detail about constructor overlo ading with an example5.Explain about String class, String constructor, and diffe rent String methods usinga program.6.Explain about StringBuffer class, StringBuf fer constructor, and differentStringBuffer methods using a program.7.Explain in detail about explicitly invoking garbage collector and finalize()method?8.Explai n method overloading and method overriding with give suitable example. 9.Explain vectors and their types.10.Explain classes and objects of java classes . UNIT-IIPART-A 1. What is are packages? A package is a collection of related classes and interfaces providing access pro tection and namespace management.2. What is a super class and how can you call a super class? When a class isextended that is derived from another class there is a relationsh ip is created, the parent class is referred to as the super class by the derived class that is the child.The derived class can make a call to the super class us ing the keyword super. If used in the constructor of the3. What is meant by Binding? Binding denotes association of a name with a class.4. What is meant by static binding? Static binding is a binding in which the class association is made duringcompile time. This is also called as Early binding.5. What is meant by Dynamic binding? Dynamic binding is a binding in which the class association is not made untilthe object is created at execution time. It is also called as Late binding.6. 2) What do you think is the logic behind having a single base class for allclass es? 1. casting2. Hierarchial and object oriented structure. 3) Why most of the Thread functionality is specified in Object Class? Basically for interthread communication. 4) What is the importance of == and equals() method with respect to Stringobject ? == is used to check whether the references are of the same object..equals() is u sed to check whether the contents of the objects are the same.But with respect t o strings, object refernce with same contentwill refer to the same object.String str1=\"Hello\";String str2=\"Hello\";(str1==str2) and str1.equals(str2) both wi ll be true. If you take the same example with Stringbuffer, the results would be different.S tringbuffer str1=\"Hello\";Stringbuffer str2=\"Hello\";str1.equals(str2) will be true.str1==str2 will be false.7.
Is String a Wrapper Class or not? No. String is not a Wrapper class.8. How will you find length of a String object? Using length() method of String class.9. How many objects are in the memory after the exection of following codesegment?S tring str1 = \"ABC\";String str2 = \"XYZ\";String str1 = str1 + str2; There are 3 Objects.10. What is the difference between an object and object reference? An object is an instance of a class. Object reference is a pointer to the object . There can be many refernces to the same object.11. What will trim() method of String class do? trim() eliminate spaces from both the ends of a string.***12. What is the use of java.lang.Class class? The java.lang.Class class is used to represent the classes and interfaces that a re loaded bya java program.13. What is the possible runtime exception thrown by substring() method? ArrayIndexOutOfBoundsException.14. What is the difference between String and Stringbuffer? Object\'s of String class is immutable and object\'s of Stringbuffer class is mu tablemoreover stringbuffer is faster in concatenation.15. What is the use of Math class? Math class provide methods for mathametical functions.16. Can you instantiate Math class? No. It cannot be instantited. The class is final and its constructor is private . But all themethods are static, so we can use them without instantiating the Ma th class. 17. What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. g ives you thesame value. If you supply negative value it simply removes the sign. 18. What will Math.ceil() do? This method returns always double, which is not less than the supplied value. It returnsnext available whole number 19. What will Math.floor() do? This method returns always double, which is not greater than the supplied value. 20. What will Math.min() do? The min() method returns smaller value out of the supplied values.21. What will Math.random() do? The random() method returns random number between 0.0 and 1.0. It always returns double.22. How to define an Interface? In Java Interface defines the methods but does not implement them. Interface can includeconstants. A class that implements the interfaces is bound to implement all the methodsdefined in Interface.Emaple of Interface: public interface sample Interface {public void functionOne();public long CONSTANT_ONE = 1000;}1. Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of anothe r object.24. Explain the different forms of Polymorphism .From a practical programming viewpoint, polymorphism exists in three distinct f orms inJava:1. o Method overloading o Method overriding through inheritance o Method overriding through the Java interface \\
25 . What are Access Specifiers available in Java? Access specifiers are keywords that determines the type of access to the member of aclass. These are:1. o Public o Protected o Private o Defaults \\ 26. How is it possible for two String objects with identical values not to be equalu nder the == operator? The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String o bjects tohave the same value, but located in different areas of memory.== compar es references while .equals compares contents. The method public booleanequals(O bject obj) is provided by the Object class and can be overridden. The defaultimp lementation returns true only if the object is compared with itself, which is eq uivalentto the equality operator == being used to compare aliases to the object. String, BitSet,Date, and File override the equals() method. For two String obje cts, value equality meansthat they contain the same character sequence. For the Wrapper classes, value equalitymeans that the primitive values are equal. public class EqualsTest { public static void main(String[] args) { String s1 = ab c;String s2 = s1;String s5 = abc;String s3 = new String(abc);String s4 = new String(ab c);System.out.println(== comparison : +(s1 == s5));System.out.println(== comparison : +(s1 == s2));System.out.println(Using equals method : + s1.equals(s2));System.o ut.println(== comparison : +s3 == s4);System.out.println(Using equals method : + s3 .equals(s4));}} Output== comparison : true== comparison : trueUsing equals method : truefalseUsi ng equals method : true PART-B 1.How is interface used to support multiple inheritance? Explain with a program. 2.Describe the various levels of access protection available in packages and the ir implications with an example program.3.Explain in detail about creating and a ccessing packages with an example program.4.Explain Dynamic method dispatch with o ne example program.5. Describe Method overriding. Explain it with an example.6.W rite short notes on:i) Upcastingii) Downcasting7. 7. Explain in detail about different types of Inheritance with an example program. Compare and contrast Java and C++. UNIT-IIIPART-A 1. 1. What are different types of inner classes? Member classes - Member inner classes are just like other member methods and member variables a nd access to the member class is restricted, just like methods and variables.Thi s means a public member class acts similarly to a nested top-level class. The pr imarydifference between member classes and nested top-level classes is that memb er classeshave access to the specific instance of the enclosing class. Local classes - Local classes are like local variables, specific to a block of code. Their vis ibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement amore public ly available interface.Because local classes are not members, the modifiers publ
ic, protected, private, and static are not usable. Anonymous classes - Anonymous inner classes extend local inner classes one levelfurther. As anonym ous classes have no name, you cannot provide a constructor. 2. What is the common usage of serialization? Whenever an object is to be sent over the network, objects need to be serialized .Moreover if the state of an object is to be saved, objects need to be serilazed . 3.What\ s the difference between an interface and an abstract class? An abstract class may contain code in method bodies, which is not allowed in ani nterface. With abstract classes, you have to inherit your class from it and Java does notallow multiple inheritance. On the other hand, you can implement multip le interfaces inyour class. 4.What is reflection? The ability to examine and manipulate a Java class from within itself may not so und likevery much, but in other programming languages this feature simply doesn\ t exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about thefunctions defined within that program. 5.Give an example for reflection . import java.lang.reflect.*; public class DumpMethods {public static void main(St ring args[]){try {Class c = Class.forName(args[0]);Method m[] = c.getDeclaredMet hods();for (int i = 0; i < m.length; i++)System.out.println(m[i].toString());}ca tch (Throwable e) {System.err.println(e);}}} 6.When should I use abstract classes rather than interfaces? Abstract classes are often used to provide methods that will be common to a rang e of similar subclasses, to avoid duplicating the same code in each case. Each s ubclass addsits own features on top of the common abstract methods. 7.Can you give an example of multiple inheritance with interfaces? To illustrate multiple inheritance, consider a bat, which is a mammal that flies . We mighthave two interfaces: Mammal , which has a method suckleInfant(Mammal) , and Flyer ,which has a method fly() . These types would be declared in interfaces 8.Can we create a Java class inside an interface? Yes, classes can be declared inside interfaces. This technique is sometimes used wherethe class is a constant type, return value or method argument in the inter face. When aclass is closely associated with the use of an interface it is conve nient to declare it in thesame compilation unit. This proximity also helps ensur e that implementation changes toeither are mutually compatible.A class defined i nside an interface is implicitly public static and operates as a toplevel class. The static modifier does not have the same effect on a nested class as itdoes with class variables and method s. The example below shows the definition of a StoreProcessor interface with nested StorageUnit class which is used in the twointerface methods.
9.Can an interface extend an abstract class? In Java an interface cannot extend an abstract class. An interface may only exte nd asuper-interface. And an abstract class may implement an interface. It may he lp to think of interfaces and classes as separate lines of inheritance that only come together when aclass implements an interface, the relationship cannot be r eversed .10 .Can we create an object for an interface?Yes, the most common scenario is to cr eate an object implementation for an interface,although they can be used as a pu re reference type. Interfaces cannot be instantiated intheir own right, so it is usual to write a class that implements the interface and fulfils themethods def ined in it. public class Concrete implements ExampleInterface { ...} 11.What is a marker interface? Marker interfaces are those which do not declare any required methods, but signi fy their compatibility with certain operations. The java.io.Serializable interface is a typicalmarker interface. It does not contain any methods, but cla sses must implement thisinterface in order to be serialized and de-serialized. 12.What are different types of cloning in Java? Ans) Java supports two type of cloning: - Deep and shallow cloning. By default s hallowcopy is used in Java. Object class has a method clone() which does shallow cloning. 13.What is Shallow copy? In shallow copy the object is copied without its contained objects.Shallow clone only copies the top level structure of the object not the lower levels.It is an exact bit copy of all the attributes.Figure 1: Original java object objThe shallow copy is done for obj and new object obj1 is created but contained objects of obj are not cop ied.Figure 2: Shallow copy object obj1It can be seen that no new objects are cre ated for obj1 and it is referring to the same oldcontained objects. If either of the containedObj contain any other object no new referenceis created 14.What is difference between deep and shallow cloning? The differences are as follows: Consider the class: public class MyData{String id;Map myData;}The shallow copyin g of this object will have new id object and values as but will pointto the myDat a of the original object. So a change in myData by either original or clonedobje ct will be reflected in other also. But in deep copying there will be new id obj ect andalso new myData object and independent of original object but with same v alues. Shallow copying is default cloning in Java which can be achieved using clone()me thod of Object class. For deep copying some extra logic need to be provided. 15.What are the characteristics of a shallow clone? If we do a = clone(b)1) Then b.equals(a)2) No method of a can modify the value o f b. 16.What are the disadvantages of deep cloning? Disadvantages of using Serialization to achieve deep cloning Serialization is more expensive than using object.clone(). Not all objects are serializable. Serialization is not simple to implement for deep cloned object. 17.Why are streams used in Java? In Java streams are used to process input and output data as a sequence of bytes
, whichdoes not assume a specific character content or encoding. Byte content ca n be read fromnetwork sources, files and other sources, and bytes copied between multiple inputs andoutputs.Streams types can be sub-classed to add filtering, t o mark a point in the stream and re-read those bytes, or to skip a number of byt es. Streams also enable serlializable objects tostored and re-constructed using ObjectInputStream and ObjectOutputStream types. 18.What does \"broken pipe\" mean? A pipe is an input/output link between two programs, commonly where you use theo utput from one program as the input for another program. A broken pipe means tha t thelinkage between the output and input is interrupted, the reasons vary. For example, thefeeder program may throw an error and terminate unexpectedly, interm ediate source or output files may not be created successfully, or key resources become unavailable duringthe process. You may also get problems with the amount of swap file storage or overallmemory usage approaches its limits. 19.What is the difference between the Reader/Writer class hierarchy and theInput Stream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and theInputStream/Outp utStream class hierarchy is byte-oriented. 20.What is the purpose of the File class? The File class is used to create objects that provide access to the files and di rectories of alocal file system. 21.What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usu allyaltering the data in some way as it is passed from one stream to another. 22.What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. TheRandomAccessFile class provides the methods needed to directly access data co ntainedin any part of a file. 23.What is a transient variable? A transient variable is a variable that may not be serialized. If you don\ t wan t some fieldto be serialized, you can mark that field transient or static. 24.How are Observer and Observable used? 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 obser vers tonotify the observers that it has changed state. The Observer interface is implemented byobjects that observe Observable objects. PART-B 1.Explain the InputStream class hierarchy with an example program.2.Explain the OutputStream class hierarchy with an example program.3.Explain the Reader Stream class hierarchy with an example program4.Explain the Writer Stream class hierar chy with an example program.5.What are the virtual functions? Explain their need s using a suitable example.Whatare the rules associated with virtual functions? What are the different forms of inheritance supported in c++?6.Discuss on the vi sibility of base class members in privately and publicly inheritedclasses.7.What are abstract classes? Give an example (with the program) to illustrate theuse o f abstract classes.10. Explain about Code Reuse with program. UNIT-IVPART-A1. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. 4. What are the two types of Exceptions? 1. Checked Exceptions and Unchecked Exceptions. 5.What is the base class of all exceptions? java.lang.Throwable 6.What is the difference between Exception and Error in java? 1. Exception and Error are the subclasses of the Throwable class. Exception clas sis used for exceptional conditions that user program should catch. Error define
sexceptions that are not excepted to be caught by the user program. Example isSt ack Overflow.1. What is the difference between throw and throws? throw is used to explicitly raise a exception within the program, the statementw ould be throw new Exception(); throws clause is used to indicate the exceptionst hat are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the metho dsignature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throwsIOExce ption,MyException{}1. Differentiate between Checked Exceptions and Unchecked Exceptions? Checked Exceptions are those exceptions which should be explicitly handled by th e calling method. Unhandled checked exceptions results in compilation error.Unch ecked Exceptions are those which occur at runtime and need not beexplicitly hand led. RuntimeException and it\ s subclasses, Error and it\ ssubclasses fall under unchecked exceptions. 7.What are User defined Exceptions? 1. Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. 8.What is the importance of finally block in exception handling? 1. Finally block will be executed whether or not an exception is thrown. If anex ception is thrown, the finally block will execute even if no catch statementmatc h the exception. Any time a method is about to return to the caller frominside t ry/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources likedat abase connections, IO handles, etc. 9.Can a catch block exist without a try block? 1. No. A catch block should always go with a try block.10. Can a finally block exist with a try block but without a catch? Yes. The following are the combinations try/catch or try/catch/finally or try/fi nally.11. What will happen to the Exception object after exception handling? Exception object will be garbage collected.12. How does finally block differ from finalize() method? Finally block will be executed whether or not an exception is thrown. So it is u sed tofree resoources. finalize() is a protected method in the Object class whic h is called by theJVM just before an object is garbage collected. 13. What are the constraints imposed by overriding on exception handling? An overriding method in a subclass may only throw exceptions declared in the par entclass or children of the exceptions declared in the parent class.\\ 14. What is an Exception? An exception is an abnormal condition that arises in a code sequence at run time. In other wo rds, an exception is a run-time error. 15. What is a Java Exception? A Java exception is an object that describes an exceptional condition i.e., an e rror condition that has occurred in a piece of code. When this type of condition arises, anobject representing that exception is created and thrown in the method that caused theerror by the Java Runtime. That method may choose t o handle the exception itself, or pass it on. Either way, at some point, the ex ception is caught and processed. 16. What are the different ways to generate andException? There are two different ways to generate an Exception.1.Exceptions can be genera ted by the Java run-time system.Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Javalanguage or the constraints of the Java execution environment.1.Exceptions can be manually generated by your code.Manua lly generated exceptions are typically used to report some error condition to th ecaller of a method. 17.Where does Exception stand in the Java treehierarchy? java.lang. Object java.lang. Throwable java.lang. Exception java.lang. Error 18. Is it compulsory to use the finally block? It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For examplewhile closing a connection object an exception has occurred. In finally block we canclose that object. Coming to the question, you can omit t he finally block when there is acatch block associated with that try block. A tr y block should have at least a catch or afinally block. 19. What is a throw in an Exception block? throw is used to manually throw an exception (object) of type Throwable class or asubclass of Throwable . Simple types, such as int or char , as well as nonThrowable classes, such as String and Object , cannot be used as exceptions. The flow of executionstops immediately after the throw statement; any subsequent statements are not executed. throw ThrowableInstance ; ThrowableInstance must be an object of type Throwable ora subclass of Throwable .
throw new NullPointerException(\"thrownException\"); 20.Why do I get a run-time Error when I add components to a JFrame/JDialog/JInternalFrame/JWindow ? In Swing, top-level windows (such as JFrame or JDialog ) do nothave components added directly to the window. Instead, add them to the c ontent pane like this: myWindow.getContentPane().add(component) 21.Where are the scroll bars on my JList (or JTextArea )? Swing components dont implement scrolling directly. Scrolling has instead beenenc apsulated in the JScrollPane class. To get scrollbars on a component, wrap it in a JScrollPane . Instead of: panel.add(component) use panel.add(new JScrollPane(component)); Components that implement the Scrollable interface will interact with JScrollPane toconfigure the scrolling behavior. Components that dont implement Scrollable will getthe default behavior supplied by JScrollPane . 22.How can I save space in my screens? Look at JSplitPane , JTabbedPane , JLayeredPane , and JScrollPane . They all provideways to let other components share space. 23.Whats the easiest way to create a dialog? Use a JOptionPane . It builds in features useful in simple dialogs. 24.How can I prevent a window from closing? By default, a window is hidden (but not disposed of) when it is closed. This hap pens after all window listeners have executed. To prevent the window from closin g unless the program closes it, use this code: frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 25.Can I mix Swing and AWT components? Yes, but You can mix these components, and its documented athttp://java.sun.com/prod
ucts/jfc/tsc/swingdoc-archive/mixing.html.However, if its at all possible, youll f ind it much less problematic to converteverything to Swing. (The problem is that AWT components are heavyweight, whileSwing components are lightweight, and heav yweight components always appear abovelightweight components; this causes diffic ulty for things like tabbed panes, internalframes, popup menus, etc.) 26. How do I use internal frames? Sun has a couple of articles explaining JInternalFrame and JDesktopPane in the SwingConnection: Creating MDI Programs with Swing Internalizable/Externalizable Frames 27.How do I use an image as the background for a JPanel ? Override the JPanel s paintComponent() method and use it to paint the image (whichyou should store as an ImageIcon ). For example: public void paintComponent(java.awt.Graphics g){super.paintComponent(g);int widt h = getWidth();int height = getHeight();java.awt.Color oldColor = g.getColor();i f (opaque){g.setColor(getBackground());g.fillRect(0, 0, width, height);}if (theI mage != null){g.drawImage(theImage.getImage(), 0, 0, this);}g.setColor(oldColor) ;} 28. How can I capture KeyEvent s for the Tab key? Override isManagingFocus() to return true , then all key events should be sent to your JComponent . < Christian Kaufhold > 29. How can I make a JComboBox textfield empty? Call theComboBox.setSelectedItem(null); < Per Cederberg > 30.Why is my JList / JTree component sized improperly when I add/removeitems from the Model? While there could be many reasons for this behavior, one possibility is that you have a JScrollPane in a
GridBagLayout without a minimum size set. Try setting a reasonablevalue and see if your proble m disappears.< Brian Sletten > 31.Can I save my UI designs as XML documents? This should be added in J49655DK 1.4. Theres an article about this new support on TheSwing Connection. Using XML serialization is much more compact than using th e oldObject serialization, but it isnt appropriate for serializing everything. 32.How do I change fonts/colors/etc. in my JOptionPane? The easiest way is to use the JOptionPane constructor where you supply the compo nentsthat are used to build the JOptionPane. Since you create the components, yo u can dowhatever you want to them before you pass them to the JOptionPane. The c onstructors touse are any of the ones that take Objects. See the JOptionPane Jav aDoc for details onwhat kinds of Objects you can pass to these constructors. 33.How can the Checkbox class be used to create a radio button? By associating Checkbox objects with a CheckboxGroup 34.Name three subclasses of the Component class? Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent 35.What is the relationship between an event-listener interface and an eventadap terclass? An event-listener interface defines the methods that must be implemented by an e venthandler for aparticular kind of event. An event adapter provides a defaultim plementation of an event listener interface. 36.What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface 37.What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container.ASc rollPane handles itsown events and performs its own scrolling. 38.What is layout manager ? How does it work? A layout manager is an object that positions and resizes the components in a Con tainer according to some algorithm; for example, the FlowLayout layout manager l ays outcomponents from left to right until it runs out of room and then continue s laying outcomponents below that row. 39. Difference between Swing and Awt? AWT are heavy-weight componenets. Swings are light-weight components. Hence swin gworks faster than AWT. 40.Can applets communicate with each other? At this point in time applets may communicate with other applets running in the samevirtual machine. If the applets are of the same class, they can communicate via sharedstatic variables. If the applets are of different classes, then each w ill need a reference tothe same class with static variables. In any case the bas ic idea is to pass the information back and forth through a static variable. PART-B 1.Explain in detail about Applet Life cycle.2.Write a program to demonstrate the Life cycle of an applet. 3.Write a program to perform the following operations by using applet.(i) Draw a Line, Rectangle(ii) Draw a oval and fill it(iii) Draw a polygon(iv) Set the bac kground and foreground color.4. Explain in detail about Event handling mechanism with an example.5.Describe about Key Event and Mouse Event.6.Explain about Template and its types with example.7.Discuss about Streams and stream classes8.Write no tes on Formatted and Unformatted Console I/O Operations.9.Explain about File Poi nters and Manipulations with example. Discuss aboutmanipulators and file streams with Program.10.Write on Details about File modes and File I/O. UNIT-V PART-A 1.
What invokes a thread\ s run() method? After a thread is started, via its start()method or that of the Thread class, th e JVM invokes the thread\ s run() methodwhen the thread is initially executed.2. What is the GregorianCalendar class? The GregorianCalendar provides supportfor traditional Western calendars.1. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.3. What is the Properties class? The properties class is a subclass of Hashtable thatcan be read from or written to a stream. It also provides the capability to specify aset of default values t o be used.1. What is the purpose of the Runtime class? The purpose of the Runtimeclass is to provide access to the Java runtime system. 2. What is the purpose of the System class? The purpose of the Systemclass is to provide access to system resources.4. What is the purpose of the finally clause of a try-catch-finally statement? Thefinally clause is used to provide the capability to execute code no matter wh ether or not an exception is thrown or caught. For example,i. try{//some stateme nts}catch{// statements when exception is cought}finally {//statements executed whether exception occurs or not}1. What is the Locale class? The Locale class is used to tailor program output tothe conventions of a particu lar geographic, political, or cultural region.2. What must a class do to implement an interface? It must provide all of themethods in the interface and identify the interface in its implements clause.1. What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.3. What is multi-threading? Multi-threading as the name suggest is the scenariowhere more than one threads a re running.4. What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread andca n implement the rum method or the run method of a different class can becalled w hich implements the interface Runnable, and the then implement the run()method. The latter one is mostly used as first due to Java rule of only one classinherit ance, with implementing the Runnable interface that problem is sorted out.1. What is deadlock? Deadlock is a situation when two threads are waitingon each other to release a r esource. Each thread waiting for a resourcewhich is held by the other waiting th read. In Java, this resource is usuallythe object lock obtained by the synchroni zed keyword.5. What are the three types of priority? MAX_PRIORITY which is 10,MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.10. What is the use of synchronizations? Every object has a lock, when a synchronizedkeyword is used on a piece of code t he, lock must be obtained by the thread first toexecute that code, other threads will not be allowed to execute that piece of code till thislock is released.11. What are synchronized methods and synchronized statements? Synchronizedmethods are methods that are used to control access to an object. Fo r example, a threadonly executes a synchronized method after it has acquired the lock for the method\ sobject or class. Synchronized statements are similar to s ynchronized methods. Asynchronized statement can only be executed after a thread has acquired the lock for theobject or class referenced in the synchronized sta tement.12. What are different ways in which a thread can enter the waiting state? A threadcan enter the waiting state by invoking its sleep() method, blocking on I/O,unsuccessfully attempting to acquire an object\ s lock, or invoking an objec
t\ s wait()method. It can also enter the waiting state by invoking its (deprecat ed) suspend() method.13. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. Thislock is acquired on the class\ s Cla ss object. 1. What\ s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.14. What is the preferred size of a component? The preferred size of a component isthe minimum component size that will allow t he component to display normally.15. What method is used to specify a container\ s layout? The setLayout() method isused to specify a container\ s layout. For example, set Layout(new FlowLayout()); will beset the layout as FlowLayout.16. What state does a thread enter when it terminates its processing? When a threadterminates its processing, it enters the dead state.1. What do you understand by Synchronization? Synchronization is a process of controlling the access of shared resources by th emultiple threads in such a manner that only one thread can access one resource ata time. In non synchronized multithreaded application, it is possible for one threadto modify a shared object while another thread is in the process of using or updating the object\ s value. Synchronization prevents such type of datacorru ption. E.g. Synchronizing a function: public synchronized void Method1 () {// Appropriate method-related code.} E.g. Synchronizing a block of code inside a function: public myFunction (){synchronized (this) {// Synchronized code here.}}18. What is Runnable interface ? Are there any other ways to make a java programas m ultithred java program? There are two ways to create new kinds of threads: 1.Define a new class that ext ends the Thread class2.Define a new class that implements the Runnable interface , and pass an object of that class to a Thread\ s constructor.3.An advantage of the second approach is that the new class can be a subclass of any class, not ju st of the Thread class. Here is a very simple example just to illustrate how to use the second approach tocreating threads: class myThread implements Runnable { public void run() {Syst em.out.println(\"I\ m running!\");}} public class tstRunnable {myThread my1 = n ew myThread();myThread my2 = new myThread();new Thread(my1).start();new Thread(m y2).start();} The Runnable interface has only one method: public void run();Thus , every class (thread) implements the Runnable interface, has to provide logic f or run() method 19.How can i tell what state a thread is in ? Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive () returnedfalse the thread was either new or terminated but there was simply no way to differentiate between the two. Starting with the release of Tiger (Java 5) you can now get what state a thread is in byusing the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time. NEW A Fresh thread that has not yet started to execute.RUNNABLE A thread that is executing in the Java virtual machine.BLOCKED A thread that is blocked waiting for a monitor lock.WAITING A thread that is wa ting to be notified by another thread.TIMED_WAITING A thread that is wating to b e notified by another thread for a specificamount of timeTERMINATED A thread who s run method has ended. The folowing code prints out all thread states. public class ThreadStates{ public static void main(String[] args){Thread t = new Thread ();Thread.State e = t.getState();Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){System.out.println(ts[i]);}}} 20. What methods java providing for Thread communications ? Java provides three methods that threads can use to communicate with each other: wait,notify, and notifyAll. These methods are defined for all Objects (not just Threads). Theidea is that a method called by a thread may need to wait for some condition to besatisfied by another thread; in that case, it can call the wait method, which causes itsthread to wait until another thread calls notify or noti fyAll. 21.What is the difference between notify and notify All methods ? A call to notify causes at most one thread waiting on the same object to be noti fied (i.e.,the object that calls notify must be the same as the object that call ed wait). A call tonotifyAll causes all threads waiting on the same object to be notified. If more than onethread is waiting on that object, there is no way to control which of them is notified by acall to notify (so it is often better to u se notifyAll than notify). 22.What is synchronized keyword? In what situations you will Use it? Synchronization is the act of serializing access to critical sections of code. W e will usethis keyword when we expect multiple threads to access/modify the same data. Tounderstand synchronization we need to look into thread execution manner . Threads may execute in a manner where their paths of execution are completelyi ndependent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaint s a window.And then there are threads that require synchronization, the act of s erializing access to critical sections of code, at various moments during their executions. For examp le, saythat two threads need to send data packets over a single network connecti on. Each threadmust be able to send its entire data packet before the other thre ad starts sending its data packet; otherwise, the data is scrambled. This scenar io requires each thread tosynchronize its access to the code that does the actua l data-packet sending. If you feel a method is very critical for business that n eeds to be executed by only onethread at a time (to prevent data loss or corrupt ion), then we need to use synchronizedkeyword. EXAMPLE Some real-world tasks are better modeled by a program that uses threads than by anormal, sequential progr am. For example, consider a bank whose accounts can beaccessed and updated by an y of a number of automatic teller machines (ATMs). EachATM could be a separate t hread, responding to deposit and withdrawal requests fromdifferent users simulta neously. Of course, it would be important to make sure that twousers did not acc ess the same account simultaneously. This is done in Java usingsynchronization, which can be applied to individual methods, or to sequences of statements. One o r more methods of a class can be declared to be synchronized. When a thread call san object\ s synchronized method, the whole object is locked. This means that i f another thread tries to call any synchronized method of the same object, the c all will block untilthe lock is released (which happens when the original call f inishes). In general, if thevalue of a field of an object can be changed, then a ll methods that read or write that fieldshould be synchronized to prevent two th reads from trying to write the field at the sametime, and to prevent one thread from reading the field while another thread is in the process of writing it. Her e is an example of a BankAccount class that uses synchronized methods to ensure thatdeposits and withdrawals cannot be performed simultaneously, and to ensure t hat theaccount balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the example simple, no check is done to ensure that a withdrawal does not l ead to anegative balance.) public class BankAccount {1.private double balance; // constructor: set balance to given amount public BankAccount( double initialDe posit ) { balance = initialDeposit;} public synchronized double Balance( ) {ret urn balance;} public synchronized void Deposit( double deposit ) { balance += d
eposit;} public synchronized void Withdraw( double withdrawal ) { balance -= wi thdrawal; } } Note: that the BankAccount\ s constructor is not declared to be synchronize d. That is because it can only be executed when the object is being created, and no other methodcan be called until that creation is finished. There are cases w here we need to synchronize a group of statements, we can do thatusing synchroze d statement. Java Code Example synchronized ( B ) {if ( D > B.Balance() ) {Repor tInsuffucientFunds();}else {B.Withdraw( D );}} 23.What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and isunable to acquirean object\ s lock, it enters the waiting state until the lock becomesavailable. 24.What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and isunable to acquire an object\ s lock, it enters the waiting state until the lock becomesavailable. 25.What is an object\ s lock and which object\ s have locks? An object\ s lock is a mechanism that is used by multiple threads to obtain sync hronizedaccess to the object. A thread may execute a synchronized method of an o bject onlyafter it has acquired theobject\ s lock. All objects and classes have locks. A class\ s lock isacquired on the class\ s Class object. PART-B 1.Explain Exception Handling and Multiple catch statement2.Explain Multithreadin g programming with suitable example3.Explain method overloading and method overr iding with give suitable example.4.What are the differences between the accesses specifies private and protected?5.What are base and derived classes? Write a pr ogram to use these classes.6.What are the different forms of inheritance? Explai n with an example.7.What is class hierarchy? Explain how inheritance helps in bu ilding classhierarchies.8.What is visibility mode? What are the different visibi lity modes supported by C++?9.What are the differences between inheriting a clas s with public and privatevisibility mode?10.What are virtual classes? Explain th e need for virtual classes while building class.11. What are abstract classes? E xplain the role of abstract class while building a classhierarchy. of 31 Leave a Comment Comment must not be empty. Submit Characters: 400 Comment must not be empty. Submit Characters: ... IT2301 Java Download or Print 839 Reads Info and Rating Category: Uncategorized. Rating: Upload Date: 11/11/2010 Copyright: Attribution Non-commercial Tags: This document has no tags. Flag document for inapproriate content This is a private document. Uploaded by kirthisarala Download *
Embed Doc * Copy Link * Add To Collection * Comments * Readcast * Share Share on Scribd: Readcast Search TIP Press Ctrl-F F to quickly search anywhere in the document. Search Search History: Searching... Result 00 of 00 00 results for result for # p. More from This User Related Documents More From This User 8 p. IEEE 2010 Titles[1] 43 p. UNIT I-CN 43 p. UNIT I-CN Next 31 p. IT2301 Java 20 p. Java+Lab+Programs Prev Related Docuements 72 p. inteview_corejava From api_11797_shankar79 17 p. Cs2305- Programming Paradigms From Radha Murali 73 p. Java 1 From dearmohseen Next 73 p. Java Interview Questions and Answers From Ashish 17 p. CS2305 From Suresh Kumar
41 p. Java Abstract Class and Interface Interview Questions From Sarada Prasanna Mohapatra Prev Next 41 p. Java Swing Interview Questions From Sarada Prasanna Mohapatra 41 p. 7217049 Java Interview Questions From Sarada Prasanna Mohapatra 23 p. Java_Lang From api_user_11797_ram.manasi Prev Next 40 p. Java Interview Questions From api_11797_haribarath 30 p. ja From api_user_11797_srkonline 30 p. Core Java Interview Questions From pravzK Prev Next 25 p. Core Java Interview Questions From Rambabu Midathana 25 p. Core Java Interview Questions 1 From Srikanth Jaini 31 p. java IQ1 From naglav Prev Next 25 p. Core Java Interview Questions BY Srinivasa Reddy Challa (Corporate ... important From Srinivasa Reddy Challa Prev Upload a Document Search Documents * * * * * * * * * * * * * * Follow Us! scribd.com/scribd twitter.com/scribd facebook.com/scribd About Press Blog Partners Scribd 101 Web Stuff Support FAQ Developers / API Jobs
* Terms * Copyright * Privacy Copyright 2012 Scribd Inc. Language: English Choose the language in which you want to experience Scribd: * English * Espaol * Portugus scribd. scribd. scribd. scribd. scribd. scribd. scribd. scribd. Download This Document PDF * PDF * DOC * TXT Document size: 241.13 117.5 49.478 Document name: 42029157-IT2301-Java.pdf.doc.txt Download PDF Your download has started. Close this dialog. Having trouble downloading? Try again. );}}};(function(){var _map={};easyXDM.Fn={set:function(name,fn){_map[name]=fn;} ,get:function(name,del){var fn=_map[name];if(del){delete _map[name];} return fn; }};}());easyXDM.Socket=function(config){var stack=chainStack(prepareTransportSta ck(config).concat([{incoming:function(message,origin){config.onMessage(message,o rigin);},callback:function(success){if(config.onReady){config.onReady(success);} }}])),recipient=getLocation(config.remote);this.destroy=function(){stack.destroy ();};this.postMessage=function(message){stack.outgoing(message,recipient);};stac k.init();};easyXDM.Rpc=function(config,jsonRpcConfig){if(jsonRpcConfig.local){fo r(var method in jsonRpcConfig.local){if(jsonRpcConfig.local.hasOwnProperty(metho d)){var member=jsonRpcConfig.local[method];if(typeof member==="function"){jsonRp cConfig.local[method]={method:member};}}}} var stack=chainStack(prepareTransport Stack(config).concat([new easyXDM.stack.RpcBehavior(this,jsonRpcConfig),{callbac k:function(success){if(config.onReady){config.onReady(success);}}}]));this.destr oy=function(){stack.destroy();};stack.init();};easyXDM.stack.PostMessageTranspor t=function(config){var pub,frame,callerWindow,targetOrigin;function _getOrigin(e vent){if(event.origin){return event.origin;} if(event.uri){return getLocation(ev ent.uri);} if(event.domain){return location.protocol+"//"+event.domain;} throw"U nable to retrieve the origin of the event";} function _window_onMessage(event){v ar origin=_getOrigin(event);if(origin==targetOrigin&&event.data.substring(0,conf ig.channel.length+1)==config.channel+" "){pub.up.incoming(event.data.substring(c onfig.channel.length+1),origin);}} return(pub={outgoing:function(message,domain, fn){callerWindow.postMessage(config.channel+" "+message,domain||targetOrigin);fn ();},destroy:function(){un(window,"message",_window_onMessage);if(frame){callerW indow=null;frame.parentNode.removeChild(frame);frame=null;}},init:function(){tar getOrigin=getLocation(config.remote);if(config.isHost){on(window,"message",funct ion waitForReady(event){if(event.data==config.channel+"-ready"){callerWindow=fra me.contentWindow;un(window,"message",waitForReady);on(window,"message",_window_o nMessage);setTimeout(function(){pub.up.callback(true);},0);}});apply(config.prop s,{src:appendQueryParameters(config.remote,{xdm_e:location.protocol+"//"+locatio n.host,xdm_c:config.channel,xdm_p:1})});frame=createFrame(config);} else{on(wind ow,"message",_window_onMessage);callerWindow=window.parent;callerWindow.postMess age(config.channel+"-ready",targetOrigin);setTimeout(function(){pub.up.callback( true);},0);}}});};easyXDM.stack.NixTransport=function(config){var pub,frame,send ,targetOrigin,proxy;return(pub={outgoing:function(message,domain,fn){send(messag
e);fn();},destroy:function(){proxy=null;if(frame){frame.parentNode.removeChild(f rame);frame=null;}},init:function(){targetOrigin=getLocation(config.remote);if(c onfig.isHost){try{if(!isHostMethod(window,"GetNixProxy")){window.execScript( Cla ss NixProxy\n + Private m_parent, m_child, m_Auth\n + \n + Public Sub SetParen t(obj, auth)\n + If isEmpty(m_Auth) Then m_Auth = auth\n + SET m_parent = obj\ n + End Sub\n + Public Sub SetChild(obj)\n + SET m_child = obj\n + m_parent. ready()\n + End Sub\n + \n + Public Sub SendToParent(data, auth)\n + If m_Aut h = auth Then m_parent.send(CStr(data))\n + End Sub\n + Public Sub SendToChild (data, auth)\n + If m_Auth = auth Then m_child.send(CStr(data))\n + End Sub\n + End Class\n + Function GetNixProxy()\n + Set GetNixProxy = New NixProxy\n + E nd Function\n , vbscript );} proxy=GetNixProxy();proxy.SetParent({send:function( msg){pub.up.incoming(msg,targetOrigin);},ready:function(){setTimeout(function(){ pub.up.callback(true);},0);}},config.secret);send=function(msg){proxy.SendToChil d(msg,config.secret);};} catch(e){throw new Error("Could not set up VBScript Nix Proxy:"+e.message);} apply(config.props,{src:appendQueryParameters(config.remote ,{xdm_e:location.protocol+"//"+location.host,xdm_c:config.channel,xdm_s:config.s ecret,xdm_p:3})});frame=createFrame(config);frame.contentWindow.opener=proxy;} e lse{try{proxy=window.opener;} catch(e){throw new Error("Cannot access window.ope ner");} proxy.SetChild({send:function(msg){global.setTimeout(function(){pub.up.i ncoming(msg,targetOrigin);},0);}});send=function(msg){proxy.SendToParent(msg,con fig.secret);};setTimeout(function(){pub.up.callback(true);},0);}}});};easyXDM.st ack.NameTransport=function(config){var pub;var isHost,callerWindow,remoteWindow, readyCount,callback,remoteOrigin,remoteUrl;function _sendMessage(message){var ur l=config.remoteHelper+(isHost?("#_3"+encodeURIComponent(remoteUrl+"#"+config.cha nnel)):("#_2"+config.channel));callerWindow.contentWindow.sendMessage(message,ur l);} function _onReady(){if(isHost){if(++readyCount===2||!isHost){pub.up.callbac k(true);}} else{_sendMessage("ready");pub.up.callback(true);}} function _onMessa ge(message){pub.up.incoming(message,remoteOrigin);} function _onLoad(){if(callba ck){setTimeout(function(){callback(true);},0);}} return(pub={outgoing:function(m essage,domain,fn){callback=fn;_sendMessage(message);},destroy:function(){callerW indow.parentNode.removeChild(callerWindow);callerWindow=null;if(isHost){remoteWi ndow.parentNode.removeChild(remoteWindow);remoteWindow=null;}},init:function(){i sHost=config.isHost;readyCount=0;remoteOrigin=getLocation(config.remote);config. local=resolveUrl(config.local);if(isHost){easyXDM.Fn.set(config.channel,function (message){if(isHost&&message==="ready"){easyXDM.Fn.set(config.channel,_onMessage );_onReady();}});remoteUrl=appendQueryParameters(config.remote,{xdm_e:config.loc al,xdm_c:config.channel,xdm_p:2});apply(config.props,{src:remoteUrl+ # +config.c hannel,name:config.channel});remoteWindow=createFrame(config);} else{config.remo teHelper=config.remote;easyXDM.Fn.set(config.channel,_onMessage);} callerWindow= createFrame({props:{src:config.local+"#_4"+config.channel},onLoad:function(){un( callerWindow,"load",callerWindow.loadFn);easyXDM.Fn.set(config.channel+"_load",_ onLoad);_onReady();}});}});};easyXDM.stack.HashTransport=function(config){var pu b;var me=this,isHost,_timer,pollInterval,_lastMsg,_msgNr,_listenerWindow,_caller Window;var usePolling,useParent,useResize,_remoteOrigin;function _sendMessage(me ssage){if(!_callerWindow){return;} var url=config.remote+"#"+(_msgNr++)+"_"+mess age;if(isHost||!useParent){_callerWindow.contentWindow.location=url;if(useResize ){_callerWindow.width=_callerWindow.width>75?50:100;}} else{_callerWindow.locati on=url;}} function _handleHash(hash){_lastMsg=hash;pub.up.incoming(_lastMsg.subs tring(_lastMsg.indexOf("_")+1),_remoteOrigin);} function _onResize(){_handleHash (_listenerWindow.location.hash);} function _pollHash(){if(_listenerWindow.locati on.hash&&_listenerWindow.location.hash!=_lastMsg){_handleHash(_listenerWindow.lo cation.hash);}} function _attachListeners(){if(usePolling){_timer=setInterval(_p ollHash,pollInterval);} else{on(_listenerWindow,"resize",_onResize);}} return(pu b={outgoing:function(message,domain){_sendMessage(message);},destroy:function(){ if(usePolling){window.clearInterval(_timer);} else if(_listenerWindow){un(_liste nerWindow,"resize",_pollHash);} if(isHost||!useParent){_callerWindow.parentNode. removeChild(_callerWindow);} _callerWindow=null;},init:function(){isHost=config. isHost;pollInterval=config.interval;_lastMsg="#"+config.channel;_msgNr=0;usePoll ing=config.usePolling;useParent=config.useParent;useResize=config.useResize;_rem oteOrigin=getLocation(config.remote);if(!isHost&&useParent){_listenerWindow=wind
ow;_callerWindow=parent;_attachListeners();pub.up.callback(true);} else{apply(co nfig,{props:{src:(isHost?config.remote:config.remote+"#"+config.channel),name:(i sHost?"local_":"remote_")+config.channel},onLoad:(isHost&&useParent||!isHost)?(f unction(){_listenerWindow=window;_attachListeners();pub.up.callback(true);}):nul l});_callerWindow=createFrame(config);if(isHost&&!useParent){var tries=0,max=con fig.delay/50;(function getRef(){if(++tries>max){throw new Error("Unable to refer ence listenerwindow");} if(_listenerWindow){return;} try{_listenerWindow=_caller Window.contentWindow.frames["remote_"+config.channel];window.clearTimeout(_timer );_attachListeners();pub.up.callback(true);return;} catch(ex){setTimeout(getRef, 50);}}());}}}});};easyXDM.stack.ReliableBehavior=function(config){var pub,timer, current,next,sendId=0,sendCount=0,maxTries=config.tries||5,timeout=config.timeou t,receiveId=0,callback;return(pub={incoming:function(message,origin){var indexOf =message.indexOf("_"),ack=parseInt(message.substring(0,indexOf),10),id;message=m essage.substring(indexOf+1);indexOf=message.indexOf("_");id=parseInt(message.sub string(0,indexOf),10);indexOf=message.indexOf("_");message=message.substring(ind exOf+1);if(timer&&ack===sendId){window.clearTimeout(timer);timer=null;if(callbac k){setTimeout(function(){callback(true);},0);}} if(id!==0){if(id!==receiveId){re ceiveId=id;message=message.substring(id.length+1);pub.down.outgoing(id+"_0_ack", origin);setTimeout(function(){pub.up.incoming(message,origin);},config.timeout/2 );} else{pub.down.outgoing(id+"_0_ack",origin);}}},outgoing:function(message,ori gin,fn){callback=fn;sendCount=0;current={data:receiveId+"_"+(++sendId)+"_"+messa ge,origin:origin};(function send(){timer=null;if(++sendCount>maxTries){if(callba ck){setTimeout(function(){callback(false);},0);}} else{pub.down.outgoing(current .data,current.origin);timer=setTimeout(send,config.timeout);}}());},destroy:func tion(){if(timer){window.clearInterval(timer);} pub.down.destroy();}});};easyXDM. stack.QueueBehavior=function(config){var pub,queue=[],waiting=true,incoming="",d estroying,maxLength=0;function dispatch(){if(waiting||queue.length===0||destroyi ng){return;} waiting=true;var message=queue.shift();pub.down.outgoing(message.da ta,message.origin,function(success){waiting=false;if(message.callback){setTimeou t(function(){message.callback(success);},0);} dispatch();});} return(pub={init:f unction(){if(undef(config)){config={};} maxLength=config.maxLength?config.maxLen gth:0;pub.down.init();},callback:function(success){waiting=false;dispatch();pub. up.callback(success);},incoming:function(message,origin){var indexOf=message.ind exOf("_"),seq=parseInt(message.substring(0,indexOf),10);incoming+=message.substr ing(indexOf+1);if(seq===0){if(config.encode){incoming=decodeURIComponent(incomin g);} pub.up.incoming(incoming,origin);incoming="";}},outgoing:function(message,o rigin,fn){if(config.encode){message=encodeURIComponent(message);} var fragments= [],fragment;if(maxLength){while(message.length!==0){fragment=message.substring(0 ,maxLength);message=message.substring(fragment.length);fragments.push(fragment); }} else{fragments.push(message);} while((fragment=fragments.shift())){queue.push ({data:fragments.length+"_"+fragment,origin:origin,callback:fragments.length===0 ?fn:null});} dispatch();},destroy:function(){destroying=true;pub.down.destroy(); }});};easyXDM.stack.VerifyBehavior=function(config){var pub,mySecret,theirSecret ,verified=false;function startVerification(){mySecret=Math.random().toString(16) .substring(2);pub.down.outgoing(mySecret);} return(pub={incoming:function(messag e,origin){var indexOf=message.indexOf("_");if(indexOf===-1){if(message===mySecre t){pub.up.callback(true);} else if(!theirSecret){theirSecret=message;if(!config. initiate){startVerification();} pub.down.outgoing(message);}} else{if(message.su bstring(0,indexOf)===theirSecret){pub.up.incoming(message.substring(indexOf+1),o rigin);}}},outgoing:function(message,origin,fn){pub.down.outgoing(mySecret+"_"+m essage,origin,fn);},callback:function(success){if(config.initiate){startVerifica tion();}}});};easyXDM.stack.RpcBehavior=function(proxy,config){var pub,serialize r=config.serializer||getJSON();var _callbackCounter=0,_callbacks={};function _se nd(data){data.jsonrpc="2.0";pub.down.outgoing(serializer.stringify(data));} func tion _createMethod(definition,method){var slice=Array.prototype.slice;return fun ction(){var l=arguments.length,callback,message={method:method};if(l>0&&typeof a rguments[l-1]==="function"){if(l>1&&typeof arguments[l-2]==="function"){callback ={success:arguments[l-2],error:arguments[l-1]};message.params=slice.call(argumen ts,0,l-2);} else{callback={success:arguments[l-1]};message.params=slice.call(arg uments,0,l-1);} _callbacks[""+(++_callbackCounter)]=callback;message.id=_callbac
kCounter;} else{message.params=slice.call(arguments,0);} _send(message);};} func tion _executeMethod(method,id,fn,params){if(!fn){if(id){_send({id:id,error:{code :-32601,message:"Procedure not found."}});} return;} var used=false,success,erro r;if(id){success=function(result){if(used){return;} used=true;_send({id:id,resul t:result});};error=function(message){if(used){return;} used=true;_send({id:id,er ror:{code:-32099,message:"Application error: "+message}});};} else{success=error =emptyFn;} try{var result=fn.method.apply(fn.scope,params.concat([success,error] ));if(!undef(result)){success(result);}} catch(ex1){error(ex1.message);}} return (pub={incoming:function(message,origin){var data=serializer.parse(message);if(da ta.method){if(config.handle){config.handle(data,_send);} else{_executeMethod(dat a.method,data.id,config.local[data.method],data.params);}} else{var callback=_ca llbacks[data.id];if(data.error){if(callback.error){callback.error(data.error);}} else if(callback.success){callback.success(data.result);} delete _callbacks[dat a.id];}},init:function(){if(config.remote){for(var method in config.remote){if(c onfig.remote.hasOwnProperty(method)){proxy[method]=_createMethod(config.remote[m ethod],method);}}} pub.down.init();},destroy:function(){for(var method in config .remote){if(config.remote.hasOwnProperty(method)&&proxy.hasOwnProperty(method)){ delete proxy[method];}} pub.down.destroy();}});};})(window,document,location,win dow.setTimeout,decodeURIComponent,encodeURIComponent); Icon_archives_35x35 The Scribd Archive This document was uploaded by someone just like you and is now part of The Scrib d Archive*. Give back to the community and gain 24 hours of download access by u ploading something of your own. Processing... Do you understand the Scribd Terms of Service and Copyright Policy, and confirm that your uploading of this material complies with those policies and does not v iolate anyone s rights? Queued: Uploading: You have uploaded: Upload failed: Document URL: This document is: PrivateThis document is: Public Cancel Upload
Make it easier to find your new document! Title: Category: Tags: (separate with commas) Description: Save Or_divider_550x7 Subscribe to The Scribd Archive and download as many documents as you d like. Monthly Subscription Most Popular $9/mo. 1 Day Pass $5 1 Year Pass $59 Choose payment option Pay with Credit Card Pay with PayPal or Credit * The Scribd Archive is a collection of millions of documents, including researc h reports, best-selling books, news source materials, and more. Read the Scribd Archive FAQ for more information. PDF * PDF * DOC
* TXT Document size: 241.13 117.5 49.478 Document name: 42029157-IT2301-Java.pdf.doc.txt Download PDF Your download has started. Close this dialog. Having trouble downloading? Try again.