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...).

If conditions


In this lesson we are going to learn how to use the If coniditions. The If condition is used to decide where the execution of the code must go. Inside the If condition the is a logical condition which decide if the code will be executed inside the If condition or if it goes out. Then, the If condition can have an Else-If to catch the next execution, or it can have a final Else to execute the default code.

Example:
int a = 3, b = 4;
if (a == b){ //the following code will not be executed
System.out.println("a is equal to b");
}
else if (a > b){ // the following code will be executed
System.out.println("a is greater than b");
}
else
System.out.println("a is less than b");
/* the code before will not be executed. By the way, this code is considered inside the else, although not having braces. In those cases, only the next sentence will be executed */

Maths


In this lesson we are going to learn the basic arithmetic operations we can do in Java.

Symbol Operation
+ Adition
- Subtraction
* Multiplication
/ Division
% Remainder

Examples:
a = 5 + 3; //a = 8
b = a - 3; //b = 5
c = b * 2; //c = 10
d = c / 2; //d = 5
e = d % 2; //e = 1

Unary operations:

Symbol Operation
++ Increments a value by one
-- Decrements a value by one

For those one, the variable can be before or following the symbol, but the operation will be different. Here is an example:
int a = 0;
a++; // a = 1
++a; // a = 2
System.out.println(a++); // print 3
System.out.println(++a); // print 4 but a = 3. The instruction prints without changing the value of the variable.

Another form of this use is the following:
int a = 0;
a = +1; //it increments the value of the variable "a".

Logical Operations:

Symbol Operation
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
&& Conditional AND
|| Conditional OR
! Inverts the value of a boolean

Examples:
int a = 5, b = 3;
return (a == b); //return false
return (a != b); //return true
return (a > b); //return true
return (a >= b); //return true
return (a < b); //return false
return (a <= b); //return false
return ((a == b) && (a != b)); //return false
return ((a == b) || (a != b)); //return true
return !(a == b); //return true

Bitwise and bit shift operations:

Symbol Operations
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

Examples:
int a = 2; // binary value: a = 00000000 00000000 00000000 00000010
a = ~a; // a = -3, binary value: a = 11111111 11111111 11111111 11111101
a = a << 2; // a = -12, binary value: a = 11111111 11111111 11111111 11110111
a = a >> 2; // a = -3 binary value: a = 11111111 11111111 11111111 11111101
a = a >>> 2; // a = 1073741823 binary value: a = 01111111 11111111 11111111 11111111
a = a & 2; // a = 2 binary value: a = 00000000 00000000 00000000 00000010
a = a ^ 2; // a = 0 binary value: a = 00000000 00000000 00000000 00000000
a = a | 2; // a = 2 binary value: a = 00000000 00000000 00000000 00000010

Enum classes


The enum classes are used to enumerated multiple secuential values with its names. Those values are statics, and can be accessed publicly. 

Example:
public enum Week{
MONDAY, //numeric value = 0
TUESDAY, //numeric value = 1
WEDNESDAY, //numeric value = 2
THURSDAY, //numeric value = 3
FRIDAY, //numeric value = 4
SATURDAY, //numeric value = 5
SUNDAY //numeric value = 6
}

Apart of this, the enum class can have variables and methods as other classes. When there are some variables in the enum class, those variables will be linked to the enum values. Thus, the enum values can be setted as you want. Here is another example:

Code:
public enum Bottle{
 LITTLE (250), MEDIUM (500), BIG (1500);
 private int ml;
 public Bottle (int size){
  this.ml = size;
 }
 public int getSize(){
  return this.ml;
 }
}
public class Pack{
 private int nBottles;
 private Bottle bottleSize;
 public Pack (int nBottles, Bottle bottleSize){
  this.nBottles = nBottles;
  this.bottleSize = bottleSize;
 }
 public int getNBottles(){ return this.nBottles; }
 public Bottle getBottleSize() { return this.bottleSize; }
 public static void main(String[] args){
  Pack p = new Pack(6, Bottle.BIG);
  System.out.println("This is a pack of " + p.getNBottles() + " bottles.");
  System.out.println("Each " + p.getBottleSize() + " bottle has " + p.getBottleSize().getSize() + " ml.");
 }
}
Output:
This is a pack of 6 bottles.
Each  BIG bottle has 1500 ml.

Interface classes


The interface classes are more like a template of a class. The interface show how must be the subclass, which methods must implements, those methods must not be implemented here but in the subclasses Those classes are used to organize a serie of future classes which will act all together. It is like the guidelines all the subclasses must follow. Here is an example:
public interface CompanyInterface{
public void buySupplies();
public void paySalaries();
}
public class Supermarket implements CompanyInterface{
public void buySupplies(){
System.out.println("Buying fruits...");
}
pubilc void paySalaries(){
System.out.println("Paying cashiers...");
}
}
public class Garage implements CompanyInterface{
public void buySupplies(){
System.out.println("Buying tyres...");
}
pubilc void paySalaries(){
System.out.println("Paying mechanics...");
}
}

