Java Tutorial Part 1
Java Tutorial Part 1
Java Tutorial Part 1
org)
Hello, World!(tutorial 1)
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.
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.
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!");
Execute Code
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.
Exercise
Print "Hello, World!" to the console.
Java is a strong typed language, which means variables need to be defined before we use them.
Numbers
int myNumber = 5;
Execute Code
double d = 4.5;
d = 3.0;
Execute Code
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';
Execute Code
String is not a primitive. It's a real type, but Java has special treatment for String.
There is no operator overloading in Java! The operator + is only defined for strings, you will
never see it with other objects, only 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;
int children = 0;
b = children; // Will not work
if (children) { // Will not work
// Will not work
}
Next Tutorial
Conditionals(tutorial 3)
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!");
}
Execute Code
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!");
}
Execute Code
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
Execute Code
if (a == b) {
// a and b are equal, let's do something cool
}
Execute Code
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... :/
}
Execute Code
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...");
Execute Code
Or
if (a == b)
System.out.println("Another line Wow!");
else
System.out.println("Double rainbow!");
Execute Code
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).
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;
}
Execute Code
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:
Arrays(tutorial 4)
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;
Execute Code
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);
Execute Code
arr[0] = 4;
arr[1] = arr[0] + 5;
Execute Code
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.
Don't try to print the array without a loop, it will print something nasty like [I@f7e6a96.
Loops(tutorial 5)
There are two kind of loops in Java, for and while.
For
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...
Execute Code
We can omit the first and third section of the loop (although it will be weird), and the loop will
still work:
For cases where we want to use a loop that look like that, we use a while loop
While
while (condition) {}
Execute Code
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
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:
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.
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
Execute Code
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
Execute Code
Functions(tutorial 6)
In Java, all function definitions must be inside classes. We also call functions methods. Let's
look at an example method
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.
int a = 3;
int b = 5;
bar(a, b);
Execute Code
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;
Execute Code
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:
Again we can picture the same two lines in the beginning of bar2
Student s1 = joe;
Student s2 = jack;
Execute Code
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.
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.
Summary
class Point {
int x;
int y;
}
Execute Code
In order to create an instance of this class, we need to use the keyword new.
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.
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Execute Code
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;
}
Execute Code
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.
p.x = 3;
p.y = 6;
Execute Code
Methods
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);
}
Execute Code
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.
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.
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
Execute Code
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
Execute Code
Right!
java MyFirstClass
Execute Code
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.
javac Arguments.java
java Arguments arg0 arg1 arg2
Inheritance(tutorial 8)
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.
}
Execute Code
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:
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 Circle,
Rectangle, Triangle, Trapezoid, etc. - as long as they extend Shape.
Exercise
Create a rectangle class which inherits the Shape class and finds the area
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 than throw (more than the above).
But, how can you handle exceptions, when you're unsure if an error will occur.
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.
}
Execute Code
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.
Exercise
In this exercise, you will try to catch problematic code. I will create a problematic code block. I
want you to wrap the problematic code in the try block, than make it print "Problem with code
detected" if the exception is thrown.