Tuesday, February 11, 2014

Thread interview questions

Thread Concepts



Q1) What is a Thread?
Ans) In Java, "thread" means two different things:
  • An instance of class java.lang.Thread.
  • A thread of execution.x
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread. Even if you don't create any new threads in your program, threads are back there running. 
The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), you'd see that main() is the first method on the stack— the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack that's separate from the main() call stack.
Q2) What is difference between thread and process?
Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that  created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.
Q3) What are the advantages or usage of threads?
Ans)
 Threads support concurrent operations. For example, • Multiple requests by a client on a server can be handled as an individual client thread.
 • Long computations or high-latency disk and network operations can be handled in the background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.• In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events.

Threads provide a high degree of control.• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A "watchdog" thread can be activated that will "kill" the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.• A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking ("time sharing").
• On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.
Q4)What are the two ways of creating thread?
Ans) There are two ways to create a new thread.
1)Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}
}
2)Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}
Q5) What are the different states of a thread's lifecycle?
Ans) The different states of threads are as follows:
1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
 4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5)      Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.
Q6) What is use of synchronized keyword?
Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
            synchronized (this){             // synchronized keyword on block of  code
            }
}
Q7) What is the difference when the synchronized keyword is applied to a static method or to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class donĂ¢€™t interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but canĂ¢€™t access the synch non static method.
Q8) What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.
Q9) What is the difference between yield() and sleep()?
Ans)  yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
         sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
Q10) What is the difference between wait() and sleep()?
Ans)
1) wait() is a method of Object class. sleep() is a method of Object class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.
Q11) What is difference between notify() and notfiyAll()?
Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.
Q12) What happens if a start method is not invoked and the run method is directly invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.
Q13) What happens when start() is called?
Ans) A new thread of execution with a new call stack starts. The state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.
Q14) If code running is a thread creates a new thread what will be the initial priority of the newly created thread?
Ans) When a code running in a thread creates a new thread object , the priority of the new thread is set equal to the priority of the thread which has created it.
Q15) When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.
Q16) What are the daemon threads?
Ans) Daemon thread are service provider threads run in the background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.
Q17) What all constructors are present in the Thread class?
Ans) Thread()
 Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Q18) Can the variables or classes be Synchronized?
Ans) No. Only methods can be synchronized.
Q19) How many locks does an object have?
Ans) Each object has only one lock.
Q20) Can a class have both Synchronized and non-synchronized methods?
Ans) Yes a class can have both synchronized and non-synchronized methods.

Monday, February 10, 2014

JAVA Critics

Primitives vs. objects / Autoboxing

Java designers decided not to implement certain features present in other languages (including multiple inheritance, operator overloading, and tuples).

When generics were added to Java 5.0, there was already a large framework of classes (many of which were already deprecated), so generics were chosen to be implemented using erasure to allow backwards compatibility and preservation of these existing classes. This limited the features that could be provided by this addition as compared to other languages.

Java's primitive types are not objects. Primitive types hold their values in the stack rather than being references to values. This was done for performance reasons. Because of this, Java is not considered to be a pure object-oriented programming language and this makes reflection more complicated. However, Java 5.0 supports automatic conversion (autoboxing) of primitive data types to corresponding object form wherever required, during compilation. When autounboxing, a null pointer exception may be thrown. Since this operation occurs implicitly (without a cast or method call), this unchecked exception may not be obvious by inspection of the line of code.

Non-Virtual methods

Java provides no way to make methods non-virtual (although they can be "sealed" by using the final modifier to disallow overriding). This means that there is no way to let derived classes define a new, unrelated method with the same name. This can be a problem when a base class is designed by a different person, and a new version introduces a method with the same name and signature as some method already present in the derived class. This means that the method in the derived class will implicitly override the method in the base class, even though that was not the intent of the designers of either class. To partially accommodate for these versioning problems, Java 5.0 introduced the @Override annotation, but to preserve backwards compatibility it could not be made compulsory by default.

Single paradigm

Java is predominantly a single-paradigm language. The addition of static imports in Java 5.0 accommodates the procedural paradigm better than earlier versions of Java.

Exception handling

Java embraced the concept of exception specifications from C++ where they were optional, but made throws clauses mandatory for any checked exception. While this can be a benefit for small systems, there is not universal agreement that using checked exceptions is a benefit for larger systems. In particular, "higher level" code is often not interested in errors thrown by "lower level" code (eg: NamingException). The coder of the naming classes must make a choice: either force higher level code to deal with naming exceptions as checked exceptions, or allow them to "bubble up" through his own low-level code without compile-time checks.

Closure