Abstract classes


An abstract class can be defined as the beginnig of a class. It implements abstract methods that can be used and modified in subclasses which extends the abstract one. The abstract methods do not have a body, the body must be implemented in the subclasses. An example can be the following: a first abstract class is Shape, the second one y Square which extends the first one. Then the Square class can use the methods and variables of the Shape class. Not all the abstract methods must be implemented. Here is an example:
public abstract class Shape{
public abstract void setName(String name);
public abstract void setNumberOfFaces(int faces);
}
public class Square extends Shape{
private String name;
public void setName(String name){
this.name = name;
}
}
public class Cube extends Shape{
private String name;
private int faces;
public void setName(String name){
this.name = name;
}
public void setNumberOfFaces(int faces){
this.faces = faces;
}
}

Methods


In this lesson we are going to study the methods. The methods becomes from the classes. They can change some propeties of the classes or the can obtain some value or functionalities of a class. Every method can have one or more arguments passed by the user, and can return a value or not. The methods can be public, private or protected. A public method can be called from a main programm where the class is constructed. A private method can only be called in the owner class. And the protected methods are method that can be called internally and from any subclass method. The subclasses will be discussed in another lesson. The variables can also be public, private or protected. Both methods and variables can be defined without specifying the visibility, here they will take the default visibility, private.

Structure of a method:

[visibility] [data returned] [name] ([data type of argument 1] [name of argument 1], [data type of argument 2] [name of argument 2]...){
[...]
}

Example:
public int getInteger(int argument1){
//something
return 1;
}

The constructor are methods too, but they are called only when the class is instancied. We can differenciate it from other methods because the constructor must have the same name as the class and it do not return anything. One class can have more than one constructor but they must be different by anyone of them from the arguments they have.

Here is an example:
public class ObjectA{
//variables
private String v1;
private int v2;
//constructor 1
public ObjectA(){
this.v1 = "Hello";
this.v2 = 0;
}
//constructor 2
public ObjectA(String arg1, int arg2){
this.v1 = arg1;
this.v2 = arg2;
}
//public method
public int getV2Incremented(){
this.v2 = this.increment(this.v2);
return this.v2;
}
//private method
private int increment(int value){
return value++;
}
}

Classes


Here we are going to explain the definition of a class. A class is an object that could be used in a main programm. This class has usually properties and methods. The properties can be modified by the user with the gets and sets methods. And the methods are used to get some results related to the class. This can be better explained with an example:
public class ObjectA {
//private properties
int property1;
int property2;
//constructor
public ObjectA(){
this.property1 = 0;
this.property2 = 0;
}
//gets and sets methods
public int getProperty1(){
return this.property1;
}
public void setProperty1(int property1){
this.property1 = property1;
}
public int getProperty2(){
return this.property2;
}
public void setProperty2(int property2){
this.property2 = property2;
}
//another method
public void increment(){
this.property1++;
this.property2++;
}
}

Now I am going to explain the example. First there is a class called ObjectA, which has to properties (property1 and property2). The properties can be accessed and modified by the get and set methods. Thus there is anohter method "increment" which increment the value of the variables property1 and property2 in one value. And finally, there is the constructor. The constructor is needed to create a local copy of the class ObjectA. In the constructor we can initialize the variables and call private methods if it is necessary.

There are multiple types of classes: enum, abstract, interface or class. All must be public if they are alone in the file. If anyone is inside another, it can be public or private. The main class of the file must be named as the file.

Comments


