Pages

Monday, June 18, 2012

Buffered reader

In many times you will read data from some device or file, like a keyboard, a serial port or a txt file. For all those devices, you will need a BufferedReader object. This object allows you to put in all the information you want to read, and then get it by characters or lines. Whatever you need to read, you can pass it to the BufferedReader when you instancied it, and then you can read its data when you need. Here is an example:
System.out.println("Write something you want to read., and press Enter.");
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String data = keyboard.readLine();
In the previous code I use the InputStreamReader to get access to the keyboard (System.in). I will explain it more deeply in another article. When the "readLine()" method is call, the execution of the code will stop there until the user enter some data in the console and press Enter. The user must press Enter to finish the line, because the ejecution will not continue until there is a complete line in the BufferedReader. All the data written in the console from the keyboard will be stored in the variable "data" as a string.

Lets examine the different method of the BufferedReader. The BufferedReader can read its content line by line, as it was shown before, but it can read it char by char or a specified number of characters. Another way is specifiyng a token or mark. When you read char by char, the mark will move ahead. Then you can skip some characters you don't want to read, or you can reset this mark to the beginning of the buffer. Here are some examples:

File.txt:
Hello, this is a file.
There are many lines in this file.
But this is the last one.

Code:
String a; char[] b = new char[10]; int c;
BufferedReader file = new BufferedReader(new FileReader("File.txt"));
a = file.readLine();
System.out.println("First read: " + a);
c = file.read(b, 0, 10);
System.out.println("Second read, " + c + " characters read: " + new String(b));
file.reset();
file.skip(7);
a = file.readLine();
System.out.println("Last read: " + a);

Output:
First read: Hello, this is a file.
Second read, 10 characters read: There are
Last read: this is a file.
Reading something with a BufferedReader can throw some exception, so every time the read methods must be inside a try/catch clause.

Sunday, June 17, 2012

Console prints


In this seccion, we are going to studie how to print messages in the console. There is two message types which can be printed in console, the error messages and the rest. The error messages normally appears with another style, in red for example, specially if you use an IDE programm to launch your application. Here is an example of the two types:
System.out.println("This is an info message");
System.err.println("This is an error message");

Both message types owns to the System class, and have the same methods to print messages. Basically, you can print in a single line (print), or have a return line at the end of your message (println). Here are some examples:
System.out.print("The next message of this one will be printed in the same line.");
System.out.println(" This message will be printed in the same line as the previous one.");
System.out.println("This will be in the second line.");

Output:
The next message of this one will be printed in the same line. This message will be printed in the same line as the previous one.
This will be in the second line.

In the case of the prints in the same line, you must take care of the spaces between the messages.

To print the values of variables in the middle of messages, you must cut the message where you want to put a variable, and then write the name of the variable inside. To cut a message you only have to close the accuotations and add the + signal to add some other stuff you want to print, like another message, variable values... Here are some examples:
int a = 5;
System.out.println("The variable a = " + a);
System.out.println("Message one " + "followed by " + "Message two");

Output:
The variable a = 5
Message one followed by Message two

The variable you want to print must be inicialized. And to print arrays or list, you must specifie which element one the collection you want to print, otherwise the direction of the object will be printed. And if the variable is not inicialized, a NullPointerException will be thrown. Here is an example:
int[] a = new int[5];
a[0] = 1; a[1] = 2; a[2] = 2; a[3] = 5; a[4] = 7;
System.out.println("The forth element of the array is " + a[3]);

Output:
The forth element of the array is 5

Wednesday, June 13, 2012

Main


To start some application in Java, you must implement the main method. This method is the one who start your application. You can have many main methods implemented, but when you are going to compile your application you must specified which one of them must be executed. The main method must be static, that means it can not own to any class (it is a little ambiguous, because it must be implement inside a class), and can have many arguments as strings.

Here is an example:
public static void main(String[] args){
if (args.length == 0)
System.out.println("No argument was specified");
else if (args.length == 1)
System.out.println("One argument was specified: "+args[0]);
else
System.out.println("Many arguments were specified!");
}

Those arguments can be used to create internal classes or set variables.

Tuesday, June 12, 2012

Collections


The collections are very similar to arrays, in fact there are special arrays. There are many collections (ArrayList, HashMap, Vector...) each one has different properties. Everyone must be instancied, and have common methods to get and set their values. Someone has different methods to set its values (like Map, HashMap, HashTable...) because every set of value is composed by a key and a value.

Every collection must specified the data type there are going to store. The data type must be specified when the variable is declared, and must be the same when it is instancied:
ArrayList<String> a;
a = new ArrayList<String>();

The collections do not need to specified its size, they have a dynamic size, you can put some values and the size of the collections will increase at the time. When you instancied a collection, you can specified some properties, like the initial size, and the value which will increase the collection at each insertion:
Vector<Integer> a = new Vector<Integer>(0,1); //initial size=0; increment value=1

