Saturday, November 26, 2011

Class Definition » This

You use the this keyword from any method or constructor to refer to the current object.
public class Box {
    int length;
    int width;
    int height;
    public Box(int length, int width, int height) {
        this.length = length;
        this.width = width;
        this.height = height;
    }
}
 
http://www.java2s.com/Tutorial/Java/0100
__Class-Definition/0180__This.htm
»»  READMORE...

Friday, November 25, 2011

Class Definition » Initialization Block

A class that contains a static initializer:
class StaticInit
{
    public static int x;

    static
    {
        x = 32;
    }

}
 
Initializing Data Members

public class MainClass {
  static final double PI = 3.14; // Class variable that has a fixed value
  static int count = 0;         // Class variable to count objects


  public void aMethod() {

  }
}
 
Initialization order
class MyClass {
  MyClass(int marker) {
    System.out.println("Tag(" + marker + ")");
  }
}

class MyInit {
  MyClass t1 = new MyClass(1); // Before constructor

  MyInit() {
    System.out.println("Card()");
    t3 = new MyClass(33);
  }

  MyClass t2 = new MyClass(2); // After constructor

  void f() {
    System.out.println("f()");
  }

  MyClass t3 = new MyClass(3); // At end
}

public class MainClass {
  public static void main(String[] args) {
    MyInit t = new MyInit();
    t.f();
  }
}
 
output
Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
 
Using Initialization Blocks:
 A non-static initialization block 
  1. Executed for each object that is created.
  2. Can initialize instance variables in a class.
public class MainClass {
  static int[] values = new int[10];

  {
    System.out.println("Running initialization block.");
    for (int i = 0; i < values.length; i++) {
      values[i] = (int) (100.0 * Math.random());
    }
  }

  void listValues() {

    for (int value : values) {
      System.out.println(value);
    }

  }

  public static void main(String[] args) {
    MainClass example = new MainClass();
    System.out.println("\nFirst object:");
    example.listValues();

    example = new MainClass();
    System.out.println("\nSecond object:");
    example.listValues();
  }
}
Running initialization block.

First object:
35
17
1
10
42
38
42
71
24
7
Running initialization block.

Second object:
45
78
49
9
11
36
0
18
56
38
 
Using Initialization Blocks: 
static initialization block 
  1. A block defined using the keyword static.
  2. Executed once when the class is loaded.
  3. Can initialize only static data members of the class.
public class MainClass {
  static int[] values = new int[10];

  static {
    System.out.println("Running initialization block.");
    for (int i = 0; i < values.length; i++) {
      values[i] = (int) (100.0 * Math.random());
    }
  }

  void listValues() {
    for (int value : values) {
      System.out.println(value);
    }
  }

  public static void main(String[] args) {
    MainClass example = new MainClass();
    System.out.println("\nFirst object:");
    example.listValues();

    example = new MainClass();
    System.out.println("\nSecond object:");
    example.listValues();
  }
}
Running initialization block.

First object:
58
22
49
75
1
35
76
19
27
63

Second object:
58
22
49
75
1
35
76
19
27
63
 
Mixed Initializer 
public class MixedInitializer {
  int i1;
  static int i2;
  int i3 = 2;
  static int i4 = 4;
  {
    System.out.println("i1 = " + i1);
    i1 = 6;
    System.out.println("i1 = 6");
  }
  static {
    System.out.println("i2 = " + i2);

    i2 = 8;

    System.out.println("i2 = 8");
  }

  public static void main(String[] args) {
    System.out.println("main() entered");
    MixedInitializer mi = new MixedInitializer();
    System.out.println("mi.i1 = " + mi.i1);
    System.out.println("i2 = " + i2);
    System.out.println("mi.i3 = " + mi.i3);
    System.out.println("i4 = " + i4);

    System.out.println("main() exited");
  }

  {
    i1 += 6;
    System.out.println("6 + i1");
  }

  static {
    i2 -= 3;
    System.out.println("i2 -= 3");
  }
}
 
Explicit static initialization 
with the static clause
class MyClass {
  MyClass(int marker) {
    System.out.println("Cup(" + marker + ")");
  }

  void f(int marker) {
    System.out.println("f(" + marker + ")");
  }
}

class MyStatic {
  static MyClass c1;

  static MyClass c2;
  static {
    c1 = new MyClass(1);
    c2 = new MyClass(2);
  }

  MyStatic() {
    System.out.println("Cups()");
  }
}

