Showing posts with label initialization. Show all posts
Showing posts with label initialization. Show all posts

Tuesday, 17 May 2011

Anonymous Arrays in java

You can even initialize an anonymous array:

new int[] { 17, 19, 23, 29, 31, 37 }


This expression allocates a new array and fills it with the values inside the braces. It counts the number of initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without creating a new variable. For example,

smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };

is shorthand for

int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;

Note Inefficiency. Be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.


Sunday, 15 May 2011

Static initialization block in java

You initialize a static field either by supplying an initial value or by using a static initialization block. You have already seen the first mechanism:
static int nextId = 1;


If the static fields of your class require complex initialization code, use a static initialization block.

Place the code inside a block and tag it with the keyword static. Here is an example. We want the employee ID numbers to start at a random integer less than 10,000.

// static initialization block

static

{

Random generator = new Random();

nextId = generator.nextInt(10000);

}




Static initialization occurs when the class is first loaded. Like instance fields, static fields are 0, false, or null unless you explicitly set them to another value. All static field initializers and static initialization blocks are executed in the order in which they occur in the class declaration.

Order of initialization in java

With so many ways of initializing data fields, it can be quite confusing to give all possible pathways for the construction process. Here is what happens in detail when a constructor is called.
  1. All data fields are initialized to their default value (0, false, or null).
  2. All field initializers and initialization blocks are executed, in the order in which they occur in the class declaration.
  3. If the first line of the constructor calls a second constructor, then the body of the second constructor is executed.
  4. The body of the constructor is executed.
Naturally, it is always a good idea to organize your initialization code so that another programmer could easily understand it without having to be a language lawyer. For example, it would be quite strange and somewhat error prone to have a class whose constructors depend on the order in which the data fields are declared.

Initialization Blocks in java

You have already seen two ways to initialize a data field:
  • By setting a value in a constructor
  • By assigning a value in the declaration
There is actually a third mechanism in Java; it's called an initialization block. Class declarations can contain arbitrary blocks of code. These blocks are executed whenever an object of that class is constructed. For example,

class Employee

{

public Employee(String n, double s)

{

name = n;

salary = s;

}

public Employee()

{

name = "";

salary = 0;

}

. . .

private static int nextId;


private int id;

private String name;

private double salary;

. . .

// object initialization block

{

id = nextId;

nextId++;

}

}



In this example, the id field is initialized in the object initialization block, no matter which constructor is used to construct an object. The initialization block runs first, and then the body of the constructor is executed.

This mechanism is never necessary and is not common. It usually is more straightforward to place the initialization code inside a constructor.


 

Cpp vs Java in case of direct field initialization

In java, one can directly initialize instance fields of a class. See here for this.

But in C++, you cannot directly initialize instance fields of a class. All fields must be set in a constructor. However, C++ has a special initializer list sytax such as:

Employee::Employee(String n, double s, int y, int m, int d) // C++

: name(n),

salary(s),

hireDay(y, m, d)

{
//some other logic if needed
}

C++ uses this special syntax to call field constructors. In Java, there is no need for it because objects have no sub-objects, only pointers to other objects.

Explicit or direct Field Initialization in java

Because you can overload the constructor methods in a class, you can obviously build in many ways to set the initial state of the instance fields of your classes. It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to something meaningful.
You can simply assign a value to any field in the class definition. For example,
class Employee

{

. . .

private String name = "";

}



This assignment is carried out before the constructor executes. This syntax is particularly useful if all constructors of a class need to set a particular instance field to the same value.

The initialization value doesn't have to be a constant value. Here is an example in which a field is initialized with a method call. Consider an Employee class where each employee has an id field. You can initialize it as follows:

class Employee

{

. . .

static int assignId()

{

int r = nextId;

nextId++;

return r;

}

. . .

private int id = assignId();

}



See cpp vs java in case of direct field initialization.

Difference between fields and local variables

