Archive for the ‘Java’ Category

Equals – why ? and why not ==

Friday, February 19th, 2010

Object oriented programming allows for objects to be created on the fly with the keyword “new”. The new will create a new object on the heap memory space and then give that memory location to the variable name, for example.

class NewClass 
{
   private int x;
} ....
 
NewClass a = new NewClass();
NewClass b = new NewClass();

What is happening in memory is something like below, the a variable has a small space and so does b, because they are just “pointers” to the actual memory locations of the class that was created.

Variable Value
a 0×0102
b 0×0110

where as the memory on the heap space would actually hold the NewClass details for example.

Memory location Value
0×0102 NewClass – overhead details
0×0104 NewClass – x value
…. ….
0×0110 NewClass – overhead details
0×0112 NewClass – x value

So the actual value of a and b are just values within memory, this could give reason why the “==” (equals) does not work e.g.

if (a==b)

even if both of them have the same internal values of the NewClass x value, they are still actual pointing to different locations (which makes sense otherwise you are comparing the same object which would be silly). There is a few functions to do the comparsions of objects, Equals, Compare for example and if you implement these functions within your class you can then “compare” the two objects instead of the memory locations that are held within the variables (a 0×0102 and b 0×0110)

To implement a Equal function it would be something similar to

	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
                return false;
	}

where the obj (Object) passed is the same type as the Class e.g. NewClass and return true if they are same (after casting the object obj value to a ClassA structure).

Here is a bigger example with code for two java files, if you save this class as normal for java to have it the same as the class name e.g. ClassA.java

public class ClassA {
	private int x;
 
	public ClassA() { x =0;}
	public ClassA(int value) { x = value;}
 
	public int xValue() { return x; }
	public void setX (int value) { x = value;}
 
	public boolean Equals(Object obj)
	{
		if (x == ((ClassA)obj).xValue())
			return true;
		return false;
	}
 
	public int Compare(Object obj)
	{
		ClassA objA = (ClassA)obj;
		if (x > objA.xValue())
			return 1;
		else if (x < objA.xValue())
			return -1;
		else
			return 0;
	}
}

this file also includes the Compare function method, so the returns have to be normal to java comparison e.g. 1 means > (greater than) , 0 = same, -1 < (less than), it is up to you to implement to make sure that this kinder of comparison adhears to how you want the class is greater than another class, could be a X value as above, or could that you call the first class number 1 and the second of that type of class 2.. it is up to you.

and then save this as Test.java

public class Test {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClassA a = new ClassA();
		a.setX(10);
		ClassA a2 = new ClassA();
		a2.setX(10);
		if (a==a2)
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
 
		if (a.Equals(a2))
			System.out.println("Yep the same");
		else
			System.out.println("nope not the same");
		a2.setX(11);
		int comparsion = a.Compare(a2);
		if (comparsion == 0)
			System.out.println("Same");
		else if (comparsion == 1)
			System.out.println("greater");
		else	// only -1 left.
			System.out.println("less than");
 
	}
 
}

compile them you just need to javac Test.java and that will compile the ClassA.java file as well, then to run

java Test
 
nope not the same
Yep the same
less than

Java applet – hello world

Saturday, January 30th, 2010

A java applet is a web object that allows you to do some funky things within a web page, you could even have a game on the screen with a java applet. But as normal you have to start from the start as such, the most used starts are the classic “hello world” example.

In a java applet, it is basically a class called Applet that you extend from and this has all of base code inside it so you only need to implement the virtual functions

  1. init
  2. start
  3. paint
  4. destory
  5. stop

And these are the basic functions that allow you to call other classes of your choice. The init – (initialize), setups up the environment of your choice, start is where the application (GUI interface) will run within, paint is what is painted to the applet screen, destory is when you destory the applet you may need to clean up some code, stop is when the application/applet is stopped.

The main basic class will extend from a applet (java.applet.Applet) so you will need to import that class library

import java.applet.Applet;
 
// basic class extends the applet
public class HelloWorld extends java.applet.Applet {

and then implement the functions start,init,stop,destory and paint if required. Below is more code that will resize the basic applet object and display (paint) the words Hello World using the Graphics class object drawString method.

import java.awt.Graphics;		// need this for the Graphics part of the paint function
import java.applet.Applet;		// to extend from.
 
public class HelloWorld extends java.applet.Applet {
 
