Sunday, 1 February 2015

Learning C

Hey is February let us learn something new, we are going to teach ourselves C.
Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the C programming language.
There is no need to download anything - Just click on the chapter you wish to begin from, and follow the instructions. Good luck!
REMEMBER we value your comments.


Table of Contents

Learn the Basics

Advanced



Tuesday, 27 January 2015

Compiling and Running with Arguments


Compiling and Running with Arguments

This section is used for you to use Java at home and understand the basics of how things are done.
After creating a simple application that prints something to the screen, you need to compile your code and run it.
It shouldn't really matter if you use Linux, Mac or Windows. You need to have a console and you need to have the following commands available in order to compile and run Java.
  • java (or java.exe)
  • javac (or javac.exe)
In order for those to be available you must download and install JDK (Java Development Kit).
If we take the code from the previous lesson and put it in a file called MyFirstClass.java, in order to compile it we need to run:
javac MyFirstClass.java
 This will create a file called MyFirstClass.class that holds the compiled java code.
To run it, we need to run java with the name of the class as the argument (Not the file!)
Wrong
java MyFirstClass.class

this is just a repetition

Right!
java MyFirstClass


Arguments

The main methods get an array of strings as an argument, these are the command line arguments you may pass to your program.
Every array in java holds a variable called length that says how many elements are within that array.
We can go over the arguments with a simple for
public class Arguments {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}
 And to compile and run it with arguments:
javac Arguments.java
java Arguments arg0 arg1 arg2


Exercise

Create a program that prints the arguments of our program. Write one argument per line.

Objects


Objects

Everything in Java is within classes and objects(our main intrest). Java objects hold a state, state are variables which are saved together within an object, we call them fields or member variables.
Let start with an example:
class Point {
    int x;
    int y;
}

This class defined a point with x and y values.
In order to create an instance of this class, we need to use the keyword new.
Point p = new Point();


