Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
First Program
What is Java?
Java is an object-oriented programming language which was developed by Sun
Microsystems. Java programs are platform independant which means they can
be run on any operating system with any type of processor as long as the Java
interpreter is available on that system.
This creates a class called Hello. All class names must start with a capital letter.
The main part of the program must go between curly brackets after the class
declaration. The curly brackets are used to group together everything inside
them.
We must now create the main method which is the section that a program starts.
}
}
The word public means that it is accessible by any other classes. static means
that it is unique. void is the return value but void means nothing which means
there will be no return value. main is the name of the method. (String[] args) is
used for command line parameters. Curly brackets are used again to group the
contents of main together. You probably won't understand a few of the things that
have just been said but you will know what they mean later on. For now it is
enough just to remember how to write that line.
You will see that the main method code has been moved over a few spaces from
the left. This is called indentation and is used to make a program easier to read
and understand.
Here is how you print the words Hello World on the screen:
Make sure that you use a capital S in System because it is the name of a class.
println is a method that prints the words that you put between the brackets after it
on the screen. When you work with letters like in Hello World you must always
put them between quotes. The semi-colon is used to show that it is the end of
your line of code. You must put semi-colons after every line like this.
Make sure you have a command prompt open and then enter the following:
javac Hello.java
If you did everything right then you will see no errors messages and your
program will be compiled. If you get errors then go through this lesson again and
see where your mistake is.
java Hello
Do not add .class on to the end of Hello. You will now see the following output on
the screen:
Hello World
Comments
Comments are written in a program to explain the code. Comments are ignored
by the compiler and are only there for people. Comments must go between a /*
and a */ or after //. Here is an example of how to comment the Hello World
program:
Variable types
There are 3 different types of data that can be stored in variables. The first type
is the numeric type which stores numbers. There are 2 types of numeric
variables which are integer and real. Integers are whole numbers such as
1,2,3,... Real numbers have a decimal point in them such as 1.89 or 0.12.
Character variables store only 1 letter of the alphabet. You must always put the
vlaue that is to be stored in a character variable inside single quotes. A string
variable is like a chracter variable but it can store more than 1 character in it. You
must use double quotes for a string instead of single quotes like with a character.
Declaring variables
You can declare a variable either inside the class curly brackets or inside the
main method's curly brackets. You declare a variable by first saying which type it
must be and then saying what its name is. A variable name can only include any
letter of the alphabet, numbers and underscores. Variable names can start with a
$ but may not start with a number. Spaces are not allowed in variable names.
You usually start a variable name with a lower case letter and every first letter of
words that make up the name must be upper case. Here is an example of how
you declare an integer variable called MyVariable in the main method:
If you want to declare more than 1 variable of the same type you must seperate
the names with a comma.
Using variables
A = is used to store a value in a variable. You put the variable name on the left
side and the value to store in the variable on the right side. Remember to use
quotes when storing String values. You can also store a value in a variable when
it is declared or later in the program.
Variables in calculations
The important thing about variables is that they can be used in calculations.
When you perform a calculation you must store the result in a variable which can
also be a variable that is used in the calculation.. Here is an example of how to
add 2 numbers together and store the result in a variable:
{
int answer;
answer = 2 + 3;
}
}
Once you have stored a value in a variable you can use it in a calculation just like
a number.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder of division
Constants
Constants are variables with values that can't be changed. The value is assigned
to a constant when it is declared. Constants are used to give names to certain
values so that their meaning is more obvious. The meaning of the number 3.14 is
not obvious but if it was given the name PI then you know immediatly what it
means.Use the word final in front of a normal variable declaration to make it a
constant.
Decisions
What are decisions?
Decisions are a way of allowing a program to choose which code to run. If a
condition is met then one section of code will be run and if it is not met then
another section can be run.
If you change i to 4 and run this program again you will see that no message is
printed.
Relational operators
You will see that a == has been used to test if the values are equal. It is
important to know that a = is for setting a value and a == is for testing a value.
The == is called a relational operator. Here is a table of the other relational
operators that can be used:
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
else
We know that if the condition is true then the code directly afer the if statement is
run. You can run code for when the condition is false by using the else
statement.
Grouping statements
If you want to run more than 1 line of code in an if statement then you must group
them together with curly brackets.
Nested if structures
You can put if statements inside other if statments which will make them nested if
structures. It is sometimes more efficient to use nested if statements such as in
the following example which finds out if a number is positive, negative or zero:
}
}
}
}
Loops
What is a loop?
A loop is a way of repeating lines of code. If you want to for example print Hello
on the screen 10 times then you can either use System.out.println 10 times or
you can put 1 System.out.println in a loop that runs 10 times which takes a lot
less lines of code.
For loop
The for loop goes from a number you give it to a second number you give it. It
uses a loop counter variable to store the current loop number. Here is the format
for a for loop:
You first set the loop counter variable to the starting value. Next you set the end
condition. While the condition is true the loop will keep running but when it is
false then it will exit the loop. The last one is for setting the amount by which the
loop variable must be increased by each time it repeats the loop. Here is how
you would do the example of printing Hello 10 times using a for loop:
If you want to use more than 1 line of code in a loop then you must group them
together between curly brackets.
While loop
The while loop will repeat itself while a certain condition is true. The condition is
only tested once every loop and not all the time while the loop is running. If you
want to use a loop counter variable in a while loop then you must initialize it
before you enter the loop and increment it inside the loop. Here is the Hello
example using a while loop:
Do while loop
The do while loop is like the while loop except that the condition is tested at the
bottom of the loop instead of the top.
}
while (i <= 10)
}
}
You will see that it says "throws Exception" at the end of the main method
declaration. An exception is an error and "throws Exception" tells java to pass the
error to the operating system for handling. Your program will not compile if you
don't put this in.
Reading strings
The easiest way to read a string is to use the graphical input dialog. We must
import the JOptionPane.showInputDialog method before we can use it. Then we
can use the JOptionPane.showInputDialog method to read the string. We can
print the entered string using the JOptionPane.showMessageDialog method. You
must then put a System.exit(0) at the end of the program or else the program will
not stop running.
import javax.swing.*;
Type conversions
Once you have read a string you might want to convert it to another data type
such as an integer. You have already seen in a previous example that you must
use the type that you want to convert to between brackets in front of the variable
to be converted. Here is an example of some conversions:
Strings are not variables but actually classes which is why we must use the
Integer.parseInt() method to convert a string to an integer.
import javax.swing.*;
Arrays
What is an array
An array is group of variables that is given only one name. Each variable that
makes up the array is given a number instead of a name which makes it easier to
work with using loops among other things.
Declaring an array
Declaring an array is the same as declaring a normal variable except that you
must put a set of square brackets after the variable type. Here is an example of
how to declare an array of integers called a.
Instead of assigning memory to the array you can assign values to it instead.
This is called initializing the array because it is giving the array initial values.
Using an array
You can access the values in an array using the number of the element you want
to access between square brackets after the array's name. There is one
important thing you must remember about arrays which is they always start at 0
and not 1. Here is an example of how to set the values for an array of 5
elements.
Sorting an array
Sometimes you will want to sort the elements of an array so that they go from the
lowest value to the highest value or the other way around. To do this we must
use the bubble sort. A bubble sort uses an outer loop to go from the last element
of the array to the first and an inner loop which goes from the first to the last.
Each value is compared inside the inner loop against the value in front of it in the
array and if it is greater than that value then it is swapped. Here is an example.
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
2D arrays
So far we have been using 1-dimensional or 1D arrays. A 2D array can have
values that go not only down but also across. Here are some pictures that will
explain the difference between the 2 in a better way.
1D Array
0 1
1 2
2 3
3 4
4 5
2D Array
0 1 2
01 2 3
14 5 6
27 8 9
All that you need to do to create and use a 2D array is use 2 square brackets
instead of 1.
Object-Oriented Programming(OOP)
What is Object-Oriented Programming?
Object oriented programming or OOP is a way of writing programs using objects.
An object is a data structure in memory that has attributes and methods. The
attributes of an object are the same as variables and the methods of an object
are the same as functions or procedures.
The reason for using objects instead of the old procedural method of
programming is because objects group the variables and methods about
something together instead of keeping them all apart as in procedural
programming. There are many other reasons why OOP is better which you will
learn about later.
Creating a class
You have already been creating classes in the programs you have written so far.
To show you how they work we will need to create a separate class in a separate
file. This class will be called Student.
Now we will add 2 variables to the class which are the student's name and
student number.
Next we must add methods for getting and setting these variables.
String studentName;
int studentNumber;
Instantiating an object
Now that we have finished writing the class we must create the main program
that will instantiate the object. We will call the main program class TestClass. It
should look just like how every other java program starts off.
Now we will instantiate the object. To do this we declare a reference to the object
called stu and set it equal to a newly created object in memory.
declared as public. This makes it safer to work with variables because they can't
be changed by mistake by another object.
Constructors
A constructor is a method that is run when an object is instantiated. Constructors
are useful for initializing variables. The constructor is declared with only the name
of the class followed by brackets. Here is an example of the Student class that
initializes both student name and student number.
Student()
{
studentName = "No name";
studentNumber = 1;
}
You can also pass parameters to a constructor when you instantiate an object.
All you need to do is add the parameters in the brackets after the constructor
declaration just like a normal method.
Student(String s, int i)
{
studentName = s;
studentNumber = i;
}
Now all you need to do is put the parameters in the brackets when you
instantiate the object in the main program.
Inheritance
What is inheritance?
Inheritance is the ability of objects in java to inherit properties and methods from
other objects. When an object inherits from another object it can add its own
properties and methods. The object that is being inherited from is called the
parent or base class and the class that is inheriting from the parent is called the
child or derived class.
class Person
{
private String name;
Now we will create the Student class that has a variable for the student number
and the get and set methods for student number. The extends keyword is used to
inherit from the Person class in the following example.
Finally we have to create a program that will instantiate a Student object, set the
name and student number and then print the values using the get methods.
Abstract inheritance
Abstract classes are created only for the purpose of being inherited from. In fact
you can't instantiate an object from an abstract class. You must put the abstract
keyword in front of the class name declaration to create an abstract class. We
can change the Person class above to show how it works.
Interfaces
Interfaces are like abstract classes because you can't instantiate them and they
are only used for being inherited from. The difference is that interfaces are not
allowed to have variables unless they are constants and methods are not allowed
to have a body. The point of an interface is for you to override the methods that
are declared in it. You must use the implements keyword instead of extends
when using interfaces. Here is an example of the Person class as an interface
and the Student class that uses the Person interface.
interface Person
{
public void setName(String n);
public String getName();