Archive for the ‘Java example’ Category

Java Basics code and rules

February 17, 2014

Components of a class:

Package statement

Import statements

/*
  Comments
*/

class declaration {
  Variables
  //Comments
  Constructors()
  Methods()
  Nested classes {}
  Nested interfaces {}
  Enum
}

A comment can precede a package statement.

Class declaration:

Compulsory:

Keyword class – case sensitive
Name of the class
class body – {}

Optional:

Access modifier, e.g. public
Nonaccess modifier, e.g. final
Keyword extends
Keyword implements

Within a class you have:

Variables, these are instance variables or instance attributes – apply to the object only
Methods, used to manipulate the instance variables
Constructors, used to create and initialise the objects of a class

You can define a class in a single file or multiple classes in one file, these (classes and interfaces) can be defined in any order.

If you have a file (example.java) with the following:

interface myInterface1 {

}
class MyClass1 {

}
interface myInterface2 {

}
public class MyClass2 {

}
public interface myInterface3 {

}

This will NOT compile because:
1 – defining a public class of MyClass2 should be in a file of MyClass2.java
2 – defining a public interface myInterface3 should be in a file of myInterface3.java

You can either:

1 – rename the class and interface to example
2 – change the access to non-public

Example:

interface myInterface1 {

}
class MyClass1 {

}
interface myInterface2 {

}
class MyClass2 {

}
public interface example {

}

Only one package per source file.

Executable classes are those which contain a main method.

public class MyExecutableClass {
       public static void main(String args[]) {
            System.out.println("Hello, I am an executable class!!!");
       }
}

main method rules:
Must be public
Must be static
Must be named main
Must be a void
Must accept String array or variable e.g.

public class MyExecutableClass {
	public static void main(String... args) { 
		System.out.println("Hello, I am an executable class!!!");
	}
}

Other examples:

public static void main(String[] callMeAnything)
public static void main(String callMeAnything[])

//Also this works
static public void main(String callMeAnything[])

These produce errors:

//This is a runtime error
static public void main(String[] arguments[])
//This is a compile error
static void public main(String args[])
Packages

The rules:
package names should be lowercase
package and subpackage names separated by ‘.’
com is commercial, followed by company name, then categories and subcategories
package statement is the first in a source file (classes and interfaces) //Comments can appear though
one package statement per file
All classes and interfaces belong to the package defined in the file

The import statement enables you to use simple names instead of using fully qualified names.

importing classes with the same name won’t compile:

import java.util.Date;
import java.sql.Date;

class example {
     
}

Unlike C or C++ importing a class doesn’t add to the size of a .class file.

import java.util.*  //imports all classes and interfaces

However it is not recursive, you cannot import classes / interfaces from a subpackage with the *.

If you don’t specify a package then there is the default package, so if the class is in the same directory it can be referenced, e.g.:

filename person.java

class person {

}

filename house.java

class house {
     person p;
}

This compiles because the files are in the same directory (or referenced) e.g.:

javac tt/person.java house.java //this compiles

import static used to import individual static members of a class, e.g.

import static java.lang.Math.PI;

public class example {
    public static void main(String[] args) {
         System.out.println(PI);
   }
}
Access modifiers

There are four access modifiers:

public
protected
default
private

Public access table:

Anyone can see.

Same package Separate package
Derived classes true true
Unrelated classes true true

Protected access table:

Accessible only to classes and interfaces in the same package
And all derived classes

Example:

file …/people/Person.java

package people;

public class Person {
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();

           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes true true
Unrelated classes true false

Default access table:

Only accessible to classes and interfaces in the same package.

file …/people/Person.java

package people;

public class Person {
     int age;
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();
           p.age = 100; //compile error as this is default, we are in a different package
           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes true false
Unrelated classes true false

If you define a class as default, it cannot be accessed outside of that package (the default one) – like an inaccessible island.

Private access table:

Private members defined within a class are only accessible within that class.

file …/people/Person.java

package people;

public class Person {
     private void countHairs() {}
     int age;
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();
           p.countHairs(); //compile error as this is a private to Person
           p.age = 100; //compile error as this is default, we are in a different package
           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes false false
Unrelated classes false false
Nonaccess modifiers

Specifically:

abstract
final
static

Abstract

prefixing abstract to the definition of a class makes it a abstract class, which cannot be instantiated. A abstract class may or may not have abstract methods.

An interface is an abstract object by default. The compiler adds abstract to the definition of an interface, you can if you want.

An abstract method does not have a body:

abstract class example {
    private string name;
    public void getName() {}  //This is NOT an abstract method, it has an empty body
    public abstract void jump();  //This is a abstract method
}

Final

A class marked as final cannot be extended by another class:

final class Person {}
class Worker extends Person {}
//This code will not compile because Person is final

An interface cannot be marked final, it is abstract.

A final variable is assigned a value once, and cannot be changed. You can call methods on a final variable e.g.

class Example {
    final StringBuilder test = new StringBuilder("abc");
    Example() {
        test.append("xyz"); //all fine
        test = new StringBuilder();  //Won't compile!
    }
}

A final method in a base case cannot be overwritten e.g.