In this case, we used a default constructor (constructor that doesn't get arguments) to create a Point. All classes that don't explicitly define a constructor has a default constructor that does nothing.
We can define our own constructor:
class Point {
    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
This means we can not longer use the default constructor new Point(). We can now only use the defined constructor new Point(4, 1).
We can define more than one constructor, so Point can be created in several ways. Let's define the default constructor again.
class Point {
    int x;
    int y;

    Point() {
        this(0, 0);
    }

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
Notice the usage of the this keyword here. We can use it within a constructor to call a different constructor (in order to avoid code duplication). It can only be the first line within the constructor.
We also used the this keyword as a reference of the current object we are running on.
After we defined p we can access x and y.
p.x = 3;
p.y = 6;

Methods

We can now define methods on Point.
class Point {
    ... // Our code previously
    void printPoint() {
        System.out.println("(" + x + "," + y + ")");
    }

    Point center(Point other) {
        // Returns the center between this point the other point
        // Notice we are using integer, we wan't get an accurate value
        return new Point((x + other.x) / 2, (y + other.y) / 2);
    }
}

Public and Private

Although we'll talk about modifiers later on, it's important to understand the different between private and public variables and methods.
When using the keyword private before a variable or a method, it means only the class itself can access the variable or method, when we're using public it means everybody can access it. We usually see constructors defined as public, variables defined as private and methods are separated, some public and some private.

Exercise

Write a new method in Point called scale, that will make the point closer by half to (0,0). So for example, point (8, 4) after scale will be (4, 2).

Functions



In Java, all function definitions must be inside classes. We also call functions methods. Let's look at an example method
public class Main {
    public static void foo() {
        // Do something here
    }
}
foo is a method we defined in class Main. Notice a few things about foo.
  • static means this method belongs to the class Main and not to a specific instance of Main. Which means we can call the method from a different class like that Main.foo().
  • void means this method doesn't return a value. Methods can return a single value in Java and it has to be defined in the method declaration. However, you can use return by itself to exit the method.
  • This method doesn't get any arguments, but of course Java methods can get arguments as we'll see further on.

Arguments

I always like to say that arguments to Java methods are passed by value, although some might disagree with my choice of words, I find it the best way to explain and understand how it works exactly.
By value means that arguments are copied when the method runs. Let's look at an example.
public void bar(int num1, int num2) {
    ...
}
Here is a another place in the code, where bar is called
int a = 3;
int b = 5;
bar(a, b);
You can picture in your head that when bar(a, b) is run, it's like in the beginning of bar the following two lines are written:
int num1 = a;
int num2 = b;
And only then the rest of the method is run.
This means that a value get copied to num1 and b value get copied to num2. Changing the values of num1 and num2 will not affect a and b.
If the arguments were objects, the rules remain the same, but it acts a bit differently. Here is a an example:
public void bar2(Student s1, Student s2) {
    ...
}
And here is how we use it
Student joe = new Student("joe");
Student jack = new Student("jack");
bar2(joe, jack);
Again we can picture the same two lines in the beginning of bar2
Student s1 = joe;
Student s2 = jack;
But when we assign objects, it's a bit different than assigning primitives. s1 and joe are two different references to the same object. s1 == joe is true. This means that running methods on s1 will change the object joe. But if we'll change the value of s1 as a reference, it will not affect the reference joe.
s1.setName("Chuck"); // joe name is now Chuck as well
s1 = new Student("Norris"); // s1 is a new student, different than joe with the name of Norris
// s1 == joe   is not true anymore

Non static methods

Non static methods in Java are used more than static methods. Those methods can only be run on objects and not on the whole class.
Non static methods can access and alter the field of the object.
public class Student {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
Calling the methods will require an object of type Student.
Student s = new Student();
s.setName("Danielle");
String name = s.getName();

Student.setName("Bob"); // Will not work!
Student.getName(); // Will not work!

Summary

  • Every Java method has to be within a class
  • Static methods belong to a class while non-static methods belong to objects
  • All parameters to functions are passed by value, primitives content is copied, while objects are not copied and some would say 'passed by reference'

Exercise

Write the method printFullName of student which prints the full name of a student.

Loops


Loops

There are two kind of loops in Java, for and while.

For

The for loop has three sections:
 
for (int i = 0; i < 3; i++) {}


First section runs once when we enter the loop.
Second section is the gate keeper, if it returns true, we run the statements in the loop, if it returns false, we exit the loop. It runs right after the first section for the first time, then every time the loop is finished and the third section is run.
The third section is the final statement that will run every time the loop runs.
So in the case we have just seen, the loop will run 3 times. Here is the order of the commands:
int i = 0;
i < 3 // 0 < 3 = true
      // Inside of loop
i++ // i is now 1
i < 3 // 1 < 3 = true
      // Inside of loop
i++ // i is now 2
i < 3 // 2 < 3 = true
      // Inside of loop
i++ // i is now 3
i < 3 // 3 < 3 = false
      // Loop is done...
We can omit the first and third section of the loop (although it will be weird), and the loop will still work:
for (;i < 5;) {}
For cases where we want to use a loop that look like that, we use a while loop

While

The syntax is very similar to the previous for we looked at:
 
while (condition) {}

The condition will run for the first time when entering and every time the loop is done. If it returns false, the loop will not run.
If we want the loop to always run at least one, we can use do-while
do {

} while(condition);
Execute Code Notice the ; in the end of the do-while.

Foreach

Another version of for, is the foreach. The keyword we use is still for, but when we want to iterate on the elements inside an array we can simply use it:
int[] arr = {2, 0, 1, 3};
for (int el : arr) {
    System.out.println(el);
}
Execute Code This is a short version and equivalent to:
int[] arr = {1, 9, 9, 5};
for (int i = 0; i < arr.length; i++) {
    int el = arr[i];
    System.out.println(el);
}
Notice that if you want to use the index of the element inside the loop, you have to use the longer version and can't use foreach.

break and continue

These two keywords help us control the loop from within it. break will cause the loop to stop and will go immediately to the next statement after the loop:
int i;
for (i = 0; i < 5; i++) {
    if (i >= 2) {
        break;
    }
    System.out.println("Yuhu");
}
System.out.println(i);
// Output:
// Yuhu
// Yuhu
// 2
continue will stop the current iteration and will move to the next one. Notice that inside a for loop, it will still run the third section.
int i;
for (i = 0; i < 5; i++) {
    if (i >= 3) {
        break;
    }
    System.out.println("Yuhu");
    if (i >= 1) {
        continue;
    }
    System.out.println("Tata");
}
System.out.println(i);
// Output
// Yuhu
// Tata
// Yuhu
// Yuhu
// 3

Exercise

Loop through and print out all even numbers from the numbers list in the same order they are received. Don't print any numbers that come after 693 in the sequence.

Arrays


Arrays

Arrays in Java are also objects. They need to be declared and then created. In order to declare a variable that will hold an array of integers, we use the following syntax:
 
 
int[] arr;

Notice there is no size, since we didn't create the array yet.
 
arr = new int[10];


This will create a new array with the size of 10. We can check the size by printing the array's length:
System.out.println(arr.length);
We can access the array and set values:
arr[0] = 4;
arr[1] = arr[0] + 5;

Java arrays are 0 based, which means the first element in an array is accessed at index 0 (e.g: arr[0], which accesses the first element). Also, as an example, an array of size 5 will only go up to index 4 due to it being 0 based.
int[] arr = new int[5]
//accesses and sets the first element
arr[4] = 4;

We can also create an array with values in the same line:
int[] arr = {1, 2, 3, 4, 5};
Don't try to print the array without a loop, it will print something nasty like [I@f7e6a96.

Conditionals


Conditionals

Java uses boolean variables to evaluate conditions. The boolean values true and false are returned when an expression is compared or evaluated. For example:
int a = 4;
boolean b = a == 4;
if (b) {
    System.out.println("It's true!");
}
 Of course we don't normally assign a conditional expression to a boolean, we just use the short version:
int a = 4;
if (a == 4) {
    System.out.println("Ohhh! So a is 4!");
}


Boolean operators

There aren't that many operators to use in conditional statements and most of them are pretty strait forward:
int a = 4;
int b = 5;
boolean result;
result = a < b; // true
result = a > b; // false
result = a <= 4 // a smaller or equal to 4 - true
result = b >= 6 // b bigger or equal to 6 - false
result = a == b // a equal to b - false
result = a != b // a is not equal to b - true
result = a > b || a < b // Logical or - true
result = 3 < a && a < 6 // Logical and - true
result = !result // Logical not - false

if - else and between

The if, else statement in java is pretty simple.
if (a == b) {
    // a and b are equal, let's do something cool
}
And we can also add an else statement after an if, to do something if the condition is not true
if (a == b) {
    // We already know this part
} else {
    // a and b are not equal... :/
}
 The if - else statements doesn't have to be in several lines with {}, if can be used in one line, or without the {}, for a single line statment.
if (a == b) System.out.println("Yeah!");
else System.out.println("Ohhh...");
 Or
if (a == b)
    System.out.println("Another line Wow!");
else
    System.out.println("Double rainbow!");
 Although this method might be useful for making your code shorter by using fewer lines, we strongly recommend for beginners not to use this short version of statements and always use the full version with {}. This goes to every statement that can be shorted to a single line (for, while, etc).

The ugly side of if

There is a another way to write a one line if - else statement by using the operator ? :
int a = 4;
int result = a == 4 ? 1 : 8;
// result will be 1
// This is equivalent to
int result;
if (a == 4) {
    result = 1;
} else {
    result = 8;
Again, we strongly recommend for beginners not to use this version of if.

== and equals

The operator == works a bit different on objects than on primitives. When we are using objects and want to check if they are equal, the operator == wiil say if they are the same, if you want to check if they are logically equal, you should use the equals method on the object. For example:
String a = new String("Wow");
String b = new String("Wow");
String sameA = a;

boolean r1 = a == b;      // This is false, since a and b are not the same object
boolean r2 = a.equals(b); // This is true, since a and b are logically equals
boolean r3 = a == sameA;  // This is true, since a and sameA are really the same object