Saturday, August 17, 2013

Singleton class and Static class

Singleton class and Static class

Difference between Singleton and Static class

The difference is singleton class might allow the implement interface, but not possible in static class.Using the single implementation (or derive from base class), it's just like another implementation.
Both should be implemented to be thread-safe

Singleton class example

A Singleton class allows to create a single instance only, that instance can be passed as parameter to other methods and it treated as a normal object.

public class MySingleTon {
private static MySingleTon myObj;
//Create private constructor
private MySingleTon(){

}

//Create a static method to get instance.
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
}


Static class example
A Static class allows static method only.
class StaticExample
{
static void getInstance()
{
//Add code here
}
static void getData()
{
//Add code here
}
}

Saturday, August 3, 2013

Singleton class and Static class

Singleton class and Static class

Difference between Singleton and Static class

The difference is singleton class might allow the implement interface, but not possible in static class.Using the single implementation (or derive from base class), it's just like another implementation.
Both should be implemented to be thread-safe

Singleton class example

A Singleton class allows to create a single instance only, that instance can be passed as parameter to other methods and it treated as a normal object.

public class MySingleTon {
private static MySingleTon myObj;
//Create private constructor
private MySingleTon(){

}

//Create a static method to get instance.
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
}

Static class example
A Static class allows static method only.
class StaticExample
{
static void getInstance()
{
//Add code here
}
static void getData()
{
//Add code here
}
}

Tuesday, October 23, 2012

difference between equals() and hashCode()

public boolean equals(Object obj)

This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison". However, the classes providing their own implementations of the equals method are supposed to perform a "deep comparison"; by actually comparing the relevant data members. Since Object class has no data members that define its state, it simply performs shallow comparison.

The equals method implements an equivalence relation:
-It is reflexive: for any reference value x, x.equals(x) should return true.
-It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
-It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
-It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
For any non-null reference value x, x.equals(null) should return false.

public int hashCode()

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 integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

-If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
-It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Hashcode example

public class HashCodeString {
public static void main(String args[]) {
Integer j = new Integer(4);
Long k = new Long(4);
Integer v = new Integer(3);
System.out.println("false is returned: " + j.equals(k)); // Result - false
System.out.println("Hash code of number 4 is: " + j.hashCode() //Result 4
+ "\nHash code of number 4 is: " + k.hashCode()); // 4
System.out.println("Method returns three: " + v.hashCode()); // 3
String baadshah = "latter in time there will be my empire every where";
System.out.println("Corresponding hash code value returned is: "
+ baadshah.hashCode()); // Result 342564105
}

}


==, .equals(), compareTo(), and compare()

==
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object

equals()
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

It turns out that defining equals() isn't trivial; in fact it's moderately hard to get it right, especially in the case of subclasses. The best treatment of the issues is in Horstmann's Core Java Vol 1. [TODO: Add explanation and example]

compareTo()
Comparable interface. Compares values and returns an int which tells if the values compare less than, equal, or greater than. If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).

compare()
omparator interface. Compares values of two objects. This is implemented as part of the Comparator interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following.

Multiple comparisions. To provide several different ways to sort somthing. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
System class. To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
Strategy pattern. To implement a Strategey pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.

If your class objects have one natural sorting order, you may not need this.

Tuesday, March 23, 2010

public static void main(String... args)

Here you will see that you can even change the signature of main(). Although there is no reason for doing this, the canonical public static void main(String[] args) can be changed to public static void main(String ... args):

public class VarGreeter3 {

public static void printGreeting(String... names) {
for (String n : names) {
System.out.println("Hello " + n + ". ");
}
}

public static void main(String... args) {
printGreeting(args);
}
}
Run VarGreeter3 with the command:

java VarGreeter3 Paul Sue

and you will get the same output as before:

Hello Paul.
Hello Sue.

Using "main(String... args)" makes it easier to invoke main directly from Java. This can be useful for writing unit tests of your main() method.

Thursday, August 27, 2009

Java Tips