There are few difference between fields and local variables. Fields are defined in the class, whereas local variables are local to the methods. The big difference comes in case of initialization.
You must always explicitly initialize local variables in a method. But if you don't initialize a field in a class, it is automatically initialized to a default (0, false, or null).

Default Field Initialization in java

If you don't set a field explicitly in a constructor, it is automatically set to a default value: numbers to 0, Booleans to false, and object references to null. But it is considered poor programming practice to rely on this. Certainly, it makes it harder for someone to understand your code if fields are being initialized invisibly.
See difference between field variables and local variables.

Sunday, 17 April 2011

Weakhashmap : Using string from literal pool as key

Consider the following code snippet:
public class TestWeakHashMap
{
private String str1 = new String("newString1");
private String str2 = "literalString2";
private String str3 = "literalString3";
private String str4 = new String("newString4");
private Map map = new WeakHashMap();

private void testGC() throws IOException
{
map.put(str1, new Object());
map.put(str2, new Object());
map.put(str3, new Object());
map.put(str4, new Object());

/**
        * Discard the strong reference to all the keys
        */
str1 = null;
str2 = null;
str3 = null;
str4 = null;

while (true) {
System.gc();
/**
            * Verify Full GC with the -verbose:gc option
            * We expect the map to be emptied as the strong references to
            * all the keys are discarded.
            */
System.out.println("map.size(); = " + map.size() + " " + map);
}
}
}

What do we expect the size of the map to be after full GC? I initially thought it should be empty. But it turned out to be 2.

Look at the way the four Strings are initialized. Two of them are defined using the 'new' operator, whereas the other two are defined as literals. The Strings defined using the 'new' operator would be allocated in the Java heap, but the Strings defined defined as literals would be in the literal pool.
The Strings allocated in the literal pool (Perm Space) would never be garbage collected.
This would mean that String 'str2' and 'str3' would always be strongly referenced and the corresponding entry would never be removed from the WeakHashMap.

So next time you create a 'new String()' , put it as a key in a WeakHashMap, and later intern() the String, beware - Your key will always be strongly referenced.

Invoking intern() method on a String will add your String to the literal pool if some other String equal to this String does not exist in the pool
private String str5 = (str4+str1).intern();

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.

Thursday, 24 March 2011

Initialling to zero rather than null

Some classes like BigDecimal,String have empty element into it. So we should use them nicely. Initialize these to zero, rather than null.

public void someFunc(BigDecimal p_number)
{
BigDecimal m_number;
m_number = p_number==null?BigDecimal.Zero : p_number;
}

Extending size of array in java

Once you create an array, java doesn't provide the function to change its size (although you can, of course, change an individual array element). So we can write our own function to expand the array size.
This code shows how to expand array from size it was initialized with to something else.

String[] array = new String[5];
...
array = expand(array, 10);

//func defn
private String[] expand(String[] array, int size) {
String[] temp = new String[size];
System.arraycopy(array, 0, temp, 0, array.length);
for(int j = array.length; j < size; j++)
temp[j] = "";
return temp;
}

Note : If you frequently need to expand the size of an array while a program is running, you should use a different data structure called an array list.See here for array list.

Thursday, 17 February 2011

Static variable initialization

Static variables if not initialized are initialized to 0.

public class Test {
static int age;
public static void main (String args []) {
age = age + 1;
System.out.println("The age is " + age);
}
}
So the above code compiles and runs printing out The age is 1.

Initialization is must in java(@Compile time itself)

Consider the following program:

public class Test {
public static void main (String args []) {
int age;
age = age + 1;
System.out.println("The age is " + age);
}
}
So what will be the outcome of this program?? 

A. Compiles and runs with no output
B. Compiles and runs printing out The age is 1
C. Compiles but generates a runtime error
D. Does not compile
E. Compiles but generates a compile time error


Correct answer is D. So java makes it important to initialize.

Tuesday, 15 February 2011

Lazy initialization

