Sei sulla pagina 1di 7

Why the methods of the Math class are static? Its to reduce un-necessary object creation.

Generally utility class methods should be kept static.See if the methods of Math class are non static then you will have to create object of Math class every time and that object is of no use after method is called once.To reduce un necessary object creation and keep the garbage collector heap healthymethod should be made static if they are utility methods.Math class methods do not depend on instance variables ...hence, why to create a object of math class....math.min(2,1) -> 1Method execution in math class depend on method args, and not instance variables...Even if u tries to create an object of Math class ...U will get an exception... Since math class has a private constructor.. Can we define an interface within an interface? Yes u can write interface within another interface.And if u want to implement inner interface u have to access it usingouter_interface_name.inner_interface_name.eg.// abc.javainterface abc {void show(); public interface xyz {void calc();}}// InterfaceImpl.java public class InterfaceImpl implements abc.xyz { public void show(){System.out.println("Hi");} public void calc(){}}

What is the meaning of persistence? Persistence means 'to save'. In java, persistence is referred to saving the state of an objectfrom memory to some other media (mostly permanent media such as hard disk, but it can be a database, a network stream etc. etc.).Hibernate is an Object to Relational mapping framework. It helps in persisting (or saving)and loading (a.k.a mapping) the state of objects in your application to a relationaldatabase management system. The reason it is so popular is because it is based onconfiguration files (also called as declarative programming). It generate all the boilerplateJDBC code for you, you just have to focus on the API's methods to persist the objectsfrom your java programs. Is Java fully object oriented? No...There is lot many reasons to say...Java supports OOP concepts partially...But not fully...The main aim of java is to avoid any complexity for programmers...So they avoided almost all the complexity from the OOP...Like multiple inheritance, friend functions, operator overloading... Etc...The main reason for keeping primitive types as non-objects is speed. For all the placeswhere primitive types dont make sense (such as containers etc.) you have the option to'wrap' then in their equivalent objects. JDK 1.5 even introduces the concept of autoboxingto make this transition even more programmers friendly. Why interfaces cannot contain static methods whereas theycan contain static variables? 1) Interface means, you can say that it is really incomplete....that is the reason, you can not create the instances....2) In second point, the all methods in the interface are abstract method... Simply you cansay, abstract methods are also the incomplete method.3) And when the methods are incomplete, the class is also incomplete, so even for theabstract class which is partially incomplete, you can't create the object. Because itrestricts the abstract methods to be called by object because they are abstract.4) And you know very well, that, static methods do not need any object to be created toget called of. So directly they can be called as <classname>.<methodname>.5) Now think, when the method is abstract (may be in abstract class or interface), and it isincomplete, and you invoke that method, then, how it can be used when it is

incomplete???? So you can't use static. (When you use static with a method, you can calldirectly without creating an object). So you can't do it.