    // resize the screen 
    public void init()
    {
	resize(150,25);
    }
 
    public void start()
    {
    }
 
    // draw with the Graphics class object a string on the canvas, point 50, 25
    public void paint(Graphics graphicsObj)
    {
	graphicsObj.drawString("Hello World!", 50,25);
    }
 
    public void stop()
    {
    }
 
    public void destroy()
    {
    }
}

Is you save that as “HelloWorld.java” and then you need to compile it into a class file (which is a common object file that java can read to run within the virtual machine).

javac HelloWord.java

which will output the HelloWorld.class file, which you will need to include into the html code applet tag, below is the HTML code

<HTML>
<head>
<title>A hello world</title>
</head>
<body>
Test output of the program
<applet code="HelloWorld.class" width=150 height=25>
</applet>
</body>
</HTML>

The output would be

Test output of the program

Note: If you look at the source code of this page, it will say

<applet code="HelloWorld.class" codebase="/Appletsexamples/"  archive="HelloWorld.jar" width="150" height="25"></applet>

I had to add in the codebase and archive because of the hosting, to create a jar file you just need to do

jar cf <tarname> <file(s) name>
 
jar cf HelloWorld.jar HelloWorld.class

The jar file is basically a zipped archive.

Arrays

Monday, July 27th, 2009

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Interfaces

Monday, July 27th, 2009

An interface describes what functions an implemented class will have to code. E.g. if a class was a car and the interface had functions for how many doors etc, then a class of Vauxhall that implements the interface would have to code the function to return the correct amount of doors.

Here is the code, I usually find the code explains it better.

// defines the fuctions that have to be implemented by a implementable class
interface implementThese
{
       void printHi();       // have to implement these
       void printBye();
}
 
// the interClass will implement the interface implementThese
class interClass implements implementThese
{
       public void printHi()
       {
              System.out.println("Hi");
       }
 
       public void printBye()
       {
              System.out.println("Bye");
       }
}
 
class inter
{
       public static void main(String args[])
       {
              interClass in = new interClass();
              // call the classes functions.
              in.printHi();
              in.printBye();
       }
}

If you save as inter.java, and then run the output will be

Hi
Bye

There can be many interfaces per class to be implemented.

Generics

Monday, July 27th, 2009

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

// the class for the generics (the T is the object of any type)
class genericsClass<T> 
{
       T val;              // private object val of type T
       public genericsClass(T t)       // constructor for the class
       {
              val = t;              // set the internal to the passed value
       }
 
       public T returnValue()       // return the internal value
       {
              return val;
       }
}
 
// main runable class
public class generics
{
       public static void main(String args[])
       {
              // create a Integer class with a default value of 3
              genericsClass<Integer> genInt = new genericsClass<Integer>(3);
              System.out.println("Value= " + genInt.returnValue());
 
              // create a String class with a default value of "hi there"
              genericsClass<String> genStr = new genericsClass<String>("hi there");
              System.out.println("Value = " + genStr.returnValue());
       }
}

If you save the code and run with java version 1.5 + (since this was part of java 1.5). The output will be

Value = 3
Value = hi there

As you can see the same class is able to use both integer and strings as the default variable type.

Method – Add Two numbers

Monday, July 27th, 2009

This tutorial uses the same code as Add Two Numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers_function
{
       // private = local to this class
       private static int addIntegers(int a, int b)
       {
              return (a+b);
       }
 
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + addIntegers(val1, val2));
       }
}

save as addtwonumbers_function.java, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Class structure

Monday, July 27th, 2009

This is a general tutorial about the class structure of programming languages.

The class is basically an object that allows public methods (accessed outside that class object) and private methods (the internal class logic) and protected with is the same as private apart from an inherited class can access the protected objects. Basically the 3 main types

Public : Access from outside the class, and internal of course, with inherited etc.
Protected : Access from inherited of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

This is 3 Java source code to demonstrate

class classexample
{
       private       int value1;
       private       int value2;
       protected int value3;
 
