Skip to main content

Posts

Showing posts from July, 2010

What is the difference(or relation) between the Comparator and the Comparable interfaces?

Classes that implement these two interfaces play different roles in the sorting process. A class that implements the Comparable interface, i.e., a Comparable type, is the type that is sorted, while a class that implements the Comparator interface, i.e., a Comparator, is used to compare other types. A Comparable object can compare itself to another Object using its compareTo(Object other) method. The object itself defines how the comparison is done. Interface Comparable has a method: public int compareTo(T o) A Comparator object is used to compare two objects of the same type using the compare(Object other1, Object other2) method. When using a Comparator, the objects being compared don't need to define the rule of comparison. Interface Comparator has a method: public int compare(T o1, T o2)

Why the fully qualified name of a static final variable is not allowed in static initialization block?

Let's start with the following example: public class Program { static final int var; static { Program.var = 8; // Compilation error } public static void main(String[] args) { System.out.println(Program.var); } } And, public class Program { static final int var; static { var = 8; //OK } public static void main(String[] args) { System.out.println(Program.var); } } Why the fully qualified name of the static final variable is not allowed in static initialization block?

Does Java support multidimensional arrays?

The Java programming language does not really support multi-dimensional arrays. It does, however, support arrays of arrays . In Java, a two-dimensional array x is really an array of one-dimensional arrays: String[][] x = new String[5][5]; The expression x[i] selects the i th one-dimensional array; the expression x[i][j] selects the j th element from that array. You may figure out how three-dimensional array y is. It is an array of two-dimensional arrays. String[][][] y = new String[5][5][5]; The expression y[i] selects the i th two-dimensional array; the expression y[i][j] selects the j th one-dimensional array; the expression y[i][j][k] selects the k th element from the y[i][j] selected one-dimensional array.

Why am I getting unreported exception when the super class default constructor has a 'throws' clause?

class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public static void main(String[] args) throws Exception { Sub s = new Sub(); } }   Compile it and you have compile-time error:   Sub.java:6: unreported exception java.lang.Exception in default constructor    public class Sub extends Super { 1 error Here is a Sun's Bug Report which can answer this question: When a superclass constructor has a non-empty throws clause, subclasses must define an explicit constructor with an appropriate throws clause, as a default constructor has no throws clause. (This is stated in JLS 2e 8.8.7, ruling out the xxxxx alternative of copying the superclass constructor's throws clause. Currently, the compiler generates a default constructor with an empty throws clause, and then generates an error message. Unfortunately, the offending call, the implicit call to the

What is 'instanceof'?

The instanceof operator is used to check whether the run-time type of an object is compatible with a given type ( 15.20.2 Type Comparison Operator instanceof ):   expression instanceof type The type of an expression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The type mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs. An instanceof expression evaluates to true if both of the following conditions are met: expression is not null . expression can be cast to type . That is, a cast expression of the form (type)(expression) will complete without raising a ClassCastException . It is a compile-time error if the type mentioned after the instanceof operator does not denote a reifiable type . If a cast of the expression to the type would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compi

Why always override hashcode() if overriding equals()?

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object . If you override the equals() , you MUST also override hashCode() . Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections. Here is the contract, copied from the java.lang.Object specialization: public int hashCode() Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable . The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same intege

What is runtime polymorphism in Java?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming. The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time. Let's take a look at the following example:   class Animal { void whoAmI() { System.out.println("I am a generic Animal."); } } class Dog extends Animal { void whoAmI() { System.out.println("I am a Dog."); } } class Cow extends Animal { void whoAmI() { System.out.println("I am a Cow."); } }

Can a Java application have memory leak?

Yes, there could be memory leak in Java applications. Wait a minute, doesn't Java virtual machine have a garbage collector that will collect and free all unreferenced memory automatically? Let's find out in general what memory leaks are, and how they occur in applications. If an application fails to return the not-in-use memory back to the heap, the "lost" memory is called memory leak. Memory leaks occur when the application doesn't free the memory allocated, usually are the objects no longer in use, but the object references are lost. If an object is no longer accessible, there is no way to free its memory. Each time such a leak is re-created, additional memory is used and not freed. Eventually, the process that runs the application will run out of memory and crash. It's true that for other programming languages, such as C/C++, there is not such a thing called garbage collector. The programmer is responsible for freeing the memory when the

Are parameters passed by reference or passed by value in method invocation in Java?

In programming, there are two ways to pass arguments to a method, pass-by-value and pass-by-reference : When you have a pass-by-value parameter, a copy of the argument is stored into the memory location allocated for the formal parameter. In this case, any changes made to the formal parameter inside the method will not affect the value of the argument back in the calling method. When a parameter is pass-by-reference, the memory address of the argument is passed to the method, making the formal parameter an alias for the argument. This means that changes made to the formal parameter inside the method will be reflected in the value of the argument when control is returned to the calling function. Technically, all parameters in Java are pass-by-value. All primitives are pass-by-value, period. When a primitive value is passed into a method, a copy of the primitive is made. The copy is what is actually manipulated in the method. So, the value of the copy can be changed

What are the forward reference rules?

Using an instance variable before its declaration is called a forward reference. If an instance variable tries to forward reference another instance variable during initialization, the result in a compile-time error. Java Language Specification designs the following restrictions to catch, at compile time, circular or otherwise malformed initializations. 8.3.2.3 Restrictions on the use of Fields during Initialization in Java Language Specification The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static ) field of a class or interface C and all of the following conditions hold: The usage occurs in an instance (respectively static ) variable initializer of C or in an instance (respectively static ) initializer of C . The usage is not on the left hand side of an assignment. The usage is via a simple name. C is the innermost class or interface enclosing