Java General Tips

 Unicode Characters are expressed as 4 character hex codes e.g. c = "\u45c7" .
 Scientific numerical literals such as 1E2 are assigned to double data types by default.
 The default type of any numeric literal with a decimal point is double.
 integer and long operations / and % can throw ArithmeticException whilst float / and % do not - not even with divide by zero.
 Negative binary numbers are the same as their positive equivalents 1 , with bits reversed.
 ( -1 >> anything ) = -1 and is always promoted to at least int type.
 ( -1 & anything ) = anything, since 1 is all 1 bits.
 The &sim operator is actually a typo in some books for "~" (bitwise integral inversion).
 In range literal assignments are allowed for byte , short and char primitive data types.
 The Math.random() method produces a number >= 0.0 and < 1.0 .
 Angles passed to Math.sin(), cos() or tan() are expressed in Radians.
 The Math class is immutable.
 The expression -0.0 == 0.0 returns true.
 Valid boolean literals are true¡± and false¡± only.
 The expression for ( ; ; ) { } is an infinite loop therefore it will compile.
 Static methods are called once at class load time.
 Static methods can not be overridden, nor can final methods.
 Methods may not have the same name as the constructor(s).
 Constructors CAN be private, as in the Math class - but it is not common.
 Constructors can throw ANY exception.
 Initializer blocks are executed in the order of their declaration.
 Instance initializers get executed ONLY IF the objects are constructed.
 The main() method can be declared final.
 Static methods can not use non-static features of the class. The main() method can not reference unqualified non-static methods.
 You can access and use static methods and variables e.g. Math.round() and Math.PI.
 Access modifiers dictate which classes NOT instances may access features.
 Access modifiers are only used on class level variables, with rare exceptions.
 (Local) Inner classes in methods can access final variables inside the enclosing method or its parameters. They may also access the non-static data of the enclosing class.
 Methods of a static inner class can not access instance variables of the enclosing class, only static ones.
 Inner classes can have any access modifier, but those defined within a method can not. Such a class is private to that block. Inner classes in a block may not be static.
 No inner class can have a static member.
 Garbage collection takes place (possibly) sometime after an object is no longer being used. Assign null to a variable when you have finished using it.
 A method of the form : public Object pop() { return storage[index--]; } will cause a memory leak.

Tuesday, January 6, 2009

Java (programming language)

Java is a programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun made available most of their Java technologies as free software under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath.

History

James Gosling initiated the Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office, also went by the name Green and ended up later renamed as Java, from a list of random words. Gosling aimed to implement a virtual machine and a language that had a familiar C/C++ style of notation.

Sun released the first public implementation as Java 1.0 in 1995. It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms. Fairly secure and featuring configurable security, it allowed network- and file-access restrictions. Major web browsers soon incorporated the ability to run secure Java applets within web pages, and Java quickly became popular. With the advent of Java 2 (released initially as J2SE 1.2 in December 1998), new versions had multiple configurations built for different types of platforms. For example, J2EE targeted enterprise applications and the greatly stripped-down version J2ME for mobile applications. J2SE designated the Standard Edition. In 2006, for marketing purposes, Sun renamed new J2 versions as Java EE, Java ME, and Java SE, respectively.

Java Platform

One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any supported hardware/operating-system platform. One should be able to write a program once, compile it once, and run it anywhere.

This is achieved by compiling the Java language code, not to machine code but to Java bytecode – instructions analogous to machine code but intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java Applets.


Automatic memory management


Java uses an automatic garbage collector to manage memory in the object lifecycle. The programmer determines when objects are created, and the Java runtime is responsible for recovering the memory once objects are no longer in use. Once no references to an object remain, the unreachable object becomes eligible to be freed automatically by the garbage collector. Something similar to a memory leak may still occur if a programmer's code holds a reference to an object that is no longer needed, typically when objects that are no longer needed are stored in containers that are still in use.

One of the ideas behind Java's automatic memory management model is that programmers be spared the burden of having to perform manual memory management. In some languages memory for the creation of objects is implicitly allocated on the stack, or explicitly allocated and deallocated from the heap. Either way the responsibility of managing memory resides with the programmer. If the program does not deallocate an object, a memory leak occurs. If the program attempts to access or deallocate memory that has already been deallocated, the result is undefined and the program may become unstable and/or may crash. This can be partially remedied by the use of smart pointers, but it adds overhead and complexity.

Syntax

The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object oriented language. All code is written inside a class and everything is an object, with the exception of the intrinsic data types (ordinal and real numbers, boolean values, and characters), which are not classes for performance reasons.

Java suppresses several features (such as operator overloading and multiple inheritance) for classes in order to simplify the language and to prevent possible errors and anti-pattern design.

Examples

The traditional Hello world program can be written in Java as:

/**
* Outputs "Hello, World!" and then exits
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

A class that is declared private may be stored in any .java file. The compiler will generate a class file for each class defined in the source file. The name of the class file is the name of the class, with .class appended. For class file generation, anonymous classes are treated as if their name was the concatenation of the name of their enclosing class, a $, and an integer.

The keyword public denotes that a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy. The class hierarchy is related to the name of the directory in which the.java file is.

The keyword static in front of a method indicates a static method, which is associated only with the class and not with any specific instance of that class. Only static methods can be invoked without a reference to an object. Static methods cannot access any method variables that are not static.

The keyword void indicates that the main method does not return any value to the caller. If a Java program is to exit with an error code, it must call System.exit()

The method name "main" is not a keyword in the Java language. It is simply the name of the method the Java launcher calls to pass control to the program. Java classes that run in managed environments such as applets and Enterprise Java Beans do not use or need a main() method. A java program may contain multiple classes that have main methods, which means that the VM needs to be explicitly told which class to launch from.