Lazy initialization is a performance optimization. It's used when data is deemed to be 'expensive' for some reason. For example:

  • if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary.
  • since accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.
Lazy initialization has two objectives :
  • delay an expensive operation until it's absolutely necessary
  • store the result of that expensive operation, such that you won't need to repeat it again
As usual, the size of any performance gain, if any, is highly dependent on the problem, and in many cases may not be significant. As with any optimization, this technique should be used only if there is a clear and significant benefit.
To avoid a NullPointerException, a class must self-encapsulate fields that have lazy initialization. That is, a class cannot refer directly to such fields, but must access them through a method.
The hashCode method of an immutable Model Object is a common candidate for lazy initialization.
Example 1
In this example, there are two fields with lazy initialization - fHashCode and fAwards.
import java.util.*;
public final class Athlete {
public Athlete(int aId){
//a toy implementation:
fId = aId;
fName = "Roger Bannister";
//fAwards is not set here!
}
//..elided
/**
Lazy initialization is used here; this assumes that awards
may not always be of interest to the caller,
and that for some reason it is particularly expensive to
fetch the List of Awards.
*/
public List getAwards(){
if ( fAwards == null ) {
//the fAwards field has not yet been populated
//Here is a toy implementation
List<String> awards = new ArrayList<String>();
awards.add( "Gold Medal 2006" );
awards.add( "Bronze Medal 1998" );
fAwards = awards;
}
return fAwards;
}
/**
This style applies only if the object is immutable.
Another alternative is to calculate the hashCode once, when the 
object is initially constructed (again, applies only when object is 
immutable).
*/
@Override public int hashCode(){
if ( fHashCode == 0 ) {
fHashCode = HashCodeUtil.SEED;
fHashCode = HashCodeUtil.hash(fHashCode, fId);
fHashCode = HashCodeUtil.hash(fHashCode, fName);
//self-encapusulated: fAwards is not referenced directly, 
//since it may be null:
fHashCode = HashCodeUtil.hash(fHashCode, getAwards());
}
return fHashCode;
}
// PRIVATE //
private int fId;
private String fName;
private List<String> fAwards;
private int fHashCode;//Cache the hashcode inside the class
} 
Example 2
Here, the look up of the printers available to a desktop PC is treated as an expensive operation.
import java.util.Arrays;
import java.util.List;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.Sides;
/** Printing services available to a desktop client. */
public final class Printers {
/** Print some plain text (perhaps internally converted to PDF). */
void printSomething(String aText, PrintService aPrinter) {
//...elided
}
/** Return the list of printers that can print PDFs (double-sided, portrait).*/
List<PrintService> listAvailablePrinters(){
if(fAvailablePrinters == null){
//double-sided, portrait, for PDF files.
PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add(Sides.DUPLEX);
attrs.add(OrientationRequested.PORTRAIT);
//Expensive operation! This can take several seconds in some environments:
fAvailablePrinters = Arrays.asList(
PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PDF, attrs)
);
}
return fAvailablePrinters;
}
// PRIVATE
/**
Looked up once, the first time it's needed, and then stored using a 
static reference. If it was a non-static reference, then 
the list of available printers would not be looked up just once, 
but perhaps many times (once per 'Printers' object, and not once per 
loaded 'Printers' class).
Self-encapsulate :
If this class's implementation needs to reference this item, it must do 
so indirectly, by calling listAvailablePrinters().  
*/
private static List<PrintService> fAvailablePrinters;
}  
Example 3 Lazy initialization is particularly useful for GUIs which take a long time to construct.
There are several policies for GUI construction which a design may follow:
  • always build - construct the window many times, whenever it is demanded, and do not cache the result.
  • first-request build - construct the window once, when first requested. Cache the result for any further requests, should they occur.
  • background build - construct the window once, in a low priority worker thread, when the system is initialized. Cache the result for any requests, should they occur.