       public int addtwo(int a, int b)
       {
              value1 = a;
              value2 = b;
              value3 = (a + b);
              return value3;
       }
 
       public int returnValue1()
       {
              return value1;
       }
}

save as classexample.java

class classexample2 extends classexample
{
       public int returnValue2()
       {
              //return value2;       // will error due to value2 is private in the inherited class
              return 0;              // to be able to compi
       }
 
       public int returnValue3()
       {
              return value3;       // fine since a protected part of the inherited class
       }
}

save as classexample2.java

class classex
{
       static public void main(String args[])
       {
              classexample example1 = new classexample();
              classexample2 example2 = new classexample2();
              System.out.println("Class 1, adding two numbers and setting the internal numbers");
              System.out.println(example1.addtwo(3,4));
              // of course will return 0, because example2 is not connected to example1 class, 
              // it just extends the definition of that class.
              System.out.println(example2.returnValue3());
       }       
}

save as classex.java

And to compile the tutorial just need to java classex because java will compile the other classes as well (and creates the class files). Once compiled the output will be

Class 1, adding two numbers and setting the internal numbers
7
0

Local variables

Monday, July 27th, 2009

This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some java code to demonstrate the difference between local variables and global.

class localvariable
{
       private static int value1 = 1;
 
       static public void globalVariable()
       {
              System.out.println("Global : " + value1);
       }
 
       static public void main(String args[])
       {
              int value1 = 0;
              globalVariable();
              System.out.println("Local : " + value1);
              return;
       }
       return 0;       
}

the output would be

Global : 1
Local : 0

Add two numbers

Monday, July 27th, 2009

This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the InputStreamReader to convert the System.in (console) into a stream, which into converted with a BufferedReader to get the whole line and not just one character/number.

The code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers
{
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + (val1 + val2));
       }
}

save that as addtwonumbers.java, because of course java is very picky about the class name to the java file, because Java creates a class of the same name as the class which in-turn is what the java virtual machine uses to execute.

Once compiled (javac addtwonumbers.java) and executed (java addtwonumbers) the output will be

Enter first number : 30
Enter second number : 23
Answer = 53

Read/Write Files

Monday, July 27th, 2009

To read in from and file and also output to a file, java uses streams to “talk” to the files. These streams allow for communicating with different stream conversion tools, the object tool within this tutorial is the DataInputStream which “talks” to the FileInputStream.

I have attached the code within a zip file with the required input file as well.

Below is the code

import java.io.*;
 
class javareadfile
{
       public static void main(String args[])
       {
              String fileName = "country.txt";//input file
              String outFileName = "sqljavacountry.txt";//output file
 
              try
              {
                     // file input stream, basically a pointer to the stream of the input file
                     FileInputStream fStream = new FileInputStream(fileName);
                     // file output stream, basically a pointer to the stream for outputing data
                     FileOutputStream fOutStream = new FileOutputStream(outFileName);
 
                     // the input/output data streams that connect to the above streams
                     DataInputStream dInput = new DataInputStream(fStream);
                     DataOutputStream dOutput = new DataOutputStream(fOutStream);
 
                     // whilst there is data available in the input stream
                     while (dInput.available() !=0)
                     {
                            String in = dInput.readLine();// read a line from the input file
                            // output a stream of data to the output file
                            dOutput.writeBytes("insert into country(place) values (\""+in+"\");\n");
                     }
                     //close the two files.
                     dInput.close();
                     dOutput.close();
              }
              catch (Exception e)// incase of any errors
              {
                     System.err.println("There was a error : " + e.toString());
              }
       }
}

If you save this as javareadfile.java and also create a countrys.txt file with what ever text you like, e.g.

United Kingdom
France
Germany
United States
etc.

Once you have compiled the program (javac -deprecation javareadfile.java, may have to use -deprecation if using java virtual machine 1.5 over 1.4) and execute the program (java javareadfile), it will look for the file countrys.txt within the same directory as the program executable and also create outcountrys.txt within the same directory (it will write over the file if there is one present). Then within the while loop it will read the input file line by line and output to the screen what has been read and also output to the output file.

Of course to finish off to close down the files and return back to the console.