Showing posts with label static. Show all posts
Showing posts with label static. Show all posts

Monday, 30 May 2011

How to synchronize a static variable of a class ?

There are some ways(3 to my knowledge, but may be more), by which a static variable can be synchronized in java.

1) Use a synchronized static method. This synchronizes on the class object.

public class Counter {
private static int count = 0;

public static synchronized void incrementCount() {
count++;
}
}


2) Explicitly synchronize on the class object, using synchronize on ClassName.class

public class Counter {
private static int count = 0;

public void incrementCount() {
synchronize (Test.class) {
count++;
}
}
}


3) Synchronize on some other static object.

public class Counter {
private static int count = 0;
private static final Object countLockHelper = new Object();

public void incrementCount() {
synchronize (countLockHelper) {
count++;
}
}
}


Method 3 is best in many cases because the lock object is not exposed outside of your class. So if you create instance of these class, they will be synchronized on the same static object.

But if you just using some basic type like integer here in case of counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

public class Counter {

private final static AtomicInteger count = new AtomicInteger(0);

public void incrementCount() {
count.incrementAndGet();
}
}

Saturday, 14 May 2011

Difference between static and init block

The static block is only loaded when the class object is created by the JVM for the 1st time whereas init {} block is loaded every time class object is created. Also first the static block is loaded then the init block.

public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}



Output:

Inside static
Inside init
Inside init
Inside init


So static block is initialized only once, that is it is per class basis, whereas init block is per object basis.

Monday, 18 April 2011

Points to not about static in java

Java Static Variables

  • Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • Any java object that belongs to that class can modify its static variables.
  • Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
  • Static variables can be accessed by java instance methods also.
  • When the value of a constant is known at compile time it is declared ‘final’ using the ’static’ keyword.


Java Static Methods

  • Similar to static variables, java static methods are also common to classes and not tied to a java instance.
  • Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
  • General use for java static methods is to access static fields.
  • Static methods can be accessed by java instance methods.
  • Java static methods cannot access instance variables or instance methods directly.
  • Java static methods cannot use the ‘this’ keyword.


Java Static Classes

  • For java classes, only an inner class can be declared using the static modifier.
  • For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java.


Java vs C++ static


Static fields and methods have the same functionality in Java and C++. However, the syntax is slightly different. 
In C++, you use the :: operator to access a static field or method outside its scope, such as Math::PI.

The term "static" has a curious history. 
  • At first, the keyword static was introduced in C to denote local variables that don't go away when a block is exited. In that context, the term "static" makes sense: the variable stays around and is still there when the block is entered again. 
  • Then static got a second meaning in C, to denote global variables and functions that cannot be accessed from other files. The keyword static was simply reused, to avoid introducing a new keyword. 
  • Finally, C++ reused the keyword for a third, unrelated, interpretation—to denote variables and functions that belong to a class but not to any particular object of the class. That is the same meaning that the keyword has in Java.

Sunday, 17 April 2011

Getting a class name from static method

So our class's static method must return the name. So consider this class and its static method:

public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}

So following are the methods:
Using reflections
MyClass.class.getName();
Also,
If you want the entire package name with it, call:
String name = MyClass.class.getCanonicalName();

If you only want the last element, call:
String name = MyClass.class.getSimpleName();

Using getEnclosingClass method
return new Object() { }.getClass().getEnclosingClass();

Abusing the security manager
System.getSecurityManager().getClassContext()[0].getName();

OR using the static inner class method to return the class name:
public static class CurrentClassGetter extends SecurityManager {
public String getClassName() {
return getClassContext()[1].getName();
}
}



Friday, 15 April 2011

Double Brace Initialization in Java!

Few days back I came to know about a different way of initializing collections and objects in Java. Although this method of initialization has been there in Java since quite a few years now, very few people actually knows about it or have used it in their code. The technique is called Double Brace Initialization technique in Java.
Let us see first how we will initialize an ArrayList in Java by “normal” way:

List<String> countries = new ArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");

Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.

Now check the Double Brace Initialization of the same code:
List<String> countries = new ArrayList<String>() {{
add("India");
add("Switzerland");
add("Italy");
add("France");
add("Germany");
}};

