Você está na página 1de 23

DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

What you will need


You will need the Java software development kit from Sun's Java site. Follow the
instructions on Sun's website to install it. Make sure that you add the java bin
directory to your PATH environment variable.

Writing your first Java program


You will need to write your Java programs using a text editor. When you type the
examples that follow you must make sure that you use capital and small letters in
the right places because Java is case sensitive. The first line you must type is:

public class Hello

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.

public class Hello


{

We must now create the main method which is the section that a program starts.

public class Hello


{
public static void main(String[] args)
{

}
}

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

By Mr Iwanga I Israel Page 1


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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:

public class Hello


{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

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.

Compiling the program


What we have just finished typing is called the source code. You must save the
source code with the file name Hello.java before you can compile it. The file
name must always be the same as the class name.

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.

Running the program


Once your program has been compiled you will get a file called Hello.class. This
is not like normal programs that you just type the name to run but it is actually a
file containing the Java bytecode that is run by the Java interpreter. To run your
program with the Java interpeter use the following command:

java Hello

By Mr Iwanga I Israel Page 2


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

Do not add .class on to the end of Hello. You will now see the following output on
the screen:

Hello World

Congratulations! You have just made your first Java program.

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:

/* This program prints the words Hello World on the screen */


public class Hello // The Hello class
{
public static void main(String[] args) // The main method
{
System.out.println("Hello World"); // Print Hello World
}
}

Variables and constants


What is a variable
Variables are places in the computer's memory where you store the data for a
program. Each variable is given a unique name which you refer to it with.

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.

Boolean variables can store 1 of 2 values which are True or False.

Here is a table of the types of variables that can be used:

By Mr Iwanga I Israel Page 3


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

Name Type Values


Numeric -
byte -128 to 127
Integer
Numeric -
short -32 768 to 32 767
Integer
Numeric -
int -2 147 483 648 to 2 147 483 647
Integer
Numeric - -9 223 372 036 854 775 808 to 9 223 372 036 854 775
long
Integer 807
float Numeric - Real -3.4 * 1038 to 3.4 * 1038
double Numeric - Real -1.7 * 10308 to 1.7 * 10308
char Character All unicode characters
String Character All unicode characters
boolean Boolean True or False

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:

public class Variables


{
public static void main(String[] args)
{
int myVariable;
}
}

If you want to declare more than 1 variable of the same type you must seperate
the names with a comma.

public class Variables


{
public static void main(String[] args)
{
int myVariable, myOtherVariable;
}
}

By Mr Iwanga I Israel Page 4


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class Variables


{
public static void main(String[] args)
{
int myInteger;
myInteger = 5;
String myString = "Hello";
}
}

You can print variables on the screen with System.out.println.

public class Variables


{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";
System.out.println(myInteger);
System.out.println(myString);
}
}

You can join things printed with System.out.println with a +.

public class Variables


{
public static void main(String[] args)
{
int myInteger = 5;
System.out.println("The value of myInteger is " + myInteger);
}
}

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:

public class Variables


{
public static void main(String[] args)

By Mr Iwanga I Israel Page 5


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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

public class Variables


{
public static void main(String[] args)
{
int answer;
int number = 2;
answer = number + 3;
}
}

Here is a table of operators which can be used in calculations:

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.

public class Variables


{
public static void main(String[] args)
{
final double PI = 3.14;
}
}

By Mr Iwanga I Israel Page 6


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

The if decision structure


The if statement evaluates a condition and if the result is true then it runs the line
of code that follows it. Here is an example of how to test if the value of a variable
called i is equal to 5:

public class Decisions


{
public static void main(String[] args)
{
int i = 5;
if (i == 5)
System.out.println("i is equal to 5");
}
}

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

By Mr Iwanga I Israel Page 7


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class Decisions


{
public static void main(String[] args)
{
int i = 4;
if (i == 5)
System.out.println("i is equal to 5");
else
System.out.println("i is not equal to 5");
}
}

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.

public class Decisions


{
public static void main(String[] args)
{
int i = 4;
if (i != 5)
{
System.out.println("i not is equal to 5");
System.out.println("i is equal to " + i);
}
}
}

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:

public class Decisions


{
public static void main(String[] args)
{
int i = 1;
if (i > 0)
System.out.println("Positive");
else
if (i < 0)
System.out.println("Negative");
else
System.out.println("Zero");

By Mr Iwanga I Israel Page 8


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

}
}

AND, OR and NOT


You can test if more than 1 condition is true using the AND(&&) operator. To test
if only 1 of many conditions is true use the OR(||) operator. The NOT(!) operator
will change a true to a false and a false to a true.

public class Decisions


{
public static void main(String[] args)
{
int i = 1;
int j = 1;
if (i == 1 && j == 1)
System.out.println("i is 1 and j is 1");
if (i == 1 || j == 2)
System.out.println("Either i is 1 or j is 1");
if (!(i == 1))
System.out.println("i is not 1");
}
}

The switch decision structure


The switch structure is like having many if statements in one. It takes a variable
and then has a list of actions to perform for each value that the variable could be.
It also has an optional part for when none of the values match. The break
statement is used to break out of the switch structure so that no more conditions
are tested.

public class Decisions


{
public static void main(String[] args)
{
int i = 3;
switch(i)
{
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is2");
break;
case 3:
System.out.println("i is 3");
break;
default:
System.out.println("Invalid value");
}

By Mr Iwanga I Israel Page 9


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

}
}

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:

for (set starting value; end condition; increment loop variable)

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:

public class Loops


{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
System.out.println("Hello");
}
}

Incrementing and decrementing


i++ has been used to add 1 to i. This is called incrementing. You can decrement i
by using i--. If you use ++i then the value is incremented before the condition is
tested and if it is i++ then i is incremented after the condition is tested.

Multiple lines of code in a loop

By Mr Iwanga I Israel Page 10


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

If you want to use more than 1 line of code in a loop then you must group them
together between curly brackets.

public class Loops


{
public static void main(String[] args)
{
int i;
for (i = 1; i <=10; i++)
{
System.out.println("Hello");
System.out.println(i);
}
}
}

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:

public class Loops


{
public static void main(String[] args)
{
int i = 1;
while (i <= 10)
{
System.out.println("Hello");
i++;
}
}
}

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.

public class Loops


{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println("Hello");
i++;

By Mr Iwanga I Israel Page 11


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

}
while (i <= 10)
}
}