In this lesson, we are going to see the comments in the code. All in the code we can put some comments to explain what is doing the programm at any time. The comments can be line by line(//), or multiple lines(/* */).

Here is an example:
//comment in a single line
/* closed comment in a single line */
/**
 * comment in multiple lines
 */

The comments of multiple lines can also be closed in the same line, letting write more code following the comment. Another type of comments are the JavaDoc (/** */). Those comments are used to introduce a class, method or variable that can be seen in an IDE when you are writting some code. Here is an example of a JavaDoc for a method:
/**
 * Description of the method
 * @param value Description of the argument named value
 * @return Description of the returned value
 */
public int setVariable(int value){
//something
return x;
}

Data types


In this lesson I am going to explain the basic data types that can be used in Java. Here are the data types with its lenghts:

Type Lenght Default value Examples value Min/Max values
boolean 1 false false/true -
byte 8 0 1, 2, 3 -128 / 127
short 16 0 1, 2, 3 -32,768 / 32767
int 32 0 1, 2, 3 -2,147,483,648 / 2,147,483,647
long 64 0L 1, 2, 3 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807
float 32 0.0f 1.1, 1.2, 1.3 1.4E-45 / 3.4028235E38
double 64 0.0d 1.1, 1.2, 1.3 4.9E-324 / 1.7976931348623157E308
char 16 '\u0000' 'a', 'b', 'c' '\u0000'(0) / '\uffff'(65,535)
String - null "Hello" -

Furthermore there are the arrays. The array can be made by any type of the previous one, and they can also be made by objects. The arrays can be of one or more dimensions. The arrays must be instancied, and have a static size, defined when their are instancied.

Example of arrays:
byte[] a = new byte[10]; //size of array = 10
int[][] b = new byte[5][5]; //array of two dimensions, each one with a size of 5

When assiging a value to non-floating numeric variables, it can be assigned from multiples bases: 2(binary), 10(decimal), 16(hexadecimal).

Examples:
int a = 0b010101; //binary format. Atention, only for JDK 1.7 or grather
int b = 1234; //decimal format
int c = 0x1234abcd; //hexadecimal format

Syntaxis


In this lesson we are going to learn about the syntaxis of the Java programming code. The Java code has classes, inside the classes are the methods, and inside the methods are the sentences. The sentences can be made of three basic types: declaration, conditions and actions. In the declaration we have to create the variables; the conditions decide where way of execution of the code; and the actions are were we act with the variables.

The declaration are written in the following way: first must be the data type, then the name of the variable, and at the end the semi colon. There are two kinds of declaration: for the primitive data types, and for the rest. For the primitive data types the declaration is easy, we only have to assigned the name of the variable and optionally the value. There can be multiple declaration of variables for a same data type if they are followed by comas.

Examle:
double a;
int b = 3;
byte c, d;

For the rest of the data types (arrays, objects...), the variable must be instancied. What does that mean? That the variable needs a constructor to be initialized. The value of a variable which is not instancied is null. To instancied a variable we will use the operator "new" followed by the constructor. Depending on the construtor, they can requiere some arguments. Here is an example:
Object a = new Object();
byte[] b = new byte[4];

There are some objects that can/must be instancied by a subclass because the first one is only an interface. Here is an example:
Calendar cal = new GregorianCalendar();

The conditions are the one which decides where the code will be executed, and in some cases for assigning a value to a variable. They are always inside parentheses, and return a boolean value. They can be in do-while/while loops, for loops, if conditions, and asigning a value to a boolean variable. Here are some examples:
int a = 3, b = 4;
if(a == b)
System.out.println("a is equal to b");
boolean c = (a > b); //c = false

Finally there are the actions. The actions are where the values of the variables are setted or getted, where the mathematical operations will be done... Those instructions must always finish by a semi colon. Here is an example:
int a = 3, b = 4;
a = a + 4;
System.out.println("a is equal to " + a);

Now we are going to talk about the admissible characters. There are the mathematical signs (+, -, *, /, %, =), the logial ones (>, <, ==, !=) and for the commentaries (//, /* */). Then, there are the brackets [] , braces {}, parentheses () and angle brackets <>. The brackets are used in the arrays, to define the index of the array. The braces are used to defined a block of code. This code can own to a class, method or loop. But you can also write some code inside those brackets without any reason. This is made to conserve internal variables only in this block of code. Here is an example:
int a = 3;
{
int b = 2; //this variable is exclusive of this block
a = a + b;
}
int b = 5; //this variable is not the same as the previous one
a = a + b;

And the parentheses are for the methods. There is were we can pass the arguments to the methods. The angle brackets are used to specified a data type in a collection. I will dedicate another article for those data types.

Anothers characters used in the Java code are the following ', ", \, \r, \n... Those are characters used for the texts. The ' is used for determine a signel character. Only one character can be between two '. The " define a string of characters, you can put all the characters inside. And then, there are the escape character and the special ones. The special characters (like \r: carriage return, \n: line return...) are used to make a special behaviour to the text where it is placed. And the escape character is used to print a special character in a text. The special character will never be showed in a text, they will do their own behaviour, and the escape character say that the character following this will be printed in the text. Here is an example:
char a = 'a';
String b = "Hello";
b = b + '\n';
System.out.println(b);
b = b + "this character is printed \\n";
System.out.println(b);

And this is the console output;
Hello 
Hello
this character is printed \n

Hello World


The first step is to create a "Hello World". Here we will start with a main programm which only print the message "Hello World" in the console.
public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello World"); }}

This code must be saved in a file with the same name as the class (in this case "HelloWorld.java"). Then we can run the example with the following commands:
> java HelloWorld.java

For running this example a Java Virtual Machine must be installed in the computer.

Introduction


The java code programming is used in many devices. This language is very important because is it object oriented, multi-platform and it can be also used for graphic programming. The only thing you need to start programming is to have a Java Virtual Machine installed in the computer/device where you want to make a programm.

The Java language can be written in simple file, and then compiled with the Java compiler. There are many ways to compile the code: by console or by some IDE (Integrated Development Environment, a programming tool). The most easiest way to programm in any language is to use an IDE. Those tools help us to avoid programming mistakes, import mistakes...

The Java language can interact with many external devices, but for this cases, you must import the specific libraries. Those libraries must be correctly imported, otherwise the programm will not run properly. 

The worst thing of the Java language, from my side, is the difficulty for working with some utilities of the operating system, like files, serial ports, mouses, keybords... Apart from this, the Java language is one of the most used languages, it can used for a lot of utilities and have a lot of frameworks for the web programming.