  class Person {
    final void greeting() {
        System.out.println("Why hello there");
    }
  }

  class Worker extends Person {
    void greeting() {
        System.out.println("How do");  //This fails to compile
    }
  }
}

Static

Makes the variable in a class applicable to all instances of the class, e.g.

class Example {
   String name;
   static int amount;
}

class test {
   public static void main(String[] args) {
       Example e1 = new Example();
       Example e2 = new Example();

       e1.name = "Example One";
       e2.name = "Example Two";

       e1.amount = 100;
       e2.amount = 200;

       System.out.println(e1.name);     //This will print Example One
       System.out.println(e2.name);     //This will print Example Two
       System.out.println(e1.amount);   //This will print 200
       System.out.println(e2.amount);  //This will print 200
       System.out.println(Example.amount);  //What does this print? Well it prints 200!
   }
}

Static and final can be used to define a constant:

class Example {
     public static final int WIDTH = 100;  //This is standard practice for constants
}

class Test {
    public static void Main (String[] args) {
         int w = Example.WIDTH;
    }
}

Static Methods

class Example {
    String name;
    private static int amount;

    static int getAmount() {
        return amount;
    }
}

Static methods and variables cannot access non-static variables:

class Example_static {
   String name;

   String getName() {
      return name;
   }

   static String staticName = getName();  //This fails to compile!
}

However, non-static can access static:

class Example_static {
   String name;
   private static int amount;

   static int getAmount() {
      return amount;
   }

   int nonStaticGetAmount() {
       return amount;
   }
}

Static methods/variables cannot access the instance members.

reference: http://www.manning.com/gupta/

Advertisements

Java Data types code and rules

February 17, 2014

Primitive variables

Boolean

boolean result = false;

Only have two states, true or false.

Numeric (Integers and Floating point)

Integers made up of byte, int, short, long

type bits min/max value
byte 8 -128 to 127
short 16 -32,768 to 32,767
int 32 -2,147,483,648 to 2,147,483,647
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

You can store integers in four bases:

Base value range example
2, binary 0 and 1
int binaryValue = 0b1011;
8, octal 0 and 7
int octalValue = 0413;
10, decimal 0 and 9
int decimalValue = 10;
16, hex 0 and 9 and A to F
int hexValue = 0x1B;

To help, Java 7 allows the use of underscores in the values, making it more readable:

class Example_intergers {
	public static void main(String[] args) {
		long valueDecimal=101_256_202;
		System.out.println("101_256_202 == "+valueDecimal);  //101256202
		long valueOct=04_21;
		System.out.println("04_21 == "+valueOct);  //273
		long valueHex=0x20_CD_89;
		System.out.println("0x20_CD_89 == "+valueHex);  //2149769
		long valueBin=0b10_11;
		System.out.println("0b10_11 == "+valueBin);  //11
	}
}

There are rules for these underscores:

int lit1 = _100;  // Cannot start
int lit2 = 100_;  // or end with a underscore!

long lit3 = 999_L; //cannot place before suffix

long octV = 0_4; //cannot place straight after 0 prefix for Octal

long binV = 0b_1; //cannot place straight after 0b prefix
long hexV = 0x_CD; //cannot place straight after 0x prefix

int t = Integer.parseInt("1234_567"); //cannot use in string of digits

further examples:

//Which of these will work?
long v0 = 0_100_267_760; //This is fine
//long v1 = 0_x_4_13; //No - compile error == ';' expected, illegal underscore
//long v2 = 0b_x10_BA_75; //No - compile error == binary numbers must contain at least one binary digit, not a statement, illegal underscore
//long v3 = 0b_10000_10_11; //No - compile error == illegal underscore
//long v4 = 0xa10_AG_75; //No, not valid hex (G) - compile error == ';' expected
long v5 = 0x1_0000_10; //fine
long v6 = 100__12_12; //double __ but think it is still valid?

Floating-Point (float and double) numbers

type bits min/max value
float 32 +/-1.4E-45 to +/-3.4028235E+38
double 64 +/-4.9E-324 to +/-1.7976931348623157E+308

You can tell the compiler it is a float:

float v1 = 100.9824F;  //All floats must be declared with F or f
float v2 = 1833.23456f;
double v3 = 42356.23456;

//You can use scientific notation
double v4 = 123.1882e2;

//You can use those underscores again

float v5 = 1_000_000.45678f;

float v6 = 1_000_000._45678f; //cannot use next to decimal point
float v7 = 1_000_000_.45678F; //as above

float v8 = 1_000_000.45678_f; //cannot use next to suffix f or d

Character

Stores a single 16-bit Unicode character. Stored as a unsigned integer.

Examples are:

char v1 = 'T';
char v2 = 123;  //should be positive, negative fails to compile
char v3 = '\u0123';

variable names:

int EXAMPLE-V1; //won't compile because of hyphen
int example.v2; //won't compile because of '.'
int %example;   //won't compile because of %

int $example; //works
int _example; //works

Object reference variables

class Example {}

Example e0 = new Example();

//e0 is the object reference variable - which is the heap-memory address value to the object

int v0 = 100; //this value is stored in memory, rather than the reference

Operator assignment

class Assignment {