Finally, while anonymous inner classes provide a basic form of closures, they are not complete and require referenced variables to either be class fields or declared "final". The rationale behind this is that it allows JVM implementors to choose a stack model for variable lifetimes, so that a variable scope is removed when exited, thus preventing real closures. In addition, when using - for instance - "Runnable" as a closure, one has to declare the "run" method and put the code in that: you cannot simply put some code in braces and pass it around.

Floating point arithmetic

While Java's floating point arithmetic is largely based on IEEE 754 (Standard for Binary Floating-Point Arithmetic), certain features are not supported even when using the "strictfp" modifier, such as Exception Flags and Directed Roundings — capabilities mandated by IEEE Standard 754. Many so-called "Java gotchas" are not problems with Java per se, but problems that are inevitable whenever using floating point arithmetic.

Look and feel

The look and feel of GUI applications written in Java using the Swing platform is often different from native applications. While programmers can choose to use the AWT toolkit that displays native widgets (and thus look like the operating platform), the AWT toolkit is unable to meet advanced GUI programming needs by wrapping around advanced widgets and not sacrificing portability across the various supported platforms, each of which have vastly different APIs especially for higher-level widgets.

The Swing toolkit--written completely in Java--both creates the problem of having a different look and feel from native applications, and avoids the problem of being limited by native toolkit capabilities because it reimplements widgets using only the most basic drawing mechanisms that are guaranteed available on all platforms. Unfortunately, the default installations of the JRE (as of August 2006) do not use the system's "native" look and feel, instead defaulting to the built-in Metal Look and Feel. If the programmer doesn't take care to set the native look and feel, users will have applications whose appearance is vastly different from that of their native applications. Apple Computer's own optimized version of the Java Runtime, which is included within the Mac OS X distribution, by default does set the default and implements its "Aqua" look-and-feel, giving Swing applications on the Macintosh a similar appearance to native software. Even in this environment, the programmer must still do some extra work to ensure that that application looks like an Aqua one (for example, they must set system properties to ensure the menubar is rendered in the OS X menubar and not in the application window as it would be on other platforms).

Performance

It is impossible to make any generalization about the performance of Java programs, because runtime performance is affected much more by the quality of the compiler or JVM than by any intrinsic properties of the language itself. Java bytecode can either be interpreted at run time by a virtual machine, or it can be compiled at load time or runtime into machine code which runs directly on the computer's hardware. Interpretation is slower than native execution, and compilation at load time or runtime has an initial performance penalty for the compilation.

Lack of language features

There are a few language requirements which incur an unavoidable time penalty, although these features are not unique to Java. Among these are array bounds checking, run-time type checking, and virtual function indirection (although each of these can in some situations be avoided by an optimizing compiler). Also the lack of features can affect performance. For example, Java does not have arrays of structures or a true multi-dimensional array, but only an array of references to objects or further arrays. Nor does Java allow returning more than one value from a function without using an object. The net result is that Java code makes more heap allocations than well-written code in some other languages.

Garbage collection

The use of a garbage collector to automatically delete objects adds overhead compared to manual deallocation and can have a positive or negative impact, or no discernible impact at all, on performance depending upon the garbage collector implementation and the characteristics of the application's use of objects. With the modern generational garbage collectors used in many JVMs, many applications actually experience greater performance because of faster allocation and deallocation algorithms.

Byte code vs. native compilation

Relative performance of JIT compilers as compared to native compilers can be quite close, and is often a subject of debate. The JIT compilation stage may be time consuming, which is inconvenient for applications that are short-lived and/or contain large amounts of code. Once compiled to native code, however, the performance of the program can be comparable to that achieved by a native compiler, even on numerical tasks. Although Java does not support manual inlining of method calls, many JIT compilers perform this optimization at load time and can exploit information from the runtime environment to guide more effective transformations, such as profile-directed inlining. Dynamic recompilation, as provided by Sun's HotSpot JVM, can exceed the performance of the static compilation available in most other languages by exploiting information that is only available at runtime.

Hardware interfacing

Because Java was designed with an emphasis on security and portability, it does not support direct access to the machine architecture and address space. This means working directly with a specific piece of hardware such as a scanner, digital camera, audio recorder, video capture, or virtually any hardware that requires direct memory space control (typically those pieces or hardware installed with drivers), cannot easily be accomplished with Java. An illustration of this issue is seen in version 1.0 of Java as it was not possible to access a printer because the interface code to the various printer drivers was not included in this first JVM.

Interfacing with native code




Java programming language was intended to serve as a novel way to manage software complexity. Many consider Java technology to deliver reasonably well on this promise. However, Java is not without flaws, and it does not universally accommodate all programming styles, environments, or requirements.