Here is an example of the first-request style, in which the fEditor field has lazy initialization (see the actionPerformed method).
package hirondelle.stocks.preferences;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.logging.*;
import hirondelle.stocks.util.Args;
import hirondelle.stocks.util.ui.StandardEditor;
import hirondelle.stocks.util.ui.UiUtil;
import hirondelle.stocks.preferences.PreferencesEditor;
import hirondelle.stocks.util.Util;
/**
* Present dialog to allow update of user preferences.
*
* <P>Related preferences are grouped together and placed in 
* a single pane of a <tt>JTabbedPane</tt>, which corresponds to an 
* implementation of {@link PreferencesEditor}. Values are pre-populated with 
* current values for preferences.
*
*<P>Most preferences have default values. If so, a  
* <tt>Restore Defaults</tt> button is provided for that set of related 
* preferences.
*
*<P>Preferences are not changed until the <tt>OK</tt> button is pressed. 
* Exception: the logging preferences take effect immediately, without the need 
* for hitting <tt>OK</tt>.
*/
public final class EditUserPreferencesAction extends AbstractAction {
/**
* Constructor.
*  
* @param aFrame parent window to which this dialog is attached.
* @param aPrefEditors contains implementations of {@link PreferencesEditor}, 
* each of which is placed in a pane of a <tt>JTabbedPane</tt>.
*/
public EditUserPreferencesAction (JFrame aFrame, List<PreferencesEditor> aPrefEditors) {
super("Preferences...", UiUtil.getEmptyIcon()); 
Args.checkForNull(aFrame);
Args.checkForNull(aPrefEditors);
fFrame = aFrame;
putValue(SHORT_DESCRIPTION, "Update user preferences");
putValue(LONG_DESCRIPTION, "Allows user input of preferences.");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_P) );    
fPrefEditors = aPrefEditors;
}
/** Display the user preferences dialog.  */
public void actionPerformed(ActionEvent event) {
fLogger.info("Showing user preferences dialog.");
//lazy construction: fEditor is created only once, when this action 
//is explicitly invoked
if ( fEditor == null ) {
fEditor = new Editor("Edit Preferences", fFrame);
}
fEditor.showDialog();
}
// PRIVATE //
private JFrame fFrame;
private java.util.List<PreferencesEditor> fPrefEditors;
private static final Logger fLogger = Util.getLogger(EditUserPreferencesAction.class);  
/**
* Specifying this as a field allows for "lazy" creation and use of the GUI, which is 
* of particular importance for a preferences dialog, since they are usually heavyweight, 
* and have a large number of components.
*/
private Editor fEditor;
/**
* Return GUI for editing all preferences, pre-populated with current 
* values.
*/
private JComponent getPrefEditors(){
JTabbedPane content = new JTabbedPane();
content.setTabPlacement(JTabbedPane.LEFT);
int idx = 0;
for(PreferencesEditor prefEditor: fPrefEditors) {
JComponent editorGui = prefEditor.getUI();
editorGui.setBorder(UiUtil.getStandardBorder());
content.addTab(prefEditor.getTitle() , editorGui);
content.setMnemonicAt(idx, prefEditor.getMnemonic());
++idx;
}
return content;
}
/** Called only when the user hits the OK button.  */
private void saveSettings(){
fLogger.fine("User selected OK. Updating table preferences.");
for(PreferencesEditor prefEditor: fPrefEditors) {
prefEditor.savePreferences();
}
}
/**
* An example of a nested class which is nested because it is attached only 
* to the enclosing class, and it cannot act as superclass since multiple 
* inheritance of implementation is not possible. 
* 
* The implementation of this nested class is kept short by calling methods 
* of the enclosing class.
*/
private final class Editor extends StandardEditor { 
Editor(String aTitle, JFrame aParent){
super(aTitle, aParent, StandardEditor.CloseAction.HIDE);
}
public JComponent getEditorUI () {
JPanel content = new JPanel();
content.setLayout( new BoxLayout(content, BoxLayout.Y_AXIS) );
content.add( getPrefEditors() );
//content.setMinimumSize(new Dimension(300,300) );
return content;
}
public void okAction() {
saveSettings();
dispose();
}
}  
}