	static int v1 = 10;
	static int v2 = v1;

	static void showValues() {
		System.out.println("v1 == "+v1);
                System.out.println("v2 == "+v2);
	}

	public static void main(String[] args) {

		showValues(); // v1 == 10 v2 == 10

		v2 += v1;
		System.out.println("v2 += v1");
		showValues(); // v1 == 10 v2 == 20
		
		v1 = v2 = 10;
		showValues(); // v1 == 10 v2 == 10

		v2 *= v1;
		System.out.println("v2 *= v1");
		showValues(); // v1 == 10 v2 == 100

		v1 = v2 = 10;
		showValues(); // v1 == 10 v2 == 10

		v2 /= v1;
		System.out.println("v2 /= v1");
		showValues(); // v1 == 10 v2 == 1

	}
}

Invalid assignments

double v1 = true; //no can do!
boolean v2 = 'c'; //no can do!
boolean v3 = 0; //no can do!
boolean v4 -= v3; //no can do (you can't add or subtract booleans)

long v5 = 123456789012L;
int v6 = v5; //no can do

int v7 = 1234;
long v8 = v7; //all good

boolean v9 = true;
int v10 = v9; //no can do

More examples

public class ExampleAssignment {
	public static void main (String[] args) {
		boolean v1, v2, v3, v4, v5, v6; //all fine
		v1 = v2 = v3 = true; //all fine
		v4 = 0; //no can do!
		v5 = 'false' //no can do!
		v6 = yes; //no can do!
	}
}

Arithmetic operators

class Assignment {

	static int v1;
	static int v2;

	static double d1;
	static double d2;

	static void setIntValues() {
		v1 = 20;
		v2 = 10;
	}

	static void setDoubleValues() {
		d1 = 20.0;
		d2 = 10.0;
	}

	static void showIntValues() {
		System.out.println("v1 == "+v1);
                System.out.println("v2 == "+v2);
	}

	static void showIntValues(int v) {
		showIntValues();
		System.out.println("v3 == "+v);
	}

	static void showDoubleValues() {
		System.out.println("d1 == "+d1);
                System.out.println("d2 == "+d2);
	}

	static void showDoubleValues(double v) {
		showDoubleValues();
		System.out.println("d3 == "+v);
	}


