IT WORLD

Welcome To The World Of IT

Free Training Programs

Free Training For Everyone, Everywhere And Every Time

Free Source Code

A Lot Of Source Code Is Waiting For You

Free IT Document For You !

A Lot Of IT Document Is Waiting For You !!

Source Code Game

Source Code Of Some Simple Game

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, May 17, 2016

Try and Catch in Java

Before going into try/catch statements, let's talk about Exceptions. Exceptions are thrown every time an error occurs. Some examples:ArrayIndexOutOfBounds is thrown if the index that does not exist in an array is accessed (e.g: Trying to access arr[5], but arr only goes up to arr[4])ArithmeticError is thrown if an illegal arithmetic operation is done (e.g: 42/0, division by zero)
There are lots of exceptions that Java can throw (more than the above).
But, how can you handle exceptions, when you're unsure if an error will occur.
That's the purpose of try/catch! This is the syntax for try/catch:
  try {
    //Code here
  } catch (ExceptionHere name) {
        //Replace ExceptionHere with your exception and name with the name of your exception.
        //Code if exception "ExceptionHere" is thrown.
  }
The code after the try block will be attempted to be run. If the exception in the catch statement is thrown during the code in the try block is run, run the code in the catch block.
You can tell the user that there is a problem, or anything else.
NOTE: You can also use Exception as the exception to catch if any exception is thrown.

Inheritance in Java

Inheritence in Java allows you to reuse code from an existing class into another class, you can derive your new class from an existing class. Your new class is called derived class which inherits all the members from its superclass.
The inherited fields can be used directly, just like any other fields. You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended). You can declare new fields in the subclass that are not in the superclass. The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. A subclass does not inherit the private members of its parent class.

An example of inheritence

Consider a class called Shape, Shape is the base class which is inherited by shapes like rectangle, square, circle etc.
public class Shape {
    public double area ()
    {
        return 0;     // Since this is just a generic "Shape" we will assume the area as zero.
                    // The actual area of a shape must be overridden by a subclass, as we see below.
                    // You will learn later that there is a way to force a subclass to override a method,
                    // but for this simple example we will ignore that.
    }
}
Class Shape is inherited by Circle which is a Shape.
The method area is defined in the base class and has been inherited in the circle class and method area is available with the circle class which is redefined specific to circle.
class Circle extends Shape {                    // The "extends" keyword is what we use to tell java that Circle inherits the functionality of Shape.

    private static final double PI = Math.PI;   // constant
    private double diameter;                    // This could be any number, representing the diameter of this circle.

    public double area () {
        double radius = diameter / 2.0;
        return PI * radius * radius;
    }

}
The advantage of using inheritance is that you can write code that can apply to a number of classes that extend a more general class. In the below example we have a method that takes the larger area from the two shapes:
public class Main {
    public static void main(String[] args) {
        Shape s1 = new Circle (5.0);
        Shape s2 = new Rectangle (5.0, 4.0);
        Shape larger = getLargerShape(s1,s2);

        System.out.println("The area of the larger shape is: "+larger.area());
    }

    public static Shape getLargerShape(Shape s1, Shape s2) {
        if(s1.area() > s2.area())
            return s1;
        else
            return s2;
    }
}
As you can see, getLargerShape() doesn't require the programmer to input a specific type of shape for its 2 parameters. You could use an instance of any class that inherits the type Shape as any of the two parameters for this method. You could use an instance of type CircleRectangleTriangle,Trapezoid, etc. - as long as they extend Shape.

Monday, May 16, 2016

Compiling and Running with Arguments in Java

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

Objects in Java

Everything in Java is within classes and objects. 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 usingpublic 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.

Functions in Java

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'

Loops in Java

There are two kind of loops in Javafor 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);
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);
}
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

Arrays in Java

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[0] = 4;
We can also create an array with values in the same line:
int[] arr = {1, 2, 3, 4, 5};

Conditionals in Java

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("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

Numbers in Java

To declare and assign a number use the following syntax:
int myNumber;
myNumber = 5;
Or you can combine them:
int myNumber = 5;
To define a double floating point number, use the following syntax:
double d = 4.5;
d = 3.0;
If you want to use float, you will have to cast:
float f = (float) 4.5;
Or, You can use this:
float f = 4.5f (f is a shorter way of casting float)

Characters and Strings

In Java, a character is it's own type and it's not simply a number, so it's not common to put an ascii value in it, there is a special syntax for chars:
char c = 'g';
String is not a primitive. It's a real type, but Java has special treatment for String.
Here are some ways to use a string:
// Create a string with a constructor
String s1 = new String("Who let the dogs out?");
// Just using "" creates a string, so no need to write it the previous way.
String s2 = "Who who who who!";
// Java defined the operator + on strings to concatenate:
String s3 = s1 + s2;
There is no operator overloading in Java! The operator + is only defined for strings, you will never see it with other objects, only primitives.
You can also concat string to primitives:
int num = 5;
String s = "I have " + num + " cookies"; //Be sure not to use "" with primitives.

boolean

Every comparison operator in java will return the type boolean that not like other languages can only accept two special values: true or false.
boolean b = false;
b = true;

boolean toBe = false;
b = toBe || !toBe;
if (b) {
    System.out.println(toBe);
}

int children = 0;
b = children; // Will not work
if (children) { // Will not work
    // Will not work
}

Hello World in Java

Java is an object oriented language (OOP). Objects in Java are called "classes".
Let's go over the Hello world program, which simply prints "Hello, World!" to the screen.
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
The first line defines a class called Main.
public class Main {
In Java, every line of code that can actually run needs to be inside a class. This line declares a class named Main, which is public, that means that any other class can access it. This is not important for now, so don't worry. For now, we'll just write our code in a class called Main, and talk about objects later on.
Notice that when we declare a public class, we must declare it inside a file with the same name (Main.java), otherwise we'll get an error when compiling.
When running the examples on the site, we will not use the public keyword, since we write all our code in one file.
The next line is:
public static void main(String[] args) {

This is the entry point of our Java program. the main method has to have this exact signature in order to be able to run our program.
  • public again means that anyone can access it.
  • static means that you can run this method without creating an instance of Main.
  • void means that this method doesn't return any value.
  • main is the name of the method.
The arguments we get inside the method are the arguments that we will get when running the program with parameters. It's an array of strings. We will use it in our next lesson, so don't worry if you don't understand it all now.
System.out.println("Hello, World!");
  • System is a pre-defined class that Java provides us and it holds some useful methods and variables.
  • out is a static variable within System that represents the output of your program (stdout).
  • println is a method of out that can be used to print a line.