encodeURL vs. encodeRedirectURL Both these methods revolve around the concept of URL rewriting. I dont know whether u r aware bout this. But basically it involves suffixing the URL with aHTTP_QUERY_STRING, which mostly is a session id used to keep track of a particular users context. URL re-writing is used get over the usage of cookies which are dependenton browser configuration, thus not reliable at all. Now Session is a comprehensive topicon its own, so wont discuss it now.But yes the difference between the methods is in their usage and not their functionality.Both perform the same task of re-writing a URL.us use encodeRedirectURL when u send a redirect header to the browser usingresponse.sendRedirect(string URL)for e.g. lets say on a particular condition u want to redirect to different pageif (name == null){response.sendRedirect(response(encodeRedirectURL("errorPage.jsp"))}on the other hand lets say u want to provide a link to shopping cart page to a user - printWriter.println("A HREF=" + response.encodeURL("shoppingCart.jasp") + ">")thus essentially they do same thing of re-writing the URL for non-cookie compliant browser.In short.....encodeURL is used for all URLs in a servlet's output.It helps session ids to be encoded with the URL.encodeRedirectURL () is used with res.sendRedirect only. It is also used for encodingsession ids with URL but only while redirecting. Transient variable can't be final or static The modifier transient can be applied to field members of a class to turn off serializationon these field members. Every field marked as transient will not be serialized. You usethe transient keyword to indicate to the Java virtual machine that the transient variable isnot part of the persistent state of an object.Java classes often hold some globally relevant value in a static class variable. The static member fields belong to class and not to an individual instance. The concept of serialization is concerned with the object's current state. Only data associated with aspecific instance of a class is serialized, therefore static member fields are ignored duringserialization (they are not serialized automatically), because they do not belong to theserialized instance, but to the class. To serialize data stored in a static variable one must provide class-specific serialization.Surprisingly, the java compiler does not complaint if you declare a static member field astransient. However, there is no point in declaring a static member field as transient, sincetransient means: "do not serialize and static fields would not be serialized anyway.On the other hand, an instance member field declared as final could also be transient, butif so, you would face a problem a little bit difficult to solve: As the field is transient, itsstate would not be serialized, it implies that, when you deserialize the object you wouldhave to initialize the field manually, however, as it is declared final, the compiler wouldcomplaint about it.For instance, maybe you do not want to serialize your class' logger, then you declared itthis way: private transient final Log log = LogFactory.getLog(EJBRefFactory.class); Now, when you deserialize the class your logger will be a null object, since it wastransient. Then you should initialize the logger manually after serialization or during theserialization process. But you can't, because logger is a final member as well. How JVM performs Thread Synchronization? JVM associates a lock with an object or a class to achieve multithreading. A lock is like atoken or privilege that only one thread can "possess" at any one time. When a threadwants to lock a particular object or class, it asks the JVM.JVM responds to thread with alock maybe very soon, maybe later, or never. When the thread no longer needs the lock, itreturns it to the JVM. If another thread has requested the same lock, the JVM passes thelock to that thread. If a thread has a lock, no other thread can access the locked data untilthe thread that owns the lock releases it.The JVM uses locks in conjunction with monitors. A monitor is basically a

guardian inthat it watches over a sequence of code, making sure only one thread at a time executesthe code. Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.When the thread leaves the block, it releases the lock on the associated object. A singlethread is allowed to lock the same object multiple times. JVM maintains a count of thenumber of times the object has been locked. An unlocked object has a count of zero When a thread acquires the lock for the first time, the count is incremented to one. Eachtime the thread acquires a lock on the same object, a count is incremented. Each time thethread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.In Java language terminology, the coordination of multiple threads that must accessshared data is called synchronization. The language provides two built-in ways tosynchronize access to data: with synchronized statements or synchronized methods.The JVM does not use any special opcodes to invoke or return from synchronizedmethods. When the JVM resolves the symbolic reference to a method, it determineswhether the method is synchronized. If it is, the JVM acquires a lock before invoking themethod. For an instance method, the JVM acquires the lock associated with the objectupon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized methodcompletes, whether it completes by returning or by throwing an exception, the lock isreleased.Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for thatobject, a count is incremented. Each time monitorexit is executed for the thread on theobject, the count is decremented. When the count reaches zero, the monitor is released. What is a class loader and what are its responsibilities? The Class loader is a subsystem of a JVM which is responsible, predominantly for loading classes and interfaces in the system. Apart from this, a class loader is responsiblefor the following activities:-Verification of imported types(classes and interfaces)-Allocating memory for class variables and initializing them to default values. Staticfields for a class are created and these are set to standard default values but they are notexplicitly initialized. The method tables are constructed for the class.-Resolving symbolic references from type to direct references The class loaders can be of two types: a bootstrap or primordial class loader and user defined class loaderEach JVMhas a bootstrap class loader which loads trusted classes , including classes from JavaAPI.JVM specs do not tell how to locate these classes and is left to implementationdesigners.A Java application with user defined class loader objects can customize class loading.These load untrustworthy classes and not an intrinsic part of JVM.They are written inJava, converted to class files and loaded into the JVM and installed like any other objects

Does Java support multi dimensional arrays? The Java programming language does not really support multi-dimensional arrays. Itdoes, however, support arrays of arrays. In Java, a two-dimensional array 'arr' is really anarray of one-dimensional arrays:int[][] arr = new int[4][6];The expression arr[i] selects the onedimensional array; the expression arr[i][j] selects theelement from that array.The built-in

multi-dimensional arrays suffer the same indignities that simple one-dimensional arrays do: Array indices in each dimension range from zero to, where lengthis the array length in the given dimension. There is no array assignment operator. Thenumber of dimensions and the size of each dimension is fixed once the array has beenallocated. What is Early Binding? The assignment of types to variables and expressions at compilation time is known as'Early Binding, it is also called 'static binding' and 'static typing'. What is Java class file's magic number? A Magic Number of a class file is a unique identifier for tools to quickly differentiateclass files from non class files. The first four bytes of each Java class file has the magicvalue as 0xCAFEBABE.And the answer to why this number, I do not actually know butthere may be very few sensible and acceptable options possible constructed from lettersA-F which can surely not be 'CAFEFACE' or 'FADECAFE'.... What is the difference between JVM and JRE? A Java Runtime Environment (JRE) is a prerequisite for running Java applications on anycomputer. A JRE contains a Java Virtual Machine (JVM), all standard, core java classesand runtime libraries. It does not contain any development tools such as compiler,debugger, etc. JDK (Java Development Kit) is a whole package required to JavaDevelopment which essentially contains JRE+JVM, and tools required to compile anddebug, execute Java applications. Does a class inherit constructors from its superclass? Is 'sizeof' a keyword? No, 'sizeof' is an operator used in C and C++ to determine the bytes of a data item, but itis not used in Java as all data types are standard sized in all machines as per specifications of the language.A JVM is free to store data any way it pleases internally, big or little endian, with anyamount of padding or overhead, though primitives must behave as if they had the officialsizes.In JDK 1.5+ you can use java.lang.instrument.Instrumentation. getObjectSize() toget the object size. What is the difference between process and threads? A thread is part of a process; a process may contain several different threads. Two threadsof the same process share a good deal of state and are not protected against one another,whereas two different processes share no state and are protected against one another. Twothreads of the same process have different values of the program counter; different stacks(local variables); and different registers. The program counter, stack pointer, and registersare therefore saved in the thread table. Two threads share open files and memoryallocation; therefore, file information and memory information (e.g. base/limit register or page table) is stored in the process table. Can an inner class be defined inside a method? Yes it can be defined inside a method and it can access data of theenclosing methods or a formal parameter if it is final. What is an anonymous class? It is a type of inner class with no name. Once defined an object can becreated of that type as a parameter all in one line. it cannot haveexplicitly declared constructor. The compiler automatically provides ananonymous constructor for such class.An anonymous class is never abstract. An anonymous class is always aninner class; it is never static. An anonymous class is alwaysimplicitly final. What modifiers may be used with an inner class that is a member of anouter class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract

Why are wait(), notify(), and notifyAll() in the Object class? Many new Java programmers ask this question when they're just starting out, and it's agood question. After all, these methods have something to do with threads, so why aren'tthey in the thread class?The answer is that Threads can use Objects to transmit messages from one thread toanother, and these methods allow that to happen. A Thread calls wait() to say "I amwaiting for a message to be sent to this object." Another thread can call notify() to say "Iam sending a message to that object." The Object is therefore a conduit through whichthreads communicate without explicitly referencing each other. If the methods were in theThread class, then two threads would need to have references to one another tocommunicate. Instead, all communicating threads just need to agree to use some specificshared resource. What is Composition and how it maps into a Java class A Composition is a tight Association and denotes "whole-part" relationship.So when anobject is destroyed then all its constituents are also destroyed, these 'parts' have nomeaning/sense in their lone existence from their 'whole'.The best example of Composition is a 'Human body' which is composed of two legs,twohands,two eyes,two ears and so on.During the lifetime of a human being,all organs makesense being part of whole,but once a human being is dead most of these parts are alsodead,unless some of his body parts are not medically reused. Now come to map composition to Java world, the best example is garbage collectionfeature of the language.While garbage collecting objects, whole has the responsibility of preventing all its parts being garbage collected by holding some references to them.It is the responsibility of whole to protect references to its parts not being exposed tooutside world.The only way to have true composition in Java is to never let references tointernal objects escape their parent's scope.An example of Inner class as shown in the following code snippet may give you an ideahow to implement Composition in Java. public class Human{ public Human(){Brain brain = new Brain();} private class Brain{........}} What is a Daemon thread? A ''daemon'' thread is one that is supposed to provide a general service in the backgroundas long as the program is running, but is not part of the essence of the program. Thus,when all of the nondaemon threads complete the program is terminated. Conversely, if there are any nondaemon threads still running the program doesn' t terminate. What is the difference between Serializable and Externalizable interface? java.io.Serializable interface is an empty interface with no methods and attributes.It isimplemented by objects which are needed to be serialized and serves only to identify thesemantics of being serializable.When process of serializing an object is to be controlled then Externalizable interface isused.The Externizable interface extends Serializable and adds twomethods,writeExternal() and readExternal() which are automatically called duringserialization and deserialization.Classes that require special handling during the serialization and deserialization processmust implement special methods with these exact signatures: private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException,ClassNotFoundException; What is memory leak? A memory leak occurs when all references (pointers) to a piece of allocated memory areoverwritten, cleared, or pass out of scope. The result is that the program simply "forgets"about that particular piece of memory.Unfortunately , the operating environment

(usuallyan OS) is not aware of the application's amnesia. That memory is treated by the outsideworld as though it still belongs to the application. The memory is therefore completelyunavailable;it has "leaked". (In the worst case, the memory can become unavailable to allapplications in the system, even if the application that created the leak is terminated. Thememory can only be reclaimed by rebooting the system.

Explain StreamTokenizer? The StreamTokenizer class takes an input stream and parses it into "tokens", allowing thetokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers,numbers, quoted strings, and various comment styles.Each byte read from the input stream is regarded as a character in the range '\u0000'through '\u00FF'. The character value is used to look up five possible attributes of thecharacter: white space, alphabetic, numeric, string quote, and comment character. Eachcharacter can have zero or more of these attributes.In addition, an instance has four flags. These flags indicate:Whether line terminators are to be returned as tokens or treated as white space thatmerely separates tokens.Whether C-style comments are to be recognized and skipped.Whether C++-style comments are to be recognized and skipped.Whether the characters of identifiers are converted to lowercase.A typical application first constructs an instance of this class, sets up the syntax tables,and then repeatedly loops calling the nextToken method in each iteration of the loop untilit returns the value TT_EOF. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. Can an anonymous class implement an interface and extend a class at thesame time? No, an anonymous class can either implement an interface or extend a class at a particular time but not both at the same time. Can protected or friendly features be accessed from different packages? No,when features are friendly or protected they can be accessed from all the classes inthat package but not from classes in another package. How many ways can one write an infinite loop ? Personally I would recommend following ways to implement infinite loop in Java buttheir can be other ways like calling a method recursively , though I never tested that.- while (true)for (;;) { }

What is Exception ? An exception is an abnormal behavior existing during a normal execution of a program.For example: When writing to a file if there does not exist required file then anappropriate exception will be thrown by java code. What is a user-defined exception? For every project you implement you need to have a project dependent exception class sothat objects of this type can be thrown so in order to cater this kind of requirement theneed for user defined exception class is realized.for example:class MyException extends Exception{ public MyException(){}; public MyException(String msg){super(msg);}} What is the difference between Java class and bean?

What differentiates Beans from typical Java classes is introspection. The tools thatrecognize predefined patterns in method signatures and class definitions can "look inside"a Bean to determine its properties and behavior. A Bean's state can be manipulated at thetime it is being assembled as a part within a larger application. The application assemblyis referred to as design time in contrast to run time. In order for this scheme to work,method signatures within Beans must follow a certain pattern in order for introspectiontools to recognize how Beans can be manipulated, both at design time, and run time. How do you set Java library path programatically? Java library path can be set by choosing an option as:--Djava.library.path=your_pathWhile setting the java.library.path property to "." instructs the Java virtualmachine to search for native libraries in the current directory.And you execute your code as

java -Djava.library.path=. HelloWorld The "-D" command-line option sets a Java platform system property. But thesevalues are 'read only' like many of the system properties, the value in java.library.pathis just FYI and changing it doesn't actually change the behaviour of the JVM.If you want to load a library from a specific location, you can use System.load() insteadwith the full path to the library. What is a thread? A thread is most fundamental unit of a computer program which is under executionindependent of other parts.A thread and a task are similar and often confused.Anoperating system executes a program by allocating it certain resources like memory,CPUcycles and when there are many a programs doing several things corresponding to severalusers requests.In such a scenario each program is viewed as a 'task' by OS for which itidentifies an allocate resources. An OS treats each application e.g. WordProcessor,spreadsheet,email client etc as a separate task , if a certain program initiatessome parallel activity e.g. doing some IO operations,printing then a 'thread' will becreated fro doing this job

Potrebbero piacerti anche