How does this works?

Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared withing the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class . The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.
If you have not understood the concept, try executing following code and it will make things clear for you.


public class Test {
public Test() {
System.out.println("Constructor called");
}
static {
System.out.println("Static block called");
}

{
System.out.println("Instance initializer called");
}

public static void main(String[] args) {
new Test();
new Test();
}
}

Output:

Static block called
Instance initializer called
Constructor called
Instance initializer called
Constructor called
Thus the instance initializer code will be called each time a new instance of object is created.

Wednesday, 13 April 2011

Static Imports in Java 5

Static keyword is used to allow access to an attribute/ a method or a class without creating instance of it. (Some of you may argue that this is not object oriented way, but we leave that discussion aside for now.) We use static for those elements which do not change from instance to instance of a class. An example would be constant variables in a program. These values are stored using ‘public static final’ keywords. In enum article we have seen one way of managing logically linked constants. Static import tries to improve the way we store and use static elements in program.
Java says it has tried to address an anti-pattern – using interface for constants. Some of us may have used this type of design in programs, where constants are grouped in an interface and used by implementing that interface. This approach is wrong because it alters the purpose of having interfaces in a Java application. Interfaces are used to define highest level of abstract behavior and also to expose a contract to the world in terms of method signatures. Thus, we cannot use interfaces to store constants. An alternative is having them in respective functional classes or in a separate class which can be reused.
When we use this class, we import it and use it wherever the variable is required. Here is the example.
Constants class
package constants;  

public class MyConstants {

public static final String CONSTANT1 = "constant 1";
public static final String CONSTANT2 = "constant 2";
public static final String CONSTANT3 = "constant 3";
}

 Class using constants without static import
import constants.MyConstants;  

public class WithoutStaticImport {

public static void main(String[] args) {
System.out.println(MyConstants.CONSTANT1);
}

}


 
If you have many such constants, then every time you need to use these constants with class name in front of it. With static import, you can get rid of the class name and use constants directly. Let us see how.

Using Static Constant

import static constants.MyConstants.CONSTANT1;  

public class WithStaticImport {

public static void main(String[] args) {
System.out.println(CONSTANT1);
}

}


Important Considerations:

  • Java suggests – use static imports sparingly because these reduce readability and maintainability of a program considerably.
  • Use it when you feel you are going to wrongly use inheritance (i.e. interfaces).
  • When number of variables is less and you can maintain the readability by using meaningful names.