	public static void main(String[] args) {

		setIntValues();
		showIntValues(); // v1 == 10 v2 == 20

		++v1;
		v2++;
		System.out.println("++v1 and v2++");
		showIntValues(); // v1 == 21 v2 == 11 - they are not part of an expression so behave the same way
		
		setIntValues();
		int v3 = v1 - ++v2;
		System.out.println("v1 - ++v2");
		showIntValues(v3); // v1 == 20 v2 == 11 v3 == 9

		setIntValues();

		v3 = v1 - v2++;
		System.out.println("v1 - v2++");
		showIntValues(v3); // v1 == 20 v2 == 11 v3 == 10

		

		setDoubleValues();
		double d3 = d1 * d2--;
		System.out.println("d1 * d2--");
		showDoubleValues(d3); // d1 == 20.0 d2 == 9.0 d3 == 200.0


		setDoubleValues();
		d3 = d1 * --d2;
		System.out.println("d1 * --d2");
		showDoubleValues(d3); // d1 == 20.0 d2 == 9.0 d3 == 180.0

		int z = 10;
		z = z++ + z + z-- - z-- + ++z;
		//equivalent to
		//10 + 11 + 11 - 10 + 10
		System.out.println("z == "+z);  //32

		z = 10;
		z = ++z + z + --z - --z + z++;
		//equivalent to
		//11 + 11 + 10 - 9 + 9
		System.out.println("z == "+z);  //32
		
	}
}

Relational operators

class RelationalExample {
	public static void main (String[] args) {
		int v1 = 10;
		int v2 = 20;

		long v3 = 10;
		long v4 = 20;

                boolean v5 = false;

		System.out.println("v1 >= v2 is "+(v1 >= v2)); //prints false

		System.out.println("v4 >= v3 is "+(v4 >= v3)); //prints true

		//Cannot compare different types, e.g. String versus long

		System.out.println("v1 == v2 is "+(v1 == v2)); //false
		System.out.println("v1 != v2 is "+(v1 != v2)); //true

		System.out.println("v5 == true is "+(v5 == true)); //false
		System.out.println("v5 != true is "+(v5 != true)); //true

		System.out.println("v5 == false is "+(v5 == false)); //true
		System.out.println("v5 != false is "+(v5 != false)); //false

		System.out.println("v5 = true is "+(v5 = true)); //true
		System.out.println("v5 = false is "+(v5 = false)); //false
	}
}

Logical operators

class LogicalExamples {
	public static void main(String[] args) {
		int v1 = 10;
		int v2 = 20;
		
		System.out.println("10 > 20 && 20 > 10 is "+(v1 > 20 && v2 > 10)); //prints false
		System.out.println("10 > 20 || 20 > 10 is "+(v1 > 20 || v2 > 10)); //prints true

		System.out.println("!(20 > 10) is "+(!(v2 > 10))); //prints false
		System.out.println("!(10 > 20) is "+(!(v1 > 20))); //prints true

		//Logical AND (&&) is true if ALL operands equates to true
		//Logical OR (||) is true if ONE operands equates to true
		//Logical NOT (!) is true if operand is false (i.e. the oposite)

		int v3 = 80;
		int v4 = 100;

		System.out.println(v3+", "+v4); //80, 100
		System.out.println("v4 < v3 AND ++v3 > 50 is "+(v4 < v3 && ++v3 > 50)); //false
		System.out.println(v3); //80
		System.out.println("v4 == 100 OR ++v3 > 100 is "+(v4 == 100 || ++v3 > 100)); //true
		System.out.println(v3); //80
		
		//Reason v3 does not get touched, lazy evaluation, once you know one you don't need to do the rest

		int a = 10;
		int b = 20;
		int c = 40;
		
		System.out.println(a++ > 10 || ++b < 30); //true
		 
		System.out.println(" a == "+a+", b == "+b+", c == "+c); //a will be 11, b 21, c40
		
		System.out.println(a > 90 && ++b < 30); //false a still 11 b not touched
		
		System.out.println(" a == "+a+", b == "+b+", c == "+c); //a will be 11, b 21, c40
		
		System.out.println(!(c>20) && a==10); //false a not evaluated
		
		System.out.println(" a == "+a+", b == "+b+", c == "+c); //a will be 11, b 21, c40
		
		System.out.println(a >= 99 || a <=30 && b == 10); //false
		
		System.out.println(" a == "+a+", b == "+b+", c == "+c);	//a will be 11, b 21, c40	
		
		System.out.println(a >= 99 && a <= 33 || b == 10); //false
		
		System.out.println(" a == "+a+", b == "+b+", c == "+c);	//a will be 11, b 21, c40	
	}
}

Operator precedence

Order is