Class path

Running a Java program requires all third party supporting libraries to be in the class path. This can be an obstacle to portability, because its syntax is platform-specific: Windows-based systems use backslashes to mark subdirectories and semicolons to separate entries, whereas all other platforms use forward slashes to mark subdirectories and colons to separate entries.
It is also necessary for each .jar or .zip archive required to be explicitly named in the class path. Java provides a way around this by allowing directories listed in the class path to end in an asterisk (*), which will be expanded to the names of all files ending in .jar or .JAR within the directory. However, such an entry does not match .zip or .class files within that directory.

License

Sun Java's proprietary nature gave it a controversial position in the free software community. Because Sun's implementation of Java was not free software, it could not be included in projects that require a free software or GPL-compatible license, such as Debian main, the $100 laptop, and Fedora Core. Sun announced in JavaOne 2006 that Java will become open source software. The statement was issued by Sun Software Executive Vice President Rich Green: "It's not a question of whether, it's a question of how, and so we'll go do this."

In July 2006, Sun's CTO Robert Brewin commented that Java will be partially open source by June 2007 but the entire platform will take more time to be fully open source. On November 13, 2006, Sun announced that its standard edition Java runtime environment will be released under the GPL by March of 2007. Its source code will be available under the GPL. According to Richard Stallman, this will mean an end to the Java trap. Mark Shuttleworth called the initial press announcement "a real milestone for the free software community."

Resource management


While Java does manage memory, it does not manage all resources, such as JDBC database connections; these must be released just as memory would need to be in C++.

The garbage collector controls when objects are deleted from memory. Java does not allow programmers to guarantee when garbage collection happens (even with System.gc()), they cannot hold off garbage collection, and they cannot delete one particular object. While this makes programming much simpler and reduces memory leaks, it lacks the flexibility that can, in some cases, result in a more efficient handling of memory. Lower-level languages such as C or assembly language provide this flexibility.

Memory management

Java takes care of memory management. This was done as it makes it harder (but not impossible) for the programmer to create problems such as memory leaks. Java always allocates objects on the heap (unless optimized to the stack or registers by the JIT compiler) and local variables on the stack or in registers. This makes Java less flexible than C++, which allows programmers to choose where objects are allocated.
While many programs, such as those written in C++, tend to fall prey to memory leaks, this is not the whole story. Other resource leaks such as file handles, database and network connections are still likely, especially when exceptions are thrown. However, where C++ has the RAII idiom to address both cases, Java programmers need to remember to release resources in finally clauses and must have a good understanding of which resources Java will release and which they must release.

Inconsistent JVM implementations

Java is a bytecode language that runs on top of the JVM; ultimately the compatibility of the language and the ability to have it run across different platforms is dependent on the stability and version of the JVM. While Java is touted as running on a large variety of systems, the most up to date JVM (and JRE) are only those actively updated for Windows, Linux and Solaris. HP (such as Java for HP-UX) and IBM (for MVS, AIX, OS/400) provide their own implementations for their family of platforms but do not always mirror the latest Sun releases. Other JVM implementations usually follow, but sometimes lag in months or years with the more common implementations and therefore introduce compatibility issues.

SCJP Part 2

The Java programming language has included five simple arithmetic operators like + (addition), - (subtraction), * (multiplication), / (division)




1. Unary operators

1.1 Increment and Decrement operators ++ --

We have postfix and prefix notation. In post-fix notation value of the variable/expression is modified after the value is taken for the execution of statement. In prefix notation, value of the variable/expression is modified before the value is taken for the execution of statement.

x = 5; y = 0; y = x++; Result will be x = 6, y = 5

x = 5; y = 0; y = ++x; Result will be x = 6, y = 6

Implicit narrowing conversion is done, when applied to byte, short or char.

1.2 Unary minus and unary plus + -

+ has no effect than to stress positivity.

- negates an expression's value. (2's complement for integral expressions)

1.3 Negation !

Inverts the value of a boolean expression.

1.4 Complement ~