Data input and type conversions


Until now we have set the values of variables in the programs. Now we will learn
how to get input from the user so that our programs are a bit more interesting
and useful.

Reading single characters


To read a single character from the user you must use the System.in.read()
method. This will return and integer value of the key pressed which must be
converted to a character. We use (char) in front of System.in.read() to convert
the integer to a character. After the user has pressed the key they must press
enter and we must put a second System.in.read() to catch this second key press.

public class ReadChar


{
public static void main(String[] args) throws Exception
{
char c;
System.out.println("Enter a character");
c = (char)System.in.read();
System.in.read();
System.out.println("You entered " + c);
}
}

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.

By Mr Iwanga I Israel Page 12


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

import javax.swing.*;

public class ReadString


{
public static void main(String[] args)
{
String s;
s = JOptionPane.showInputDialog("Enter your name");
JOptionPane.showMessageDialog(null, "Your name is " + s);
System.exit(0);
}
}

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:

public class Convert


{
public static void main(String[] args)
{
int i;
char c = 'a';
i = (int)c;
i = 5;
c = (char)i;
}
}

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.*;

public class ConvertString


{
public static void main(String[] args)
{
String s;
int i;
s = JOptionPane.showInputDialog("Enter a number");
i = Integer.parseInt(s);
JOptionPane.showMessageDialog(null, "The number you entered is "
+ i);
System.exit(0);
}
}

By Mr Iwanga I Israel Page 13


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class Array


{
public static void main(String[] args)
{
int[] a;
}
}

An array is more complex than a normal variable so we have to assign memory


to the array when we declare it. When you assign memory to an array you also
set its size. Here is an example of how to create an array that has 5 elements.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
}
}

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.

public class Array


{
public static void main(String[] args)
{
int[] a = {12, 23, 34, 45, 56};
}
}

Using an array

By Mr Iwanga I Israel Page 14


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
}
}

A much more useful way of using an array is in a loop. Here is an example of


how to use a loop to set all the values of an array to 0 which you will see is much
easier than setting all the values to 0 seperately.

public class Array


{
public static void main(String[] args)
{
int[] a = new int[5];
for (int i = 0; i < 5; i++)
a[i] = 0;
}
}

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.

public class Array