  • Postfix
  • Unary
  • Multiplication
  • Addition
  • Relational
  • Equality
  • Logical AND
  • Logical OR
  • Assignment
  • int a = 10, b = 20, c = 30;
    System.out.println(a % b * c + a / b);
    
    /*
    
    (((a % b) * c)) + (a / b)
    (((10 % 20) * 30)) + (10 / 20)
    ( (10       * 30)) + (0)
    (300)
    
    */
    
    //You can use parentheses to change the order
    
    System.out.println(a % b * (c + a) / b);
    
    /*
    ((10 % 20) * ((30 + 10) / 20)
    ((10     ) * ( 40       / 20)
    ((10     ) * ( 2            )
    (20)
    */
    

    reference: http://www.manning.com/gupta/

    Java Methods and encapsulation

    December 16, 2013

    Scope of variables

    Local variables
    class Example {
         private int v1; //instance variable
         public int getValue() {
              int res = 0;   //local variable
              res = 10*12;
              return res;
         }
    
        public void setValue(int value) {
             res = value;   //This will not compile as res only exists within getValue()
        }
    
        public int getAnotherValue() {
             if (v1 > 100) {
                 int res2 = 100;    //local variable, to the if!
                 res2 = res2 * v1;
                 return res2;
             }
             else {
                 res2 = 0;       //won't compile, this variable is not available.
                 return res2;
             }
        }
    
        public int getAnotherExample() {
             for (int counter = 0; counter < 5; counter++) {
                 System.out.println(v1*counter);
             }
             System.out.println("Counter is "+counter); //will not compile as counter is only available to the for loop
        }
    }
    
    Method parameters
    class Example {
        private int v1;
        public void setValue(int value) { //this is a method parameter
            v1 = value;                   //it is only available in this method
        }
    
        public int getValueExample(int value) {  //method parameter
            int res = 100;                       //local variable
            res = (res * v1)/value;
            return res;
        }
    }
    
    Instance variables
    class Example {
         private int v1;                    //instance variable
         public void setValue(int value) {
             v1 = value;                    //instance variable set by method parameter
         }
    
         public int getValue() {
            return v1;                     //instance variable returned
         }
    }
    
    Class variables

    These belong to a class, not to the objects of the class. They are static, this defines them as a class variable.

    
    package com.demo;
    
    class Example {
        static int v1 = 0;
    }
    
    package com.demo;
    
    class Test {
        public static void main(String[] args) {
             Example.v1 = 100;
    
             Example e1 = new Example();
             Example e2 = new Example();
    
             System.out.println(e1.v1);  //prints 100
             System.out.println(e2.v1);  //prints 100
    
        }
    }
    

    Some rules:

  • local variables are normally used within a method as part of a calculation, storing the intermediate results
  • method parameters are used to pass in values
  • instance variables are used to return/set the state of the object
  • class variables used to store values against the class, which applies to all objects of the class
  • Scope of variables

    Local variables have the shortest scope, and class variables the longest, after local you have method and instance variables.

    You cannot define a static variable and instance variable with the same name.
    Local and method variables also cannot have the same name
    You CAN define local variables with the same name as instance and class variables.

    class Example {
        static int v1 = 100;
        //private int v1 = 200;                 //This line means it will not compile
        private boolean enabled = true;
        
        public void exampleMethod() {
              boolean enabled = false;
              int v1 = 800;              //Both of these exist for the duration of the method.
        }
    
        /*
        public void setValue(int value) {
              int value = 100;               //This line means it will not compile
        }
        */
    }
    

    Objects

    Creation
    class ObjectExample {
        Example e1 = new Example();             //A example object
        String s1 = new String("hello world");  //A string object
        String s2 = "hello again";              //A string object
        ObjectExample() {
            new Example();                     //A new object, but unreferenced
        }
    }
    
    class Example {
        private int value;
        private String name;
        public void setValue(int v) {
            value = v;
        }
        public void setName(String name) {
             this.name = name;
        }
    }
    
    class ObjectExample {
        public static void main(String[] args) {
             Example e1 = new Example();   //Object created
             e1.setName("hello world");    //setting value
             e1 = null;                    //reference is set to null, meaning the GC will clean it up
             ...
        }
    }
    

    When an object is out of scope (the object is created within a method, or an if statement, etc) then it will be picked up by the GC.