Inverts the bit pattern of an integral expression. (1's complement - 0s to 1s and 1s to 0s)

Cannot be applied to non-integral types.

1.5 Cast ()

Persuades compiler to allow certain assignments. Extensive checking is done at compile and runtime to ensure type-safety.

2. Arithmetic operators - *, /, %, +, -

· Can be applied to all numeric types.

· Can be applied to only the numeric types, except '+' - it can be applied to Strings as well.

· All arithmetic operations are done at least with 'int'. (If types are smaller, promotion happens. Result will be of a type at least as wide as the wide type of operands)

· Accuracy is lost silently when arithmetic overflow/error occurs. Result is a nonsense value.

· Integer division by zero throws an exception.

· % - reduce the magnitude of LHS by the magnitude of RHS. (continuous subtraction)

· % - sign of the result entirely determined by sign of LHS

· 5 % 0 throws an ArithmeticException.

· Floating point calculations can produce NaN (square root of a negative no) or Infinity ( division by zero). Float and Double wrapper classes have named constants for NaN and infinities.

· NaN's are non-ordinal for comparisons. x == Float.NaN won't work. Use Float.IsNaN(x) But equals method on wrapper objects(Double or Float) with NaN values compares Nan's correctly.

· Infinities are ordinal. X == Double.POSITIVE_INFINITY will give expected result.

· + also performs String concatenation (when any operand in an expression is a String). The language itself overloads this operator. toString method of non-String object operands are called to perform concatenation. In case of primitives, a wrapper object is created with the primitive value and toString method of that object is called. ("Vel" + 3 will work.)

· Be aware of associativity when multiple operands are involved.

System.out.println( 1 + 2 + "3" ); // Prints 33

System.out.println( "1" + 2 + 3 ); // Prints 123

3. Shift operators - <<, >>, >>>

· << performs a signed left shift. 0 bits are brought in from the right. Sign bit (MSB) is preserved. Value becomes old value * 2 ^ x where x is no of bits shifted.

· >> performs a signed right shift. Sign bit is brought in from the left. (0 if positive, 1 if negative. Value becomes old value / 2 ^ x where x is no of bits shifted. Also called arithmetic right shift.

· >>> performs an unsigned logical right shift. 0 bits are brought in from the left. This operator exists since Java doesn't provide an unsigned data type (except char). >>> changes the sign of a negative number to be positive. So don't use it with negative numbers, if you want to preserve the sign. Also don't use it with types smaller than int. (Since types smaller than int are promoted to an int before any shift operation and the result is cast down again, so the end result is unpredictable.)

· Shift operators can be applied to only integral types.

· -1 >> 1 is -1, not 0. This differs from simple division by 2. We can think of it as shift operation rounding down.

· 1 << 31 will become the minimum value that an int can represent. (Value becomes negative, after this operation, if you do a signed right shift sign bit is brought in from the left and the value remains negative.)

· Negative numbers are represented in two's complement notation. (Take one's complement and add 1 to get two's complement)

· Shift operators never shift more than the number of bits the type of result can have. ( i.e. int 32, long 64) RHS operand is reduced to RHS % x where x is no of bits in type of result.

int x;

x = x >> 33; // Here actually what happens is x >> 1

4. Comparison operators - all return boolean type.

4.1 Ordinal comparisons - <, <=, > , >=

· Only operate on numeric types. Test the relative value of the numeric operands.

· Arithmetic promotions apply. char can be compared to float.

4.2 Object type comparison - instanceof

· Tests the class of an object at runtime. Checking is done at compile and runtime same as the cast operator.

· Returns true if the object denoted by LHS reference can be cast to RHS type.

· LHS should be an object reference expression, variable or an array reference.

· RHS should be a class (abstract classes are fine), an interface or an array type, castable to LHS object reference. Compiler error if LHS & RHS are unrelated.

· Can't use java.lang.Class or its String name as RHS.

· Returns true if LHS is a class or subclass of RHS class

· Returns true if LHS implements RHS interface.

· Returns true if LHS is an array reference and of type RHS.

· x instanceof Component[] - legal.

· x instanceof [] - illegal. Can't test for 'any array of any type'

· Returns false if LHS is null, no exceptions are thrown.

· If x instanceof Y is not allowed by compiler, then Y y = (Y) x is not a valid cast expression. If x instanceof Y is allowed and returns false, the above cast is valid but throws a ClassCastException at runtime. If x instanceof Y returns true, the above cast is valid and runs fine.

4.3 Equality comparisons - ==, !=

· For primitives it's a straightforward value comparison. (promotions apply)

· For object references, this doesn't make much sense. Use equals method for meaningful comparisons. (Make sure that the class implements equals in a meaningful way, like for X.equals(Y) to be true, Y instance of X must be true as well)

· For String literals, == will return true, this is because of compiler optimization.

5. Bit-wise operators - &, ^, |

· Operate on numeric and boolean operands.

· & - AND operator, both bits must be 1 to produce 1.

· | - OR operator, any one bit can be 1 to produce 1.

· ^ - XOR operator, any one bit can be 1, but not both, to produce 1.

· In case of booleans true is 1, false is 0.

· Can't cast any other type to boolean.

6. Short-circuit logical operators - &&, ||

· Operate only on boolean types.

· RHS might not be evaluated (hence the name short-circuit), if the result can be determined only by looking at LHS.

· false && X is always false.

· true || X is always true.

· RHS is evaluated only if the result is not certain from the LHS.

· That's why there's no logical XOR operator. Both bits need to be known to calculate the result.

· Short-circuiting doesn't change the result of the operation. But side effects might be changed. (i.e. some statements in RHS might not be executed, if short-circuit happens. Be careful)

7. Ternary operator

· Format a = x ? b : c ;

· x should be a boolean expression.

· Based on x, either b or c is evaluated. Both are never evaluated.

· b will be assigned to a if x is true, else c is assigned to a.

· b and c should be assignment compatible to a.

· b and c are made identical during the operation according to promotions.

8. Assignment operators.

· Simple assignment =.

· op= calculate and assign operators extended assignment operators.

· *=, /=, %=, +=, -=

· x += y means x = x + y. But x is evaluated only once. Be aware.

· Assignment of reference variables copies the reference value, not the object body.

· Assignment has value, value of LHS after assignment. So a = b = c = 0 is legal. c = 0 is executed first, and the value of the assignment (0) assigned to b, then the value of that assignment (again 0) is assigned to a.

· Extended assignment operators do an implicit cast. (Useful when applied to byte, short or char)

byte b = 10;

b = b + 10; // Won't compile, explicit cast required since the expression evaluates to an int

b += 10; // OK, += does an implicit cast from int to byte

9. General

· In Java, No overflow or underflow of integers happens. i.e. The values wrap around. Adding 1 to the maximum int value results in the minimum value.

· Always keep in mind that operands are evaluated from left to right, and the operations are executed in the order of precedence and associativity.

· Unary Postfix operators and all binary operators (except assignment operators) have left to right assoiciativity.

· All unary operators (except postfix operators), assignment operators, ternary operator, object creation and cast operators have right to left assoiciativity.

· Inspect the following code.

public class Precedence {

final public static void main(String args[]) {

int i = 0;

i = i++;

i = i++;

i = i++;

System.out.println(i); // prints 0, since = operator has the lowest precedence.

int array[] = new int[5];

int index = 0;

array[index] = index = 3; // 1st element gets assigned to 3, not the 4th element

for (int c = 0; c < array.length; c++)

System.out.println(array[c]);

System.out.println("index is " + index); // prints 3

}

}


Type of Operators

Operators

Associativity

Postfix operators

[] . (parameters) ++ --

Left to Right

Prefix Unary operators

++  -- + - ~ !

Right to Left

Object creation and cast

new (type)

Right to Left

Multiplication/Division/Modulus

* / %

Left to Right

Addition/Subtraction

+ -

Left to Right

Shift

>> >>> <<

Left to Right

Relational

< <= > >= instanceof

Left to Right

Equality

== !=

Left to Right

Bit-wise/Boolean AND

&

Left to Right

Bit-wise/Boolean XOR

^

Left to Right

Bit-wise/Boolean OR

|

Left to Right

Logical AND (Short-circuit or Conditional)

&&

Left to Right

Logical OR (Short-circuit or Conditional)

||

Left to Right

Ternary

? :

Right to Left

Assignment

Sunday, February 9, 2014

Mca Internship

I have some observations for MCA Interns.I want to clear some myths for you here

  1. Everybody wants to work on Live project
    1. Please note that no institution or company can put u directly on live project. May be they have fear that your coding standards may not be up to standards of Client.
    2. Always Live project goes through phase of dummy then testing and later UAT (user acceptance test) at last it reaches to Production environment which we call generally LIVE PROJECT.
    3. So try to learn on dummy projects then companies/client decides whether this should go live.
    4. As a developer important is learning java concepts, understanding business, Programing methodologies like Waterfall / Agile.
  2. Everybody wants to work on SPRING STRUTS 2.0
    1. Its fact that until you know core java , you should not do development in higher technologies
    2. My advice would be first know core java then servlet /jsp and at last frameworks and start implementing those frameworks in  your projects
  3. In Interview Struts/Hibernate/Spring require
    1. That is true but interview starts with core java and ends with frameworks
    2. If interview lasts for 40 mins means interviewer will ask core java at least 25 mins then go for frameworks and then your project discussion.
  4. Freshers Does not get calls
    1. At least one call you will get at worst condition in 3 to 4 months, if you have good knowledge you will crack it so don't expect more calls but concentrate upon knowledge. means if you get single call you should and must crack it.
  5. Where is more scope JAVA/.NET
    1. Very simple concept Lot of scope in cricket, you can earn lot of money but you should know good cricket :)  :) same for bollywood :) :)
    2. So as I said in above 1 point  If you are good in java you will get job and same for .net.  as  companies want good people and if you are good no issue.
    3. Please concentrate upon what you are doing , do your best and give your 100 %, I assure you that you will get success.