public class MainClass {
  public static void main(String[] args) {
    System.out.println("Inside main()");
    MyStatic.c1.f(99); // (1)
  }
}
Output
Inside main()
Cup(1)
Cup(2)
f(99)
 
The full process of initialization 
class Insect {
  private int i = 1;

  protected int j;

  Insect() {
    System.out.println("i = " + i + ", j = " + j);
    j = 1;
  }

  private static int x1 = print("static Insect.x1 initialized");

  static int print(String s) {
    System.out.println(s);
    return 0;
  }
}

class Beetle extends Insect {
  private int k = print("Beetle.k initialized");

  public Beetle() {
    System.out.println("k = " + k);
    System.out.println("j = " + j);
  }

  private static int x2 = print("static Beetle.x2 initialized");
}

public class MainClass {
  public static void main(String[] args) {
    Beetle b = new Beetle();
  }

}
output
static Insect.x1 initialized
static Beetle.x2 initialized
i = 1, j = 0
Beetle.k initialized
k = 0
j = 1
 
 Demonstrates various initializers
 
/*
 *     file: InitializerDemo.java
 *  package: oreilly.hcj.review
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */


import java.util.StringTokenizer;

/**  
 * Demonstrates various initializers.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.4 $
 */
public class InitializerDemo {
  /** Simple static initialization. */
  public static final String NAME = "Initializer Demo";

  /** Initialized static on one line. */
  public static final String ARCH = System.getProperty("os.arch");

  /** Static method based initialization. */
  public static final String USER_HOME;

  static {
    USER_HOME = System.getProperty("user.home");
  }

  /** Simple instance member initialization. */
  public String description = "An initialized member";

  /** Method call instance member initialization. */
  public long timestamp = System.currentTimeMillis();

  /** Complex instance member initialization. */
  private String xmlClasspath;
  {
    final StringBuffer buf = new StringBuffer(500);
    final String classPath = System.getProperty("java.class.path");
    StringTokenizer tok =
      new StringTokenizer(classPath, System.getProperty("path.separator"));
    buf.append("<classpath>\n");
    while (tok.hasMoreTokens()) {
      buf.append("  <pathelement location=\"");
      buf.append(tok.nextToken());
      buf.append("\"/>\n");
    }
    buf.append("</classpath>");
    xmlClasspath = buf.toString();
  }

  /** 
   * Creates a new instance of Initalizers
   */
  public InitializerDemo() {
  }

  /** 
   * Main method of the demonstration.
   *
   * @param args Command line arguments (ignored).
   */
  public static final void main(final String[] args) {
    InitializerDemo demo = new InitializerDemo();
    System.out.println("------Dumping Contents-----------");
    System.out.println("---------------------------------");
    System.out.println(InitializerDemo.NAME);
    System.out.println(InitializerDemo.ARCH);
    System.out.println(InitializerDemo.USER_HOME);
    System.out.println(demo.description);
    System.out.println(demo.xmlClasspath);
    System.out.println("---------------------------------");
  }
}

/* ########## End of File ########## */
 
 Demonstrates the pitfalls of depending on the 
order of static initializers
/*
 *     file: StaticOrderDemo.java
 *  package: oreilly.hcj.review
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */


import java.util.Arrays;

/**  
 * Demonstrates the pitfalls of depending on the order of static initializers.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.3 $
 */
public class StaticOrderDemo {
  static {
    Class cl = Values.class;
    System.out.println("Class " + cl.getName() + " Loaded");
  }

  /** 
   * Creates a new instance of StaticOrderDemo
   */
  public StaticOrderDemo() {
  }

  /** 
   * The main demo method.  Used only to start the virtual machine.
   *
   * @param args Arguments passed.
   */
  public static final void main(final String[] args) {
  }

  // --- Inner Classes --

  /**  
   * Holds ranges for the values.
   *
   * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
   * @version $Revision: 1.3 $
   */
  public static class Ranges {
    /** Bluw range */
    public static final String[] RANGE_BLUE = { "Sky", "Navy" };

    /** Red range */
    public static final String[] RANGE_RED = { "Light", "Dark" };

    static {
      System.out.println("static{} method for Ranges");
      System.out.println(Arrays.asList(RANGE_BLUE));
      System.out.println(Values.VALUE_SPECIFIER);
      System.out.println(Arrays.asList(RANGE_RED));
    }
  }