Benefits of static import with already present static java fields
Here are some examples:
  • instead of System.out.println you can use out.println:
    Import the field:
    import static java.lang.System.out;

    So now in code you can write:
    out.println("Hello, World!");
  • PI instead of Math.PI
    area = PI * R * R
    look so much nicer than
    area = Math.PI * R * R

    Tuesday, 12 April 2011

    Some points to note about enums

    There are few things which could probably be improved in the coming versions of Java.

    • Currently null can be passed as a method parameter or assigned where an enum is expected. A compile-time verification for null enum assignment would probably avoid all those extra null checks that we need to incorporate in our code.
    • Static fields within enums cannot be accessed in its constructor. But, static methods are allowed to be invoked. The compiler enforces verification only for static fields and not methods.
    • However, enum constructors are invoked before static initialization is performed and hence the static fields would not be initialized. So, if you invoke static methods from the constructor which inturn access static fields, they would all be un-initialized.

    Sunday, 20 February 2011

    Static Member Classes

    static member class (or interface) is much like a regular top-level class (or interface). For convenience, however, it is nested within another class or interface.

     Defining and Using a Static Member Interface

    // A class that implements a stack as a linked list
    public class LinkedStack {
    // This static member interface defines how objects are linked
    public static interface Linkable {
    public Linkable getNext();
    public void setNext(Linkable node);
    }


    // The head of the list is a Linkable object
    Linkable head
    ;

    // Method bodies omitted
    public void push(Linkable node) { ... }
    public Object pop() { ... }
    }

    // This class implements the static member interface
    class LinkableInteger implements LinkedStack.Linkable {
    // Here's the node's data and constructor
    int i;
    public LinkableInteger(int i) { this.i = i; }

    // Here are the data and methods required to implement the interface
    LinkedStack
    .Linkable next;
    public LinkedStack.Linkable getNext() { return next; }
    public void setNext(LinkedStack.Linkable node) { next = node; }
    }

    Features of Static Member Classes

    A static member class or interface is defined as a static member of a containing class, making it analogous to the class fields and methods that are also declaredstatic. Like a class method, a static member class is not associated with any instance of the containing class (i.e., there is no this object). A static member class does, however, have access to all the static members (including any other static member classes and interfaces) of its containing class. A static member class can use any other static member without qualifying its name with the name of the containing class.
    A static member class has access to all static members of its containing class, including private members. The reverse is true as well: the methods of the containing class have access to all members of a static member class, including the private members. A static member class even has access to all the members of any other static member classes, including the private members of those classes.
    Since static member classes are themselves class members, a static member class can be declared with its own access control modifiers. These modifiers have the same meanings for static member classes as they do for other members of a class.In above example, the Linkable interface is declared public, so it can be implemented by any class that is interested in being stored on a LinkedStack.

    Restrictions on Static Member Classes

    A static member class cannot have the same name as any of its enclosing classes. In addition, static member classes and interfaces can be defined only within top-level classes and other static member classes and interfaces. This is actually part of a larger prohibition against static members of any sort within member, local, and anonymous classes.

    New Syntax for Static Member Classes

    In code outside of the containing class, a static member class or interface is named by combining the name of the outer class with the name of the inner class (e.g.,LinkedStack.Linkable). You can use the import directive to import a static member class:
    import LinkedStack.Linkable;  // Import a specific inner class
    import LinkedStack.*; // Import all inner classes of LinkedStack
    Importing inner classes is not recommended, however, because it obscures the fact that the inner class is tightly associated with its containing class.

    Type of nested classes

    A nested class is a class defined within another class. A nested classes should exist only to serve its enclosing class. If a nested class would be useful in some other context, then it should be a top-level class. This was covered in the post : Nesting of classes : Introduction.

    Note : Inner classes are one type of nested class. So both cannot be inter-changeably used.

    Types of nested class : Introduction
    There are two types of nested classes: static and non-static.

    A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used.

    The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

    Types of Nested class ( Detailed )

    There are four kinds of nested classes: static member classes, nonstatic member classes, anonymous classes, and local classes.
    1. Static member classes
    2. Member classes
    3. Local classes
    4. Anonymous classes

    Non-instantiable Utility classes - Enforce Noninstantiability With a Private Constructor

    Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses. They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays. They can also be used to group static methods, including factory methods, for objects that implement a particular interface, in the manner of java.util.Collections. Lastly, they can be used to group methods on a final class, instead of extending the class.

    Such utility classes were not designed to be instantiated: an instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs.

    Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance (Item 17). There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor:

    // Noninstantiable utility class
    public class UtilityClass {
    // Suppress default constructor for noninstantiability
    private UtilityClass() {
    throw new AssertionError();
    }
    ... // Remainder omitted
    }


    Because the explicit constructor is private, it is inaccessible outside of the class. The AssertionError isn't strictly required, but it provides insurance in case the constructor is accidentally invoked from within the class. It guarantees that the class will never be instantiated under any circumstances. This idiom is mildly counterintuitive, as the constructor is provided expressly so that it cannot be invoked. It is therefore wise to include a comment, as shown above.

    As a side effect, this idiom also prevents the class from being subclassed. All constructors must invoke a superclass constructor, explicitly or implicitly, and a subclass would have no accessible superclass constructor to invoke.

    This pattern also works well when you want the ability to cache an object. For example if you were creating a String class that is immutable. For every String "FOO" created you want one instance. If you make the class notinstantiable and instead add a String.get("foo") method, you can ensure that you return one and only one instance. For example:

    public class MyString {
    private MyString() { }
    private WeakHashMap<String,String> map = new WeakHashMap<String,String>();
    public get(String s) {
    if (map.get(s))
    return map.get(s);
    else {
    map.put(s,s);
    return map.get(s);
    }
    }
    }



    In fact this pattern is used for the Java Integer class. It is recommended you use Integer.valueOf(int i). We can see why by looking at their code:

    private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
    for(int i = 0; i < cache.length; i++)
    cache[i] = new Integer(i - 128);
    }
    }

    /**
    * Returns a <tt>Integer</tt> instance representing the specified
    * <tt>int</tt> value.
    * If a new <tt>Integer</tt> instance is not required, this method
    * should generally be used in preference to the constructor
    * {@link #Integer(int)}, as this method is likely to yield
    * significantly better space and time performance by caching
    * frequently requested values.
    *
    * @param i an <code>int</code> value.
    * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
    * @since 1.5
    */
    public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache
    return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
    }


    For any value between -128 and 127 the class has already been constructed and when you call it, you simply get a pointer to that Object.

    So in conclusion when you have a class that you don't always want instantiated you should consider making the constructor private.

    Friday, 18 February 2011

    Static initializer block is called only when the class is being loaded in JVM

    public class StaticTest {
    static {
    System.out.println("Hi there");
    }
    public void print() {
    System.out.println("Hello");
    }
    public static void main(String args []) {
    StaticTest st1 = new StaticTest();
    st1.print();
    StaticTest st2 = new StaticTest();
    st2.print();
    }
    }
    So this class prints :
    Hi there
    Hello
    Hello

    Note that Hi there is printed only once.

    Method overloading,overriding and static

    public class Test {
    public static void test() {
    print();
    }
    public static void print() {
    System.out.println("Test");
    }
    public void print() {
    System.out.println("Another Test");
    }
    }
    So this code will not work stating - duplicate method error.

    Static methods are hidden, so not over-ridden

    static methods can be hidden ie you can declare a static method in the subclass with the same signature as a static method in the superclass. The superclass method will not be accessible from a subclass reference

    Thursday, 17 February 2011

    Swapping of two numbers works in case of static function

    Consider the case of swapping 2 integers. We swapped them earlier by boxing them to object. But it works in case of static function as well:

     

    public class Swapping{
      static void swap(int i,int j){
        int temp=i;
        i=j;
        j=temp;
        System.out.println("After swapping i = " + i + " j = " + j);
      }
      public static void main(String[] args){
        int i=1;
        int j=2;
      
        System.out.prinln("Before swapping i="+i+" j="+j);
        swap(i,j);
      
      }
    }

    Output is they are swapped. Smile with tongue out

    Sunday, 26 September 2010

    Static Inner Classes

    Consider the following Java code fragment:
    public class A
    {
    int y;

    public static class B
    {
    int x;

    void f () {}
    }
    }
    This fragment defines the class A which contains an static inner class B. A static inner class behaves like any ``outer'' class. It may contain methods and fields, and it may be instantiated like this:
    A.B object = new A.B ();
    This statement creates an new instance of the inner class B.
    Given such an instance, we can invoke the f method in the usual way:
    object.f();
     
    Note:
    It is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.
    The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y.

    Saturday, 25 September 2010

    Sorting a List

    // Create a list
    String[] strArray = new String[] {"z", "a", "C"};
    List list = Arrays.asList(strArray);

    // Sort
    Collections.sort(list); // C, a, z

    // Case-insensitive sort
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z

    // Reverse-order sort
    Collections.sort(list, Collections.reverseOrder()); // z, a, C

    // Case-insensitive reverse-order sort
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
    Collections.reverse(list); // z, C, a

    Tuesday, 21 September 2010

    Some static methods in java.util.Collections

    The java.util.Collections class contains static utility methods for manipulating collections.

    Some useful Collections methods

    Assume the following declarations have been made, where T is a class or interface type.
    int i; 
    List listC; // List of the Comparable objects.
    List list; // Any kind of list. Need not be Comparable.
    Comparator comp;
    T key;
    T t;
    Collection coll; // Any kind of Collection (List, Set, Deque).
    Collection collC; // Any kind of Collection implementing Comparable.
    Rearranging - Sorting, Shuffling, . . .
    Collections.sort(listC) Sorts listC. Elements must be Comparable. Stable, O(N log N).
    Collections.sort(list, comp) Sorts list using a comparator.
    Collections.shuffle(list) Puts the elements of list in random order.
    Collections.reverse(list) Reverses the elements of list.
    Searching
    i = Collections.binarySearch(listC, key) Searches list for key. Returns index of element or negative value if not found. See Binary Search.
    i = Collections.binarySearch(list, key, comp) Searches in list for key using Comparator comp.
    t = Collections.max(collC) Returns maximum valued Comparable object in collC.
    t = Collections.max(coll, comp) Maximum valued object in coll using Comparator comp.
    t = Collections.min(collC) Returns minimum valued Comparable object in collC.
    t = Collections.min(coll, comp) Minimum valued object in coll using Comparator comp.
    There are many additional methods in Collections, but the above are a good start.

    Searching may also be implemented in data structure classes

    All List and Set classes implement the contains() method, which performes a linear search on lists (O(N)), a binary search for TreeSets (O(log N)), and a hashed search for HashSets (O(1)).
    Maps define get() to search for the key. For HashMaps the search is O(1), and for TreeMaps the search is O(log N).

    Sorting may be implicit in a data structure class

    TreeSet data and TreeMap keys are sorted at all times. They are implemented as binary trees, so insertion and search are both O(log N). An iterator can be used to get retrieve the data (TreeSets) or keys (TreeMaps) in sorted order. Either the element class must be Comparable, or a Comparator must be supplied.

    Monday, 21 December 2009

    Static in java

    Static Members
    Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.

    Constants
      Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:
    public class Math
    {
    . . .
    public static final double PI = 3.14159265358979323846;
    . . .
    }
    You can access this constant in your programs as Math.PI.

    If the keyword static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every Math object would have its own copy of PI.

    Another static constant that you have used many times is System.out. It is declared in the System class as:
    public class System
    {
    . . .
    public static final PrintStream out = . . .;
    . . .
    }

    As we mentioned several times, it is never a good idea to have public fields, because everyone can modify them. However, public constants (that is, final fields) are ok. Because out has been declared as final, you cannot reassign another print stream to it:
    System.out = new PrintStream(. . .); // ERROR--out is final

    NOTE:
    If you look at the System class, you will notice a method setOut that lets you set System.out to a different stream. You may wonder how that method can change the value of a final variable. However, the setOut method is a native method, not implemented in the Java programming language. Native methods can bypass the access control mechanisms of the Java language. This is a very unusual workaround that you should not emulate in your own programs.

    Static Methods
    Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression:
    Math.pow(x, a)

    computes the power x^a. It does not use any Math object to carry out its task. In other words, it has no implicit parameter.

    You can think of static methods as methods that don't have a this parameter. (In a non-static method, the this parameter refers to the implicit parameter of the method)

    Because static methods don't operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method:

    public static int getNextId()
    {
    return nextId; // returns static field
    }

    To call this method, you supply the name of the class:
    int n = Employee.getNextId();

    Could you have omitted the keyword static for this method?
    Yes, but then you would need to have an object reference of type Employee to invoke the method.

    NOTE :
    It is legal to use an object to call a static method. For example, if harry is an Employee object, then you can call harry.getNextId() instead of Employee.getnextId(). However, we find that notation confusing. The getNextId method doesn't look at harry at all to compute the result. We recommend that you use class names, not objects, to invoke static methods.

    You use static methods in two situations:
    • When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow)
    • When a method only needs to access static fields of the class (example: Employee.getNextId).

    Also see difference between java and c++ static.
    Points to note about static.




    Tuesday, 15 December 2009

    Nesting of classes : Introduction

    It is possible to define a class within another class; such classes are known as nested classes.

    The scope of a nested class is bounded by the scope of its enclosing class. Also a nested class has access to the members, including private members, of the class in which it is nested. However, the
    enclosing class does not have access to the members of the nested class.

    Consider the case that class B is defined within class A. So it means:
    • B is known to A, but not outside of A. 
    • B as has access to A's members, including private members.
    See types of nested classes .