What are the differences between the equality operator and the equals method?

The Java language offers the programmer more than one way to check for equality -- but all those ways are not created equal. The equality operator == is a fundamental operator in the Java language. The result type of the expression is always boolean . According to 15.21 Equality Operators in Java Language Specification 3rd Edition : For numeric types, the value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false . For comparing boolean types, the result of == is true if the operands (after any required unboxing conversion) are both true or both false ; otherwise, the result is false . For comparing reference types, at run time, the result of == is true if the operand values are both null or both refer to the same object or array ; otherwise, the result is false .

What are the valid signatures of the main() function of a class?

The Java literature frequently refers to the Signature of a method. A method signature is a collection of information about the method, and that includes the name , type (e.g., static or non-static), visibility (e.g., public, private, etc.), arguments (e.g., formal parameters), and return type . The main method is the entry point of the JVM when the class in launched. The JVM launchs the Java program by invoking the main method of the class identified in the command to start the program. The method main must be declared public , static , and void . It must accept a single argument that is an array of strings. The main method can be declared as either:

Does Java have pointers?

Java does not have pointers, no way. Java does have references. A reference is an abstract identifier for an object. It is not a pointer. A reference tags a particular object with a name in the Java virtual machine so that the programmer may refer to it. How exactly the virtual machine implements references at the level of machine code is VM-dependent and completely hidden from the programmer in any case. Most VMs including Sun’s use handles, not pointers. A handle is a pointer to a pointer. At the level of machine code in the CPU a reference is an address in memory where the address of the object is stored. This way the objects can be moved around in memory and only the master pointer needs to be updated rather than all references to the object. This is completely hidden from the Java programmer, though. Only the implementer of the virtual machine needs to worry about it. Indeed, this is not the only way references can be implemented. Microsoft’s VM actually does use po

Java Threads Interview Questions