Monday, 25 October 2010

2D Array Declaration, Allocation and Initialization

Introduction

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... In practice most arrays are one-dimensional, and two-dimensional (rows and columns) are also quite common. Higher dimensional arrays are less common so they aren't used in the examples, but there's nothing mysterious about them and the same principles apply.
Two-dimensional arrays are used whenever the model data is best represented with rows and columns, or has two varying aspects (eg, gender and age, weight and height, ...). It's also the idea, altho not the implementation, of graphics that specifies a two (or three) dimensional position with an x and y (and z) coordinate.
Terminology. Other terms you will see for a two-dimensional array are matrix or table.

Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach.

Declaration

Two-dimensional arrays are objects. A variable such as gradeTable is a reference to a 2D array object. The declaration

int[][] myArray ;

says that myArray is expected to hold a reference to a 2D array of int. Without any further initialization, 
it starts out holding null.


Allocation


The declaration
int[][] myArray = new int[3][5] ;

says that myArray can hold a reference to a 2D array of int, creates an array object of 3 rows and 5 columns, and puts the reference in myArray. All the cells of the array are initialized to zero. The declaration


int[][] myArray = { 
{0,0,0,0,0}, 
{0,0,0,0,0}, 
{0,0,0,0,0} 
};



does exactly the same thing as the previous declaration (and would not ordinarily be used.)

Initialization


The declaration


int[][] myArray = { 
{8,1,2,2,9}, 
{1,9,4,0,3}, 
{0,3,0,0,7} 
};


creates an array of the same dimensions (same number of rows and columns) as the previous array and initializes the cells to specific values.


Length of 2D array

The length of a 2D array is the number of rows it has. You might guess that "length" could be defined as a number pair (rows, columns). But the number of columns may vary from row to row so this will not work.

eg.
        int arr[][] = new int[2][4];
so arr.length = 2, and arr[0].length=4 i.e. length of row.


(Note we are using length and not length() )
Using .length instead of named constants in 2D arrays(unlike c/cpp)

Named constants make a program very readable, but they may not be available if the array has been passed as a parameter. You can get the size of each dimension with the .length attribute. This is the most general style.
for (int row = 0; row < a2.length; row++) {
       for (int col = 0; col < a2[row].length; col++) {
           output += " " + a2[row][col];
       }
       output += "\n";
} 



Iterating over 2 Dimensional Arrays

Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but the default row-first iteration gives the best performance because "locality of reference" improves the perfomance of cache and virtual memory. It also allows use of the handy foreach loop.

int[][] a2 = new int[ROWS][COLS];

String output = "";   // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
    for (int col = 0; col < COLS; col++) {
        output += " " + a2[row][col];
    }
    output += "\n";
}


foreach style for loop


for (int[] row : a2) {
            for (int val : row) {
                output += " " + val;
            }
            output += "\n";
        }
  

Types of 2D arrays in java


2D arrays in java are of 2 types – even and ragged or uneven arrays.
Defining an even array
Here, Each row of a 2D array may have a same number of cells in the array.

int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];


Defining non-uniform or ragged arrays

Here, each row of a 2D array may have a different number of cells.


int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4]; 


Similarly we can initialized ragged arrays like :

int[][] uneven = 
    { { 1, 9, 4 },
      { 0, 2},
      { 0, 1, 2, 3, 4 } };

Assigning 1D array to row of 2D array

int myArray[][] = new int [4][4];
myArray[0] = new int[] {1, 9, 4,7,8} ;   
int[] x = {1, 7, 4,5,6,7,6,90,4,5,6,7,8,9,0,1,3,4,5} ; // declare and init x
myArray[1]=x;