    Point of note, you can never be certain WHEN these objects will be garbage collect, only that they are due to be garbage collected.

    Methods

    Return types
    class Example {
        private int value;
        public void setValue(int v) {
            value = v;
        }
        public int getValue() {
            return value;
        }
    }
    
    class ObjectExample {
        public static void main(String[] args) {
           Example e1 = new Example();
           int v = e1.setValue(100);  //This line means it won't compile!
           e1.getValue();             //This line is fine (no errors), of course not sure what you are doing....
           String t = e1.getValue();  //won't compile!
    
           //NB: the value 100 is a method argument, however setValue(int v) int v is a method parameter
           // method arguments can be literals or variables
        }
    }
    
    Variable arguments
    class Example {
        public int variExample1(int... m) {
            int res = 0;
            for (int i = 0; i < m.length; i++) {
                System.out.println(m[i]);
                res += m[i];
            }
            return res;
        }
        public int variExample2(String... s, int... m) {  //multiple variables which accept variable arguments will not compile
            int res = 0;
            for (int i = 0; i < m.length; i++) {
                System.out.println(m[i]);
                res += m[i];
            }
            return res;
        }
        public int variExample3(int... m, String a) {   //the variable argument must be the last one, otherwise it will not compile
            int res = 0;
            for (int i = 0; i < m.length; i++) {
                System.out.println(m[i]);
                res += m[i];
            }
            return res;
        }
    
    }        
    
    Return types

    Three rules:

  • methods which return a value must complete with return and the value
  • void methods can return to exit, but must not return a value
  • if the return is not the “last statement to execute”, i.e. the return is before a calculation it won’t compile
  • Overloaded methods

    These:

  • must have different method parameters
  • may or may not have different return types
  • may or may not have different access modifiers
  • cannot be defined by just changing the access modifiers or return type

    Examples

    class ExampleOverload {
    
        int DoSomething(int val1, int val2) {
            return val1 * val2;
        }
    
        int DoSomething(int val1, int val2, int val3) {
            return val1 * val2 * val3;
        }
    
        int DoSomething(double val1, int val2, char val3) {
            return vl2 * val1 + val3;
        }
    
        int DoSomething(int val1, double val2) {
            return val1 * val2;
        }
    
        int DoSomething(double val1, int val2) {  //Note this is a overloaded method
            return val1 * val2;
        }
    
        //Note the last two can cause an issue if you call DoSomething(1,2) which overloaded method gets used? 
       //There are three to chose from. It will chose the fist as it has both int and int, otherwise
       //This will not compile
    
       //The following are not overloaded
    
       int doSomething(int a, int b) {
           return a * b;
       }
       
       //Just changing the return type does not overload the method
       double doSomething(int a, int b) {
           return a * b;
       }
    
       public int doSomething(int a, int b) {
           return a * b;
       }
       //Just changing the access modifier does not overload the method
       private int doSomething(int a, int b) {
           return a * b;
       }
    }
    

    Constructors

    class Example {
        String strValue0;
        int intValue0;
        Employee() {                            //Constructor - can be all four access methods
           intValue0 = 100;                     //It does not have an implicit return type
           strValue0 = "Hello World";           //It creates and returns an object of the class
        }                                       //If you define a return type it becomes a method
        Employee(int iValue, String sValue) {   //Constructor - these are public, protected, default, and private
           intValue0 = iValue;
           strValue0 = sValue;
        }
    }
    
    class TestExample {
        public static void main(String[] args) {
           Example e1 = new Example();
           Example e2 = new Example(200,"2nd test");
           System.out.println(e1.intValue0);         //prints 100
           System.out.println(e2.intValue0);         //prints 200
        }
    }
    
    
    Initializer?????
    class Example {
        Example() {
            System.out.println("Constructor!!!!");
        }
    