  /**  
   * Holds values.
   *
   * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
   * @version $Revision: 1.3 $
   */
  public static class Values {
    /** A value holder */
    public static final String VALUE = "Blue";

    /** A specifier for the value */
    public static final String VALUE_SPECIFIER;

    static {
      System.out.println("static{} method for Values");
      System.out.println(VALUE);
      System.out.println(Ranges.RANGE_BLUE);
      VALUE_SPECIFIER = Ranges.RANGE_BLUE[1];
    }
  }
}

/* ########## End of File ########## */

http://www.java2s.com/Tutorial/Java/0100__
Class-Definition/Catalog0100__Class-Definition.htm
 
»»  READMORE...

Thursday, November 24, 2011

Class Definition » Recursive Method

Recursion: a method (function) calls itself
Characteristics of Recursive Methods:
  1. Method calls itself.
  2. When it calls itself, it solves a smaller problem.
  3. There is a smallest problem that the routine can solve it, and return, without calling itself.
public class MainClass {
  public static void main(String[] args) {
    int theAnswer = triangle(12);
    System.out.println("Triangle=" + theAnswer);
  }

  public static int triangle(int n) {
    if (n == 1)
      return 1;
    else
      return (n + triangle(n - 1));
  }
}
output
Triangle=78
 
The Towers of Hanoi
 
public class MainClass {
  public static void main(String[] args) {
    int nDisks = 3;
    doTowers(nDisks, 'A', 'B', 'C');
  }

  public static void doTowers(int topN, char from, char inter, char to) {
    if (topN == 1){
      System.out.println("Disk 1 from " + from + " to " + to);
    }else {
      doTowers(topN - 1, from, to, inter);
      System.out.println("Disk " + topN + " from " + from + " to " + to);
      doTowers(topN - 1, inter, from, to);
    }
  }
}
 output
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C 

Recursion: another example 
public class MainClass {
  public static void main(String[] args) {
    double x = 5.0;
    System.out.println(x + " to the power 4 is " + power(x, 4));
    System.out.println("7.5 to the power 5 is " + power(7.5, 5));
    System.out.println("7.5 to the power 0 is " + power(7.5, 0));
    System.out.println("10 to the power -2 is " + power(10, -2));
  }

  // Raise x to the power n
  static double power(double x, int n) {
    if (n > 1)
      return x * power(x, n - 1); // Recursive call
    else if (n < 0)
      return 1.0 / power(x, -n); // Negative power of x
    else
      return x;
  }
}
output
5.0 to the power 4 is 625.0
7.5 to the power 5 is 23730.46875
7.5 to the power 0 is 7.5
10 to the power -2 is 0.01
 
 Recursive factorial method 
public class MainClass {
  public static void main(String args[]) {
    for (int counter = 0; counter <= 10; counter++)
      System.out.printf("%d! = %d\n", counter, factorial(counter));

  }

  // recursive declaration of method factorial
  public static long factorial(long number) {
    if (number <= 1) // test for base case
      return 1; // base cases: 0! = 1 and 1! = 1
    else
      // recursion step
      return number * factorial(number - 1);
  }
}
output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Recursive fibonacci method 
public class MainClass {
  // recursive declaration of method fibonacci
  public static long fibonacci(long number) {
    if ((number == 0) || (number == 1)) // base cases
      return number;
    else
      // recursion step
      return fibonacci(number - 1) + fibonacci(number - 2);
  }

  public static void main(String[] args) {
    for (int counter = 0; counter <= 10; counter++)
      System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
  }
}
output
Fibonacci of 0 is: 0
Fibonacci of 1 is: 1
Fibonacci of 2 is: 1
Fibonacci of 3 is: 2
Fibonacci of 4 is: 3
Fibonacci of 5 is: 5
Fibonacci of 6 is: 8
Fibonacci of 7 is: 13
Fibonacci of 8 is: 21
Fibonacci of 9 is: 34
Fibonacci of 10 is: 55
 
Recursive method to find all permutations of a String 
public class MainClass {
  public static void main(String args[]) {
    permuteString("", "String");
  }