Like I said before, the collections have common methods to access their values:
  • boolean add(Object o): add a new element at the end of the collection
  • boolean add(int index, Object o): add a new element at the specified index
  • boolean addAll(Collection<Object> c): add all the given collection to the end of this collection
  • void clear(): delete all the elements
  • boolean contains(Object o): return true if the collection has the given object
  • boolean containsKey(Object key): return true if the collection has the given object as a key
  • boolean containsValue(Object value): return true if the collection has the given object as a value
  • Object get(int index): return the object stored in the given index
  • int getIndexOf(Object o): return the index where is stored the given object
  • int lastIndexOf(Object o): return the index where is stored the given object starting to look at the end of the collection
  • Object put(Object key, Object value): put a set of key/value in the collection
  • Object remove(int index): remove the object stored at the given index
  • boolean remove(Object o): remove the given object from the collection, and returns true if it was successfull
  • int size(): return the size of the collection


Here are not shown all the methods, and not every of those methods are in every collection, each collection has its own properties. Here are explained to most commons:
  • ArrayList and Vector: those are both simples arrays. Every data you add will be stored at the end of the collection. The difference between them are very insignificant: The Vector store its values synchronizing multiples threads, and ArrayList does not. Internally, the ArrayList size is smaller than the Vector's.
  • HashMap and HashTable: those are a two dimensional arrays. Every value is defined from a key, not from an index like the previous one. The new values in those arrays are not stored at the end of the collection, but in the first place of internal memory. To get one of the stored values, you must give the key, and viceversa. The difference between HashMap and HashTable are similar to ArrayList and Vector. HashTable stores its values synchronizing multiples threads, and HashMap does not. But HashMap allows store null values, and only one null key, and HashTable does not store any null value (neither key or value).

Arrays


In the Java language, the arrays are quite simple. You must instanciate it before operate with, and specifie its size. Then you can set a value to each index. Every index must be set as the original data type, if it must to be instancied, here it must also be instancied.

Here is an example:
byte[] a = new byte[3];
a[0] = 3;
a[1] = 3;
a[2] = 4;
Object[] b = new Object[2];
b[0] = new Object();
b[1] = new Object();

If you want to copy an array, there is a method in the System class which can made it for you:
byte[] a = new byte[2];
byte[] b = new byte[2];
a[0] = 1;
a[1] = 2;
System.arrayCopy(a, 0, b, 0, a.length);

The method System.arrayCopy(...) take the values from a source array to a destination array. You must specifie the initial position where to start reading in the source array, and the initial position where to start writting in the destination array, then the number of elements to copy must be also specified. Both arrays must be intancied before call this method.

The arrays has some properties, and one of them is to know the size of the array, as it was made in the previous example. When you create an array, you do not know how the size will be in the future, so you can use this method when you check the content in a loop. This is very important because if you access to a direction of an array bigger than its size, an exception will be thrown.

Sunday, June 10, 2012

While loops


In this lesson we are going to learn about the while and do-while loop. Those loops have not a defined initial number of cicles to do. They will execute the code inside the loop until the condition is false. The difference betwenn the do-while loop and the while loop is that the first one will execute the code inside its loop almost one time, as the while loop will look first if its condition is right to execute its code.

Example:
int a = 5, b = 3;
//this loop will never be executed
while (a < 5){
a--;
}
//this will be execute until a is less or equal than 5
do{
a--;
}while(a > 5);

For loops


The for loops are used when the number of times you want the loop to be executed is previously defined. The for loop has a block of code which is executed every loop, and the conditional sentence to do the loops. The conditional sentence is divided is three parts: the initial value, the condition to stay in the loop and the action to do every loop. Each of those three fields are optional, but be carefull because you can convert it in an inifinitive loop.
The initial value is where you can create a variable and indicate its initial value. There, you can also use an existing value and set it to another value.
The condition to stay in the loop is set in the second field of the for loops. This indicate how many times will the code of the for loop be executed. The most common condition for this field is a counter, but any condition can be used. The parameters used here can be either modified int he third field or in the code of the for block. Basically, the condition waits for a true or false return.
The last field, is the action which execute the for loop at every loop. This action is most of the times incrementing a counter, but as I said before, it is an optional field, so the counter can be incremented inside the for loop. If the condition waits to the change of a parameter, then this field can be ommited.

Here is an example:
for(int i=0; i<4; i++){
System.out.println("numeber=" + i);
}

Output:
number=0
number=1
number=2
number=3

Another example:
int a = 0;
boolean exit = false;
for(;!exit;){
if (a == 4){
a++;
System.out.println("We still inside the loop");
}
else{
exit = true;
System.out.println("We are going out the loop");
}
}

Output:
We still inside the loop
We still inside the loop
We still inside the loop
We still inside the loop
We are going out the loop

The condition field can also be ommited, but in this case, we must do something to get out from the for loop. One instruction to get out of a loop, is simply a return instruction. In this case we go out of the for loop and the method. Another instruction is the break instruction. This instruction can be used to go out of any loop or a block of code (do-while, while, for, switch...).