SCJP Part 1

1. Source file's elements (in order)
•         Package declaration
•         Import statements
•         Class definitions

2. Importing packages doesn't recursively import sub-packages.

3. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.

4. Comments can appear anywhere. Can't be nested. No matter what type of comments.

5. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file's name and give an error at the line where the other class is defined.

6. It's not required having a public class definition in a file. Strange, but true. J In this case, the file's name should be different from the names of classes and interfaces (not public obviously).

7. Even an empty file is a valid source file.

8. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.

9. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false and null are literals (not keywords), but they can't be used as identifiers as well.

10. const and goto are reserved words, but not used.

11. Unicode characters can appear anywhere in the source code. The following code is valid.

ch\u0061r a = 'a';

char \u0062 = 'b';

char c = '\u0063';

12. Java has 8 primitive data types.
Data Type Size (bits) Initial Value Min Value Max Value
boolean 1 false  false true
byte 8 0 -128 (-27) 127 (27 - 1)
short 16 0 -215 215 - 1
char 16 '\u0000' '\u0000' (0) '\uFFFF' (216 - 1)
int 32 0 -231 231 - 1
long 64 0L -263 263 - 1
float 32 0.0F 1.4E-45 3.4028235E38
double 64 0.0 4.9E-324 1.7976931348623157E308