What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by the following ways: 1. Invoking its sleep() method, 2. By blocking on I/O 3. By unsuccessfully attempting to acquire an object's lock 4. By invoking an object's wait() method. 5. It can also enter the waiting state by invoking its (deprecated) suspend() method. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method, it returns to the waiting state from a running state. How to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state? OrExtending Thread class or implementing Runnable Interface. Which is better? You have two ways to do so. First, making your class "extends" Thread class. The other way is making you

What is variable hiding and shadowing?

In Java, there are three kinds of variables: local variables, instance variables, and class variables. Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed. A Local Variable Shadows An Instance Variable Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block. In the following example, there is a instance variable named "a", and inside the method setA() there is a local variable "a": class Program {   int  a;   int  b;

What is the advantage of using an Iterator compared to the get(index) method?

You can navigate or access a List by using the get(index) method or an Iterator. Sometimes the get(index) method is your only option, and sometimes it's slightly faster than an Iterator. Other times, however, it can be much, much slower than an Iterator. For example, a LinkedList is a classic example. This class has a get(index) method but it is very slow. Well, it's not that bad if the list is short, or if you're looking for an item that is close to the beginning or end. But if you need to access the List frequently, you will see a big difference. Let's take a look at the following example: public class TestClass { public static void main(String[] args) { int len = 100000; LinkedList linkedLst = new LinkedList(); ArrayList arrayLst = new ArrayList(); for (int m =0; m!= len; m++) { int x = (int)Math.random(); linkedLst.add(x); arrayLst.add(x); }

Java Interview Questions

What is the difference between calling run() method and call run() method through start() method??? Couldn't we call method run() ourselves, without doing double call: first we call start() method which calls run() method? What is a meaning to do things such complicate? There is some very small but important difference between using start() and run() methods. Look at two examples below: Example one: Code: Thread one = new Thread(); Thread two = new Thread(); one.run(); two.run(); Example two: Code: Thread one = new Thread(); Thread two = new Thread(); one.start(); two.start(); The result of running examples will be different. In Example one the threads will run sequentially: first, thread number one runs, when it exits the thread number two starts. In Example two both threads start and run simultaneously. Conclusion: the start() method call run() method asynchronously (does not wait for any result, just fire up an action), while we run run() method synchronous

WebLogic Administration Concepts

Domain • A domain is an interrelated set of WebLogic Server resources that are managed as a unit. • A domain contains the application components deployed in the domain, and the resources and services required by those application components and the server instances in the domain • A domain can include multiple clusters. Admin server • In each domain, only one WebLogic Server instance acts as the Administration Server. • This server instance which configures, manages, and monitors all other server instances and resources in the domain. • Each Administration Server manages one domain only. If a domain contains multiple clusters, each cluster in the domain has the same Administration Server. Managed server It is also a weblogic server instance. A domain includes one or more WebLogic Server instances, which can be clustered, non-clustered, or a combination of clustered and non-clustered instances. Cluster Cluster can run

StringBuilder vs StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands (buffer size) as needed. Related classes: String, CharSequence. StringBuilder was added in Java 5.0. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster. No imports are necessary because these are both in the java.lang package. StringBuffer and StringBuilder methods and constuctors Assume the following code: StringBuffer sb = new StringBuffer(); StringBuffer sb2; int i, offset, len; char c; String s; char chararr[];

Generating an XML Document with JAXB

An XML Schema represents the structure of an XML document in XML syntax. J2EE developers may require an XML document to conform to an XML Schema. The Java Architecture for XML Binding (JAXB) provides a binding compiler, xjc , to generate Java classes from an XML Schema. The Java classes generated with the JAXB xjc utility represent the different elements and complexType s in an XML Schema. (A complexType provides for constraining an element by specifying the attributes and elements in an element.) An XML document that conforms to the XML Schema may be constructed from the Java classes. In this tutorial, JAXB is used to generate Java classes from an XML Schema. An example XML document shall be created from the Java classes. This article is structured into the following sections. Preliminary Setup Overview Generating Java Classes from XML Schema Creating an XML Document from Java Classes Preliminary Setup To generate Java classes from an XML Schema with the JAXB , the JAXB

Basic UNIX commands

Note: not all of these are actually part of UNIX itself, and you may not find them on all UNIX machines. But they can all be used on turing in essentially the same way, by typing the command and hitting return. Note that some of these commands are different on non-Solaris machines - see SunOS differences . If you've made a typo, the easiest thing to do is hit CTRL-u to cancel the whole line. But you can also edit the command line (see the guide to More UNIX ). UNIX is case-sensitive. Files ls --- lists your files ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list files by size, by date, recursively etc. more filename --- shows the first part of a f

Web Services Tutorial

Introduction to Web Services Web Services became a hot new technology in 2002. Microsoft first coined the term "Web Services" in June of 2000 when it introduced Web Services as a major component of its .NET technology aimed at revolutionizing distributed computing. I see it as a new vision for using the Internet in the development, engineering and use of software. Web services standards are emerging. Several technologies combine to make up "Web Services". The main standard is Extensible Markup Language, XML. XML was developed by the World Wide Web Consortium ( W3.org ) It is a meta-language for describing data and creating additional markup languages. XML tags form individual pieces of data. An XML document is text-based and is made up of XML tags. XML is portable and has been rapidly adopted throughout the industry, thus making it the preferred choice for enabling cross-platform data communication in Web Services. XML provided the basis for many core W

DB2 Error: com.ibm.db2.jcc.b.SqlException: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-551;42501;SPILTODB2|SELECT|VAJ.CODES, DRIVER=3.53.95

Problem : DB2 Error: com.ibm.db2.jcc.b.SqlException: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-551;42501;SPILTODB2|SELECT|VAJ.CODES, DRIVER=3.53.95 Solution : The UserID which is trying access the table does not have proper previleges / credentials to access the table. So assign correct previleges to the UserId and try, it will work out.

Words of Web Technology....

*       A *       ACCESS LOG - An access log is a list of all the requests for individual files that people have requested from a Web site. These files will include the HTML files and their imbedded graphic images and any other associated files that get transmitted. The access log (sometimes referred to as the "raw data") can be analyzed and summarized by another program. *       ACTIVE X - A programming language designed for program execution in a Microsoft Internet Explorer browser *       ACROBAT - A program from Adobe that lets you capture a document and then view it in its original format and appearance. *       AFFILIATE -Programs that generate leads and sales from other websites, paying commissions for those sites that host their products. *       ADO - ActiveX Data Objects (ADO) is an application program interface from Microsoft that lets a programmer writing Windows applications get access to a relational or non-relational database from both Microsoft and other

Servlets Interview Questions

1) What is servlet? Ans: Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. 2) What are the classes and interfaces for servlets? Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http. Javax.servlet contains: Interfaces Classes Servlet Generic Servlet ServletRequest ServletInputStream ServletResponse ServletOutputStream ServletConfig ServletException ServletContext UnavailableException SingleThreadModel Javax.servlet.http contains: Interfaces Classes HttpServletRequest Cookie HttpServletResponse HttpServlet HttpSession HttpSessionBindingEvent HttpSessionContext HttpUtils HttpSeesionBindingListener 3) What is the difference between an applet and a servlet? Ans: a) Servlets are to servers what applets are to browsers. b)