  public static void permuteString(String beginningString, String endingString) {
    if (endingString.length() <= 1)
      System.out.println(beginningString + endingString);
    else
      for (int i = 0; i < endingString.length(); i++) {
        try {
          String newString = endingString.substring(0, i) + endingString.substring(i + 1);

          permuteString(beginningString + endingString.charAt(i), newString);
        } catch (StringIndexOutOfBoundsException exception) {
          exception.printStackTrace();
        }
      }
  }
}
output
String Strign Strnig Strngi Strgin Strgni Stirng Stirgn Stinrg Stingr Stigrn Stignr Stnrig Stnrgi Stnirg Stnigr Stngri Stngir Stgrin Stgrni Stgirn Stginr Stgnri Stgnir Srting Srtign Srtnig Srtngi Srtgin Srtgni Sritng Sritgn Srintg Sringt Srigtn Srignt Srntig Srntgi Srnitg Srnigt Srngti Srngit Srgtin Srgtni Srgitn Srgint Srgnti Srgnit Sitrng Sitrgn Sitnrg Sitngr Sitgrn Sitgnr Sirtng Sirtgn Sirntg Sirngt Sirgtn Sirgnt Sintrg Sintgr Sinrtg Sinrgt Singtr Singrt Sigtrn Sigtnr Sigrtn Sigrnt Signtr Signrt Sntrig Sntrgi Sntirg Sntigr Sntgri Sntgir Snrtig Snrtgi Snritg Snrigt Snrgti Snrgit Snitrg Snitgr Snirtg Snirgt Snigtr Snigrt Sngtri Sngtir Sngrti Sngrit Sngitr Sngirt Sgtrin Sgtrni Sgtirn Sgtinr Sgtnri Sgtnir Sgrtin Sgrtni Sgritn Sgrint Sgrnti Sgrnit Sgitrn Sgitnr Sgirtn Sgirnt Sgintr Sginrt Sgntri Sgntir Sgnrti Sgnrit Sgnitr Sgnirt tSring tSrign tSrnig tSrngi tSrgin tSrgni tSirng tSirgn tSinrg tSingr tSigrn tSignr tSnrig tSnrgi tSnirg tSnigr tSngri tSngir tSgrin tSgrni tSgirn tSginr tSgnri tSgnir trSing trSign trSnig trSngi trSgin trSgni triSng triSgn trinSg tringS trigSn trignS trnSig trnSgi trniSg trnigS trngSi trngiS trgSin trgSni trgiSn trginS trgnSi trgniS tiSrng tiSrgn tiSnrg tiSngr tiSgrn tiSgnr tirSng tirSgn tirnSg tirngS tirgSn tirgnS tinSrg tinSgr tinrSg tinrgS tingSr tingrS tigSrn tigSnr tigrSn tigrnS tignSr tignrS tnSrig tnSrgi tnSirg tnSigr tnSgri tnSgir tnrSig tnrSgi tnriSg tnrigS tnrgSi tnrgiS tniSrg tniSgr tnirSg tnirgS tnigSr tnigrS tngSri tngSir tngrSi tngriS tngiSr tngirS tgSrin tgSrni tgSirn tgSinr tgSnri tgSnir tgrSin tgrSni tgriSn tgrinS tgrnSi tgrniS tgiSrn tgiSnr tgirSn tgirnS tginSr tginrS tgnSri tgnSir tgnrSi tgnriS tgniSr tgnirS rSting rStign rStnig rStngi rStgin rStgni rSitng rSitgn rSintg rSingt rSigtn rSignt rSntig rSntgi rSnitg rSnigt rSngti rSngit rSgtin rSgtni rSgitn rSgint rSgnti rSgnit rtSing rtSign rtSnig rtSngi rtSgin rtSgni rtiSng rtiSgn rtinSg rtingS rtigSn rtignS rtnSig rtnSgi rtniSg rtnigS rtngSi rtngiS rtgSin rtgSni rtgiSn rtginS rtgnSi rtgniS riStng riStgn riSntg riSngt riSgtn riSgnt ritSng ritSgn ritnSg ritngS ritgSn ritgnS rinStg rinSgt rintSg rintgS ringSt ringtS rigStn rigSnt rigtSn rigtnS rignSt rigntS rnStig rnStgi rnSitg rnSigt rnSgti rnSgit rntSig rntSgi rntiSg rntigS rntgSi rntgiS rniStg rniSgt rnitSg rnitgS rnigSt rnigtS rngSti rngSit rngtSi rngtiS rngiSt rngitS rgStin rgStni rgSitn rgSint rgSnti rgSnit rgtSin rgtSni rgtiSn rgtinS rgtnSi rgtniS rgiStn rgiSnt rgitSn rgitnS rginSt rgintS rgnSti rgnSit rgntSi rgntiS rgniSt rgnitS iStrng iStrgn iStnrg iStngr iStgrn iStgnr iSrtng iSrtgn iSrntg iSrngt iSrgtn iSrgnt iSntrg iSntgr iSnrtg iSnrgt iSngtr iSngrt iSgtrn iSgtnr iSgrtn iSgrnt iSgntr iSgnrt itSrng itSrgn itSnrg itSngr itSgrn itSgnr itrSng itrSgn itrnSg itrngS itrgSn itrgnS itnSrg itnSgr itnrSg itnrgS itngSr itngrS itgSrn itgSnr itgrSn itgrnS itgnSr itgnrS irStng irStgn irSntg irSngt irSgtn irSgnt irtSng irtSgn irtnSg irtngS irtgSn irtgnS irnStg irnSgt irntSg irntgS irngSt irngtS irgStn irgSnt irgtSn irgtnS irgnSt irgntS inStrg inStgr inSrtg inSrgt inSgtr inSgrt intSrg intSgr intrSg intrgS intgSr intgrS inrStg inrSgt inrtSg inrtgS inrgSt inrgtS ingStr ingSrt ingtSr ingtrS ingrSt ingrtS igStrn igStnr igSrtn igSrnt igSntr igSnrt igtSrn igtSnr igtrSn igtrnS igtnSr igtnrS igrStn igrSnt igrtSn igrtnS igrnSt igrntS ignStr ignSrt igntSr igntrS ignrSt ignrtS nStrig nStrgi nStirg nStigr nStgri nStgir nSrtig nSrtgi nSritg nSrigt nSrgti nSrgit nSitrg nSitgr nSirtg nSirgt nSigtr nSigrt nSgtri nSgtir nSgrti nSgrit nSgitr nSgirt ntSrig ntSrgi ntSirg ntSigr ntSgri ntSgir ntrSig ntrSgi ntriSg ntrigS ntrgSi ntrgiS ntiSrg ntiSgr ntirSg ntirgS ntigSr ntigrS ntgSri ntgSir ntgrSi ntgriS ntgiSr ntgirS nrStig nrStgi nrSitg nrSigt nrSgti nrSgit nrtSig nrtSgi nrtiSg nrtigS nrtgSi nrtgiS nriStg nriSgt nritSg nritgS nrigSt nrigtS nrgSti nrgSit nrgtSi nrgtiS nrgiSt nrgitS niStrg niStgr niSrtg niSrgt niSgtr niSgrt nitSrg nitSgr nitrSg nitrgS nitgSr nitgrS nirStg nirSgt nirtSg nirtgS nirgSt nirgtS nigStr nigSrt nigtSr nigtrS nigrSt nigrtS ngStri ngStir ngSrti ngSrit ngSitr ngSirt ngtSri ngtSir ngtrSi ngtriS ngtiSr ngtirS ngrSti ngrSit ngrtSi ngrtiS ngriSt ngritS ngiStr ngiSrt ngitSr ngitrS ngirSt ngirtS gStrin gStrni gStirn gStinr gStnri gStnir gSrtin gSrtni gSritn gSrint gSrnti gSrnit gSitrn gSitnr gSirtn gSirnt gSintr gSinrt gSntri gSntir gSnrti gSnrit gSnitr gSnirt gtSrin gtSrni gtSirn gtSinr gtSnri gtSnir gtrSin gtrSni gtriSn gtrinS gtrnSi gtrniS gtiSrn gtiSnr gtirSn gtirnS gtinSr gtinrS gtnSri gtnSir gtnrSi gtnriS gtniSr gtnirS grStin grStni grSitn grSint grSnti grSnit grtSin grtSni grtiSn grtinS grtnSi grtniS griStn griSnt gritSn gritnS grinSt grintS grnSti grnSit grntSi grntiS grniSt grnitS giStrn giStnr giSrtn giSrnt giSntr giSnrt gitSrn gitSnr gitrSn gitrnS gitnSr gitnrS girStn girSnt girtSn girtnS girnSt girntS ginStr ginSrt gintSr gintrS ginrSt ginrtS gnStri gnStir gnSrti gnSrit gnSitr gnSirt gntSri gntSir gntrSi gntriS gntiSr gntirS gnrSti gnrSit gnrtSi gnrtiS gnriSt gnritS gniStr gniSrt gnitSr gnitrS gnirSt gnirtS
 
 http://www.java2s.com/Tutorial/Java/0100__Class-Definition/Catalog0100__Class-Definition.htm
»»  READMORE...