        {
           System.out.println("Initializer!!!!!!");
        }
    }
    class TestExample {
        public static void main(String[] args) {
            Example e1 = new Example();
    
            /*
                 The output from the line above will be:
    
                 Initializer!!!!!!
                 Constructor!!!!
            */
    

    These are for anonymous classes, to initialise the variables.

    Default Constructor and overloaded constructors

    Java creates a default constructor for a class if you don’t define one. However if you define your own constructor, Java will not create the default constructor – meaning you can’t call it. However you can define more than one constructor yourself, and you can define your own default constructor…

    class ExampleDefaultClass {
            String strValue0;
            int intValue0;
    
            ExampleDefaultClass(String x) {
                    this(x,-1);                       //Note the use of this to call the other constructor to pass in the value. It has to be named this and not Example(x,-1);
            }
    
            ExampleDefaultClass(String x, int y) {     //This is an overloaded constructor
                    strValue0 = x;                           
                    intValue0 = y;
            }
    }
    
    class TestClass {
            public static void main(String[] args) {
                    ExampleDefaultClass e1 = new ExampleDefaultClass();  //this will fail to compile!
                    ExampleDefaultClass e1 = new ExampleDefaultClass("hello",100);
            }
    }
    

    Some rules:

  • overloaded constructors must have different arguments lists
  • constructor can call another constructor with this
  • consturctor can’t call a constructor by its name
  • when using this to call another constructor it must be the first line of the constructor
  • Note, when using the this keyword, it must be the first statement!

    class Example {
         int intValue;
         String strValue;
    
         Example() {
             System.out.println("default constructor");    //This will not compile.
             this("x",-1);
         }
         Example(String a, int b) {
             strValue = a;
             intValue = b;
         }
    }
    
    Object fields

    Getters and Setters, how to pass values to private fields.

    class Example {
        private String strValue;
        private int intValue;
        
        public String getStrValue() {
            return strValue;
        }
    
        public int getIntValue() {
            return intValue;
        }
    
        public void setStrValue(String value) {
            strValue = value;
        }
    
        public void setIntValue(Int value) {
            intValue = value;
        }
    
        public int specialAdders(int... values) {
            int res = 0;
            for (int i = 0; i < values.length; i++) {
                res += values[i];
            }
            return res;
        }
    }
    
    class TestExample {
        public static void main(String args[]) {
             Example e = new Example();
             e.setStrValue("Hello world");
             e.setIntValue(99);
             System.out.println(e.getStrValue);
             System.out.println(e.getIntValue);
             System.out.println(e.specialAdders(1,2,3,4,5));
         }
    }
    

    By making the variables private, we are hiding them from other classes. The getters and setters can control the access to the classes variables. The setters, for example, can contain logic to validate the value before setting the variable. This is encapsulation, also known as information hiding.

    A well encapsulated class is where instance variables are private and access can only be gained, and controlled, by methods.

    Passing primitives
    class Prim {
        int a;
        void modifyVal(int a) {
            a = a + 1;
            System.out.println(a);
        }
    }
    
    class TestPrim {
            public static void main(String args[]) {
                    Prim p = new Prim();
                    System.out.println(p.a); //this prints 0
                    p.modifyVal(p.a);        //this prints 1
                    System.out.println(p.a); //this prints 0
            }
    }
    

    Note the value of a belonging to the class does not change because passing in the value to a method parameter of a takes precedence over the instance variable.

    Reference objects
    class Pers {
            private String name;
            Pers(String value) {
                    name = value;
            }
            public String getName() {
                    return name;
            }
            public void setName(String value) {
                    name = value;
            }
    }
    class TestPers {
            public static void swap(Pers p1, Pers p2) {
                    Pers temp = p1;                        //p1 and p2 are simply pointers to the object
                    p1 = p2;                               //this does not change the underlying objects
                    p2 = temp;
            }
    
            public static void swapV(Pers p1, Pers p2) {
                    Pers temp = new Pers(p1.getName());  //Here we create a new object and set the value
                    p1.setName(p2.getName());            //here we change p1 underlying object details
                    p2.setName(temp.getName());          //here we change p2 underlying object details
            }
    
            public static void main(String args[]) {
                    Pers pers1 = new Pers("John");
                    Pers pers2 = new Pers("Betty");
    
                    System.out.println(pers1.getName() + ":" + pers2.getName());  //prints John:Betty
                    swap(pers1, pers2);
                    System.out.println(pers1.getName() + ":" + pers2.getName());  //prints John:Betty
                    swapV(pers1, pers2);
                    System.out.println(pers1.getName() + ":" + pers2.getName());  //prints Betty:John
            }
    }
    

    reference: http://www.manning.com/gupta/

    Java Application connecting to a DB2 instance – Solution to Sql Exception No Suitable driver found

    November 26, 2011

    Ok, so this one bugged me for a while, and it was only a throw away comment on a forum  that gave me the clue.

    I have written a simple Java app to connect to a DB2 database to query the data and perform some analytics on that data. However my connection would never work!!!

    This was my code

    
    private Connection connection = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;
    
    try
    {
    res = new Vector();
    
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
    connection = DriverManager.getConnection("jdbc:db2://"+host+":"+port+"/"+database,user,pass);
    
    statement = connection.createStatement();
    
    preparedStatement = connection.prepareStatement("SELECT * FROM "+table+" order by 1");
    
    resultSet = preparedStatement.executeQuery();
    
    ...
    }
    catch (Exception e)
    {
    throw e;
    }
    finally
    {
    close();
    }
    
    

    This is based on the article I had read from IBM. Further to this article, I had managed to locate db2java.jar from the client installation. However, everytime I executed the code I was getting the error:

    Specified connection failed with java.sql.SQLException: No suitable driver found

    Searching for this, most articles suggested the connection string was wrong. I knew it wasn’t because I checked and double checked.

    Then I read a comment in a forum which said to use jcc.DB2Driver and not app.DB2Driver. I looked in the library db2java.jar and I could not find DB2Driver under jcc! However, I then realised within the driver directory of my DB2 client that there were more Java libraries, and one of these was db2jcc.jar.

    I swapped over my libraries and updated my code (note the change to Class.forName):

    
       private Connection connection = null;
       private Statement statement = null;
       private PreparedStatement preparedStatement = null;
       private ResultSet resultSet = null;
    
       try
       {
          res = new Vector();
    
          Class.forName("com.ibm.db2.jcc.DB2Driver");
          connection = DriverManager.getConnection("jdbc:db2://"+host+":"+port+"/"+database,user,pass);
    
          statement = connection.createStatement();
    
          preparedStatement = connection.prepareStatement("SELECT * FROM "+table+" order by 1");
    
          resultSet = preparedStatement.executeQuery();
    
          ...
       }
       catch (Exception e)
       {
          throw e;
       }
       finally
       {
          close();
       }
    
    

    This worked perfectly. Just wanted to share it!

    Building a standalone Java command line app with Netbeans

    November 26, 2011

    Pretty simple one really, and it was – once I remembered / found out.

    Seeing as I swap around from IDE to programming language, to OS I realised the other day that I didn’t know how to build a self contained command line java app (e.g. I had written a simple program and I wanted to ship it with the mysql driver) within Netbeans.

    So after a bit of searching, and being put off by the prospect of using ant I discovered a way to do it… I thought I would write this in the hope I won’t forget and to help others (took a little while to find this answer).

    Let imagine we have a simple Java program, good old hello world (see below)

    public static void main(String[] args)
    {
          Connection connection = null;
          Statement statement = null;
    
          try
          {
               Class.forName("com.mysql.jdbc.Driver");
    
               connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/svm","username","password");
    
               statement = connection.createStatement();
          }
          catch(Exception e)
          {
               System.out.println("Oh boy - "+e.toString());
          }
          finally
          {
               try
               {
                     connection.close();
               }
               catch(Exception e)
               {
                     System.out.println("Oh by there is a problem! "+e.toString());
               }
          }
    
          System.out.println("Hello world");
    }
    

    And further to this, the simple program also connects to a MySQL database…

    Now, you can see the desire… you to want to ship the jar including the mysql library? Well, this can be achieved really easily (in Netbeans). Just do the following:

    • Within the root directory of the project there is a file named – build.xml
    • Open this file in Netbeans, you will notice some XML at the top of the file about project name etc, within the open project element you see a lot of comments.
    • Scroll to the end of the file
    • Just before the closing element of project e.g. </project> insert the following example lines
     <target name="-post-jar" >
         <jar jarfile="${dist.jar}" update="true">
             <zipfileset src="${dist.jar}" includes="**/*.class"/>
             <zipfileset src="dist/lib/mysql-connector-java-5.1.6-bin.jar" excludes="META-INF/*"/>
         </jar>
     </target>
    

    This is the specific entries for adding the MySQL library to your jar file. You will note that it is referencing the library from my /project/dist/lib/ directory.

    And that’s it! Clean and build and you find your jar is bigger and contains your library!!!! Brilliant – ship it to the world now 🙂

    My source