{
public static void main(String[] args)
{
int[] a = {3, 5, 1, 2, 4};
int i, j, temp;
for (i = 4; i >= 0; i--)
for (j = 0; j < i; j++)
if (a[j] > a[j + 1])

By Mr Iwanga I Israel Page 15


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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

public class Array


{
public static void main(String[] args)
{
int[][] a = new int[3][3];
a[0][0] = 1;
}
}

By Mr Iwanga I Israel Page 16


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

Using classes and objects


Before you can create an object you need to create a class. A class is the code
for an object and an object is the instance of a class in memory. When you
create an object from a class it is called instantiating the object. To help you
understand think of the plan for a house. The plan for the house is like the class
and the house that will be built from the plan is the object.

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.

public class Student


{
}

Now we will add 2 variables to the class which are the student's name and
student number.

public class Student


{
String studentName;
int studentNumber;
}

Next we must add methods for getting and setting these variables.

public class Student


{

By Mr Iwanga I Israel Page 17


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

String studentName;
int studentNumber;

public void setStudentName(String s)


{
studentName = s;
}

public void setStudentNumber(int i)


{
studentNumber = i;
}

public String getStudentName()


{
return studentName;
}

public int getStudentNumber()


{
return 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.

public class TestClass


{
public static void main(String[] args)
{
}
}

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.

public class TestClass


{
public static void main(String[] args)
{
Student stu = new Student();
}
}

Using the object


Now we can call the methods from the stu object to set the values of its
variables. You can't set the values of the variables in an object unless they are

By Mr Iwanga I Israel Page 18


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

declared as public. This makes it safer to work with variables because they can't
be changed by mistake by another object.

public class TestClass


{
public static void main(String[] args)
{
Student stu = new Student();
stu.setStudentName("John Smith");
stu.setStudentNumber(12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}

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.

public class Student


{
String studentName;
int studentNumber;

Student()
{
studentName = "No name";
studentNumber = 1;
}

public void setStudentName(String s)


{
studentName = s;
}

public void setStudentNumber(int i)


{
studentNumber = i;
}

public String getStudentName()


{
return studentName;
}

public int getStudentNumber()


{
return studentNumber;
}
}

By Mr Iwanga I Israel Page 19


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class Student


{
String studentName;
int studentNumber;

Student(String s, int i)
{
studentName = s;
studentNumber = i;
}

public void setStudentName(String s)


{
studentName = s;
}

public void setStudentNumber(int i)


{
studentNumber = i;
}

public String getStudentName()


{
return studentName;
}

public int getStudentNumber()


{
return studentNumber;
}
}

Now all you need to do is put the parameters in the brackets when you
instantiate the object in the main program.

public class TestClass


{
public static void main(String[] args)
{
Student stu = new Student("John Smith",12345);
System.out.println("Student Name: " + stu.getStudentName());
System.out.println("Student Number: " + stu.getStudentNumber());
}
}

By Mr Iwanga I Israel Page 20


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

How to use inheritance


We will first create a parent class called Person. We will then create a child class
called Student. Then we will create a program to use the Student class. The
following is a Person class which has a variable for the person's name. There are
also set and get methods for the name.

class Person
{
private String name;

public void setName(String n)


{
name = n;
}

public String getName()


{
return 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.

class Student extends Person


{
private String stuNum;

public void setStuNum(String sn)


{
stuNum = sn;
}

public String getStuNum()


{
return stuNum;
}
}

By Mr Iwanga I Israel Page 21


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

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.

public class TestInheritance


{
public static void main(String[] args)
{
Student stu = new Student();
stu.setName("John Smith");
stu.setStuNum("12345");
System.out.println("Student Name: " + stu.getName());
System.out.println("Student Number: " + stu.getStuNum());
}
}

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.

abstract class Person


{
private String name;

public void setName(String n)


{
name = n;
}

public String getName()


{
return name;
}
}

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();

By Mr Iwanga I Israel Page 22


DEPARTMENT OF INFORMATION TECHNOLOGY 2010

class Student implements Person


{
private String stuNum;
private String name;

public void setStuNum(String sn)


{
stuNum = sn;
}

public String getStuNum()


{
return stuNum;
}

public void setName(String n)


{
name = n;
}

public String getName()


{
return name;
}
}

By Mr Iwanga I Israel Page 23

Você também pode gostar