13. All numeric data types are signed. char is the only unsigned integral type.

14. Object reference variables are initialized to null.

15. Octal literals begin with zero. Hex literals begin with 0X or 0x.

16. Char literals are single quoted characters or unicode values (begin with \u).

17. A number is by default an int literal, a decimal number is by default a double literal.

18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it's an identifier)

19. Two types of variables.

a. Member variables
•         Accessible anywhere in the class.
•         Automatically initialized before invoking any constructor.
•         Static variables are initialized at class load time.
•         Can have the same name as the class.
b. Automatic variables method local
• Must be initialized explicitly. (Or, compiler will catch it.) Object references can be initialized to null to make the compiler happy. The following code won't compile. Specify else part or initialize the local variable explicitly.

public String testMethod ( int a) {

String tmp;

if ( a > 0 ) tmp = "Positive";

return tmp;

}

• Can have the same name as a member variable, resolution is based on scope.

20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.

21. Arrays should be
•         Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
•         Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
•         Initialized. for (int i = 0; i < a.length; a[i++] = 0)
22. The above three can be done in one step.

int a[] = { 1, 2, 3 }; (or )

int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.

23. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns array's size. (Use Vectors for dynamic purposes).
24. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable.
25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]
26. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0.
27. Comma after the last initializer in array declaration is ignored.
int[] i = new int[2] { 5, 10}; // Wrong
int i[5] = { 1, 2, 3, 4, 5}; // Wrong
int[] i[] = {{}, new int[] {} }; // Correct
int i[][] = { {1,2}, new int[2] }; // Correct
int i[] = { 1, 2, 3, 4, } ; // Correct
28. Array indexes start with 0. Index is an int data type.
29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.
30. Arrays declared even as member variables also need to be allocated memory explicitly.
static int a[];
static int b[] = {1,2,3};
public static void main(String s[]) {
System.out.println(a[0]); // Throws a null pointer exception
System.out.println(b[0]); // This code runs fine
System.out.println(a); // Prints 'null'
System.out.println(b); // Prints a string which is returned by toString
}
31. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values.
32. If only declared (not constructed), member array variables default to null, but local array variables will not default to null.
33. Java doesn't support multidimensional arrays formally, but it supports arrays of arrays. From the specification - "The number of bracket pairs indicates the depth of array nesting." So this can perform as a multidimensional array. (no limit to levels of array nesting)
34. In order to be run by JVM, a class should have a main method with the following signature.
public static void main(String args[])
static public void main(String[] s)
35. args array's name is not important. args[0] is the first argument. args.length gives no. of arguments.

36. main method can be overloaded.
7. main method can be final.
38. A class with a different main signature or w/o main method will compile. But throws a runtime error.
39. A class without a main method can be run by JVM, if its ancestor class has a main method. (main is just a method and is inherited)
40. Primitives are passed by value.
41. Objects (references) are passed by reference. The object reference itself is passed by value. So, it can't be changed. But, the object can be changed via the reference.
42. Garbage collection is a mechanism for reclaiming memory from objects that are no longer in use, and making the memory available for new objects.