Why not compile Java for Windows?

Since most Java applets run on PC platform, why not offer a compiled version of Java directly run in Windows without JVM? Users can still use standard Java via JVM, it's just a performance enhancement. That would negate the entire purpose of the java development program. Notice how you asked the question, "...since most...!" That should indicate to you that not all OS's are windows platforms and the purpose of java is to provide a language that can be interpreted(or used) by all OS's. Just because a person can program doesn't mean they will be using a computer that will be of the Intel based family of mpu's. By doing what you suggest would restrict many programmers work to that platform, not to mention the compatibility of browsers and OS's to decypher the programmers intent.  We can still use standard Java through JVM. Because some Java programs are just like windows applications without involving multiple platforms, a compiled version for windows

How to make Java objects eligible for garbage collection?

An object becomes eligible for garbage collection when it becomes unreachable by any code. Two way can make this happened: Explicitly set the reference variable that refers to the object to  null . Reassign the reference variable that points to the object to refer to other object. For example, class Program { public static void main(String[] args) { X x1 = new X("1"); X x2 = new X("2"); x1 = null; // X("1") object is eligible for collection after this x2 = new Y(); // X("2") object is eligible for collection after this } } Did you like the above article? Please share with your friends..

WebSphere MQ Series Archives

To know what is MQ, Fundamentals of MQ and what is the basic concept of Message Oriented Middleware click below link  Fundamentals of MQ To know how to use MQ with Java Application Programming, check below link. WebSphere MQ Using Java Version 6.0 Finally if you have any questions regarding MQ and Java programming check below links. MQSeries.Net MQSeries.Net Forum

WebSphere MQ Series Tutorial

MQ Series : - It is an IBM web sphere product which is evolved in 1990’s. MQ series does transportation from one point to other. It is an EAI tool (Middle ware) VERSIONS :-5.0, 5.1, 5.3, 6.0, 7.0(new version). The currently using version is 6.2 Note : - MQ series supports more than 35+ operating systems. It is platform Independent. For every OS we have different MQ series software’s. But the functionality of MQ series Default path for installing MQ series is:- C: programfiles\IBM\Eclipse\SDK30 C: programfiles\IBM\WebsphereMQ After installation it will create a group and user. Some middleware technologies are Tibco, SAP XI. MQ series deals with two things, they are OBJECTS, SERVICES. In OBJECTS we have QUEUES CHANNELS PROCESS AUTHENTICATION QUERY MANAGER. In SERVICES we have LISTENERS. Objects : - objects are used to handle the transactions with the help of services. QUEUE MANAGER maint

Starting java programs as a windows service (or a unix deamon)

Introduction you can easily start your java program as a part of the OS loading sequence by using one of many available tools today and i can see that Java Service Wrapper is the easiest way to do so... the best thing about this tool is that you configure a property file for your windows service and use the same file for installing unix deamon.... Downloading and Installing there are three packages of Java Service Wrapper: professional, standard and community the last is free under GPLv2 extract the file to a folder(this folder will be referenced as ${wrapper_home} ) Your Side Develop, compile and jar your java desktop application that for sure got a class with the main method... Wrapper Side the wrapper comes with an example service, all you have to do is the following edit the file ${wrapper_home}\conf\wrapper.conf (will be described in details shortly) use the batch files located at ${wrapper_home}\bin to install, start, stop, suspend, resume and uninstall the serv

Why does this for/while loop instantiation fail to compile?

We get a compiler error when we declare a variable in a for/while loop without braces. For example, public class RedLoopDemo {     public static void main(String[] args) {           for (int x=0; x!=10; x++)             String str = "LOOP";  //Compiler Error     }   } But it is fine when you add braces, public class AbcdLoopDemo {     public static void main(String[] args) {           for (int x=0; x!=10; x++) {             String str = "LOOP";         }     }    }

How to read input from console (keyboard) in Java?

There are few ways to read input string from  your console/keyboard. The following smaple code shows how to read a string from the console/keyboard by using Java. public class ConsoleReadingDemo {     public static void main(String[] args) {         // ====         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));         System.out.print("Please enter user name : ");         String username = null;         try {             username = reader.readLine();         } catch (IOException e) {             e.printStackTrace();         }         System.out.println("You entered : " + username);         // ===== In Java 5, Java.util,Scanner is used for this purpose.         Scanner in = new Scanner(System.in);         System.out.print("Please enter user name : ");         username = in.nextLine();               System.out.println("You entered : " + username);           // ====== Java 6         Co