43. An object being no longer in use means that it can't be referenced by any 'active' part of the program.
44. Garbage collection runs in a low priority thread. It may kick in when memory is too low. No guarantee.
45. It's not possible to force garbage collection. Invoking System.gc may start garbage collection process.
46. The automatic garbage collection scheme guarantees that a reference to an object is always valid while the object is in use, i.e. the object will not be deleted leaving the reference "dangling".
47. There are no guarantees that the objects no longer in use will be garbage collected and their finalizers executed at all. gc might not even be run if the program execution does not warrant it. Thus any memory allocated during program execution might remain allocated after program termination, unless reclaimed by the OS or by other means.
48. There are also no guarantees on the order in which the objects will be garbage collected or on the order in which the finalizers are called. Therefore, the program should not make any decisions based on these assumptions.
49. An object is only eligible for garbage collection, if the only references to the object are from other objects that are also eligible for garbage collection. That is, an object can become eligible for garbage collection even if there are references pointing to the object, as long as the objects with the references are also eligible for garbage collection.
50. Circular references do not prevent objects from being garbage collected.
51. We can set the reference variables to null, hinting the gc to garbage collect the objects referred by the variables. Even if we do that, the object may not be gc-ed if it's attached to a listener. (Typical in case of AWT components) Remember to remove the listener first.
52. All objects have a finalize method. It is inherited from the Object class.
53. finalize method is used to release system resources other than memory. (such as file handles and network connections) The order in which finalize methods are called may not reflect the order in which objects are created. Don't rely on it. This is the signature of the finalize method.
protected void finalize() throws Throwable { }
In the descendents this method can be protected or public. Descendents can restrict the exception list that can be thrown by this method.
54. finalize is called only once for an object. If any exception is thrown in finalize, the object is still eligible for garbage collection (at the discretion of gc)
55. gc keeps track of unreachable objects and garbage-collects them, but an unreachable object can become reachable again by letting know other objects of its existence from its finalize method (when called by gc). This 'resurrection' can be done only once, since finalize is called only one for an object.
56. finalize can be called explicitly, but it does not garbage collect the object.
57. finalize can be overloaded, but only the method with original finalize signature will be called by gc.
58. finalize is not implicitly chained. A finalize method in sub-class should call finalize in super class explicitly as its last action for proper functioning. But compiler doesn't enforce this check.
59. System.runFinalization can be used to run the finalizers (which have not been executed before) for the objects eligible for garbage collection.

How to Study Scjp 1.5

Steps  -
 I took this from other website Its real advice.http://www.wikihow.com/Study-Scjp-1.5
  1. 1
    Plan out the certification exam you are going to take well in advance.
  2. 2
    It is always better to have the voucher ready say after 6 months or so you will be giving the exam.
  3. 3
    Start early with the concepts. Some of the good books available are from the authors: Kathy Sierra and Khalid Mughal.
  4. 4
    Practice...Practice and Practice. That's one of the important things to get going! The more you practice, the more your concepts are clear.
  5. 5
    Make a habit of dedicating a particular slot of (say) 2-3 hours (depends on individual) to study various tutorials, notes, articles, not to forget the books mentioned above.
  6. 6
    Lastly there are mock test for SCJP 1.5 available which you can appear. Mock test CDs are available along with the books from Kathy Sierra.
  7. 7
    All Set....revise the Key Points from each chapter, prepare some notes for your own understanding and you are now ready to take the Exam!
  • Write short programs that helps you understand the exam objectives of SCJP 1.5

Warnings

  • Do not neglect any topic.

Saturday, February 8, 2014

Method Overriding

Overriding

        also called shadowing-    www.javabykiran.com

■  Overriding is defined as when a subclass method provides three things which are the same as in the overridden method:
(1) method name, and
(2) parameter list, and
(3) return type See signature.

■  You cannot change the return type of an overridden method. 

■ You cannot make the overriding method be less accessible (meaning more private) than the overridden method.  See modifiers.

■ The order of this accessibility, from least restrictive to most restrictive, is: 
(least restrictive is) public, then
protected, then
friendly/package/default, and lastly
(most restrictive is)  private 

■ You cannot override a public or protected method using no modifiers (which would be assigning friendly/package, which is more restrictive). i.e.

■  You cannot override a private method either, in any way. (It's private. You cannot override it because it cannot be seen outside its class.) Doing so compiles but becomes overloading in all cases.

■  When overriding you cannot throw higher level exceptions or exceptions any from different hierarchies.   You can just throw none, the same, fewer, orsubclasses of those exceptions already being thrown in the overridden method.

■  You cannot ever override a non-static method with a static method, or a static method with a non-static method. 

■  super.methodname( ) calls parent methods which you did not override. 

■  If an overridden method is synchronized, you can safely ignore the synchronized.

■  It is not overriding if, in subclasses, you simply re-use the names of higher private methods again.  That is allowed.

Comparisons

comparisons


            Read also  instanceof,  interning,  equals(...)

■  To test if an object belongs to a class (or to one of its superclasses), to an interface, or whether it is an Array, use instanceof.  i.e.

String s = "S";  
if ( s instanceof Object )  is true
if ( s instanceof String )  is true

■  To test if two object references point to the same object or if an object reference is null, use == (double equals). 
For object references, !=  means does not point to the same object.  i.e.

String s1 = "S";  
String s2 = "T"; 
if ( s1 == s2 ) is false.
. . . .
String s1 = "S";  
String s2 = "T"; 
if ( s1 != s2 ) is true.
. . . .
String s1 = null;  
if ( s1 == null ) is true.

■  Remember that the toString( ) method always creates a new object.  i.e.

if ( samething.toString( ) == samething.toString( ) ) will always be false because they’re always different objects.

■  The == operator doesn’t differentiate between floating point's primitive positive zero, normal zero, or negative zero.  i.e.

if ( –0.0 == +0.0 ) is true.  So are any other == comparisons between 0.0. +0.0, and -0.0.

■  For objects only, use object.equals( anotherobject ) to see if the actual contents of two objects match. 

■  You cannot use == to compare objects of different types, as a compile error will result. i.e.

String s1 = "S";  
Character c1 = new Character( 'S' ); 
if (  s1 == c1 ) System.out.print( "True" );   will not compile.

■  To test if two objects are of the same class type (or supertype) use Object’s getClass( ) method with == .   The getClass( ) method returns a Class object. i.e.
if (object1.getClass( ) == object2.getClass( )) then do something. 

.equals(...)  method


■   Compare objects.     equals(...)  does a byte-by-byte comparison on contents, ignoring the object's location.  It is the opposite of == , which ignores contents and compares location pointers.

■  Unless you override the equals(...) method in an object's class, equals(...) is the same as == , which compares just pointers, not contents. Without an override you will default to using the equals(...) method from Object, which does just a   ==  comparison. The wrappers and collections classes, plus String,  all overrideequals(...) so they provide actual content comparisons. 

■ You cannot use equals(...) for primitives or literals.  i.e.

                        Double D = new Double( 5 );  
                        if ( D.equals( 5 ) ) will not compile due to the literal 5.

                        Double D = new Double( 5 ); 
                        int d = 5; 
                                if ( D.equals( d ) )   will not compile due to the presence of the primitive d.

■  You cannot get true results on objects of different types using equals(...). It is only for objects of the same type.  i.e.

                        Character C = new Character( 'A' );  
                        Object O = new StringBuffer( "A" );  
                        String S = "A";
                        if ( C.equals( O ) )             is false
                        if ( S.equals( C ) )             is false
                        if ( S.equals( O ) )             is false

■ You cannot use equals(...) between different wrapper types as it will always returns a false.  i.e.

                        Double D = new Double ( 2.0 );
                        Float F = new Float( 2.0 );
                        if (D.equals( F) )     is false due to different object types

■  You cannot use equals(...) for StringBuffer, as StringBuffer does not provide an override.   i.e.

                        StringBuffer s1 = new StringBuffer( "ABC" );
                        StringBuffer s2 = new StringBuffer( "ABC" );
                        if ( s1.equals(s2) )                 is false

                        However...
                        String s1 = new String( "ABC" );
                                String s2 = new String( "ABC" );
                                if ( s1.equals( s2 ) )               is true

■ You cannot ever check an object for null with equals(...)
That’s because with null there's no actual null object to which to compare. 
You must say if (obj == null) instead.  i.e.

                        if ( object.equals( null ) ) runs and it returns false if the object is real.
                        But it gives a NullPointerException if the object in question was actually null.

■  Unlike the == operator, the equals(...) method treats two wrapper NaNs as equal.   i.e.

                        Float F1 = new Float( Float.NaN ); 
                        Float F2 = new Float( Float.NaN ); 
                        if ( F1.equals( F2 ) )                       returns true
                        if ( F1 == F2 ) )                             returns false

■  Unlike the == operator, which treats all manners of floating point zeroes as unequal, equals(...) treats wrapper contents of floating point +0.0 as equal to 0.0. i.e.

In wrappers:

= = returns
equals(...) returns
+0.0 to 0.0
unequal
equal
+0.0 to -0.0
unequal
unequal
0.0 to -0.0
unequal
unequal