Notes on some Basics in Java
written by Scott McElfresh
last modified September 27, 2004
(based on earlier documents by Scott and documents by Don Slater)
(This document is still in draft form. Please inform Scott of any
errors.)
Comments
and Documentation
There are two ways to indicate comments in a Java program. The
first is two backslashes ( \\). This indicates to the
compiler to ignore the rest of the line. The second is to
have /* and */ surrounding the text that
you wish to be a comment - often useful for multi-line comments.
Javadoc is a particular
way of formatting comments so that various browsers and other software
can format your documentation.
Identifiers.
The names of variables, classes, and methods are identifiers. The
rules for identifiers in Java are similar to most other languages.
- Letters and numbers (and the underscore character, but I rarely
use this).
- Must start with a letter.
- Is case-sensitive. (Capitalization matters. ie
"Number" is not the same as "number".)
- Although not required by Java, the name should be descriptive of
what the variable is represents.
There are some heuristics that are used by most java programmers regarding identifier naming. These include:
- In identifiers comprised of multiple words, each word (except for
perhaps the first) starts with an upper case letter, while the other
letters are lower case.
- Class names start with a capital letter.
- Variables start with lower case letters.
Variable
Declarations
Variables are declared by uttering the type or class of the variable,
then whitespace, followed by the name of the variable. EG:
int number;
double price;
String name;
Note that semicolons end each variable declaration statement (as well
as other statements).
Primitive Types
Java has primitive types and reference types. The primitive
types are for variables that contain a single piece of
information. References are for objects of classes.
The primitive types in Java are:
byte, short, int,
long, float, double, char, boolean
The first four are for integers. Unless we have a specific
situation that calls for something else, we usually use int for
integers. These are 4 bytes and can represent numbers
between -231 and 231 -1.
For real numbers, we have float and double available to us. In
basic java programming,we almost always use the double
type.
The type char
allows us to represent characters from the Unicode set. (Some of
you may be familiar with ASCII character set. Unicode is a
superset of ASCII and allows for more international
characters.) We represent a character literal by
apostrophes (single quotes) around the character in question.
EG: '4',
'e', ',', '\n' (the backslash
indicates a special character)
The type boolean
allows us to represent values that are either true or false.
All other types are reference types.
Assignment and Expressions
Variables are assigned values with the = sign. For instance:
int x;
x =
14; // assigns the value 14 to the variable x
We can also assign a variable in the same line we declare it. EG:
int x =
14; // declares x and assigns the value 14 to the
variable x
We have the usual, +, -, *, and / operators for numbers.
For integers, the / operator does integer division, meaning that the
result is an integer if both of the operands are integers.
For instance, 5/2 evaluates to 2 (because the
remainder is eliminated). However,
5.0/2 evaluates to 2.5 because one of the operands is a real
number, telling Java to give a real number
result.
For ints, there is an additional operator: %. This modulus operator says to return
the remainder after doing division. For instance, 5%2
evaluates to 1, because 5 divided by 2 is 2 with a remainder of 1.
The increment operator ++ can be used on integers.
x++; is equivalent to x = x + 1;
Output
To put something on the console window, we use the System class.
System.out.println("Hi
there");
will put the words Hi there on the console window. Future things
will be written on the next line. The print method will remain on
the same line for future printing. EG:
System.out.print("Hi");
System.out.println("there");
System.out.println("Goodbye");
would display:
Hithere
Goodbye
The quotes indicate that this is a literal string.
int x = 10;
System.out.print("Hi");
System.out.println("x");
would display:
Hix
while
int x = 10;
System.out.print("Hi");
System.out.println(x);
would display:
Hi10
We may also put multiple items to output by using the + operator (to
concatenate strings).
int x = 10;
System.out.println("Hi"
+ x + "goodbye");
would produce:
Hi10goodbye
If and If-Else
Java has if and if-else statements that operate like in other
languages.
if ( a boolean
test)
statement 1;
else
statement 2;
statement 3;
If the test is true, statement 1 is executed, if the test is false,
statement 2 is executed. Execution then proceeds to statement 3.
If you want more than one statement to be executed, you need to use the
groupers { and }. EG:
if (a boolean test)
{
statement 1A;
statement 1B;
}
else
{
statement2A;
statement2B;
}
statement 3
If there are no statements to be executed when the test is false, we
can eliminate the else part altogether.
Notes:
- Java requires parentheses around the test.
- For ease of reading, statements that are only executed under
certain conditions (here, statements 1, 1A,1B, 2, 2A, and 2B) should be
indented more than the if line.
Switch statement:
Java has a switch statement similar to switch and case statement in
other languages. You'll have to do some research to learn
about switch in Java.
Loops
Java has for loops, while loops, and do-while loops.
While loops:
The syntax of a while loop is:
while (boolean
test)
{
statement1;
statement2;
}
If
the test is true, the body of the loop is executed, and then the test
is tested again. Repeated until the test is false when it is
tested.
Notes:
- If there is only one statement to be repeated, the { }'s may be
eliminated.
- The body of the loop should be indented.
- There are parentheses around the boolean test, sometimes called
the loop guard.
- There is no semicolon after the first line (sometimes called the
loop header). If there is a semicolon there, the loop will
end on that line.
For Loops:
The for loop works like in many other languages. The syntax
is:
for (initialize
statement; boolean test; increment statement)
{
statement;
}
This is equivalent to:
initialize
statement;
while (
boolean test )
{
statement;
increment statement;
}
For instance,
for (int i = 0; i
< 10; i = i + 1)
System.out.println(i);
would write the numbers from 0 to 9 down the side of the console window.
Notes:
- If there is only one statement to be repeated, the { }'s may be
eliminated.
- The body of the loop should be indented.
- There is no need for parentheses around the boolean test,
sometimes called the loop guard.
- There is no semicolon after the first line (sometimes called the
loop
header). If there is a semicolon there, the loop will end
on that
line.
Do-while loops
These are similar to while loops except that the loop body executes
once before checking the boolean test.
do
{
statements;
} while (boolean test);
Notes:
- If there is only one statement to be repeated, the { }'s may NOT
be eliminated in a do-while loop.
- The body of the loop should be indented.
- There are parentheses around the boolean test, sometimes called
the loop guard.
Example:
int x = 10;
while
(x < 10)
{
System.out.println(x);
x++;
}
would produce nothing on the screen because
x is not less than 10.
|
int x = 10;
do
{
System.out.println(x);
x++;
}while
(x < 10);
would put the number 10 on screen because it prints
before checking of less than 10.
|
Boolean Expressions and Operators
Java has the usual boolean relational operators:
<, >, <=, >=. ==, and
!=. The != means not equal to. The
== is the test for equality, while the single equals sign is the
assignment operator (see above).
The ! operator is "not" or "opposite". Putting it in
front of an expression takes the opposite. EG: if (! (x
< 10)) ... Note that there are parentheses
around the entire test.
&& means and, while || means or.
As in other places, && means that both sides have to be true in
order for the whole expression to be true, while || means that only one
side has to be true in order for the whole expression to be true.
Importing Libraries:
Java comes with lots of library classes that can be used. For
instance, the java.io.BufferedReader library.
At the top of our program we put:
import
java.io.BufferedReader;
We can also put :
import
java.io.*; // the * says to import everything that is a
part of the io package of library classes.
Input
In Java, everything that gets read in requires some libraries and
utilizing Strings. All input is read as a string of
characters which must then be interpreted. For instance, if
the user types 17, it is read in as the character '1', followed
by the character '7'.
Two of the ways that Java can get input are described below:
Console input, and GUI input.
If you have a string S (eg String S = "17"), you can
convert it to an integer by using the parseInt method of the Integer
class:
int x = Integer.parseInt(S);
Console input:
In order to read what the user types into the console window, you must
create a BufferedReader variable associated with the console
window. That code can be copied from below:
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(input);
In order for this code to compile, you must import the proper
library. We do this by putting
import
java.io.*;
at the top of our file.
Once our console variable has been declared, we can get input, like so:
System.out.print("what
is your name? ");
String name;
name =
console.readLine(); // the readLine method reads in one
line of characters typed.
If we want a number, we have to do something like:
System.out.print("How
old are you? ");
String answer;
answer =
console.readLine(); // the readLine method reads in one
line of characters typed.
int age =
Integer.parseInt(answer);
In order for this to work, there is one additional issue that needs to
be dealt with. The code above for creating the console variable
can cause an IOException. If an IOException is thrown it must be caught or thrown
again. One easy way to handle this
(although not particularly elegant, by some measures) is to add throws
IOException to the end of the header of any method that uses a
BufferedReader variable. EG:
public
static void main (String[] args) throws IOException
GUI input:
If we want to bring up a nice looking window for the user to type into,
one way is to use the JOptionPane class. This means that we have
to import it:
import
javax.swing.JOptionPane;
We can then use it as such:
String name =
JOptionPane.showInputDialog("what is your name?");
String answer
= JOptionPane.showInputDialog("what is your age?");
int age =
Integer.parseInt(answer);
Arrays
Arrays work in Java similarly to other languages, but there are some
minor differences, conceptually and logistically. To
declare an array of ints, called list:
int [] list; // declare an array of ints, called list
OR
int list[]; // declare an array of ints, called list
This declares that we will be using an identifier list to refer to an
array of ints. However, there is no actual array yet. To
allocate actual memory for this array, we need to say:
list = new int [10]; // allocate memory to hold an array of 10 ints
Unlike some other languages, the size of the array does not have to be a constant. EG:
int x = 8;
list = new int [x];
However, note that if we change the value of x, we still have an array
to hold 8 ints. Arrays in Java can not be
resized. However, the identifiers representing arrays can be made
to refer to new arrays with a different size.
Access:
To access an individual element of an array, we use the [] subscripting notation for the index. EG:
list[3] = 6; // puts the int 6 in the array spot labeled (indexed) by 3.
If the length of the array <= 3, this will cause an exception,
usually halting the program (unless you've included other code
otherwise).
Note that Java starts indexing arrays at 0. Thus, an array of 5 ints has indices 0, 1, 2, 3, 4
Length:
You can ask an array for its length, but uttering: identifer.length. EG: list.length
Introduction to references with respect to arrays.
Consider the following code:
int []
list;
//line 1
list = new int [5]; //line 2
for (int i = 0; i < list.length; i ++)
list[i] = 2;
list = new int [8]; //line 6
for (int i = 5; i < 8; i ++)
list[i] = 3;
Line 1 creates an identifier called list. Line 2 says to create an array of 5 ints, and have list refer to that array.
The first for loop says to put the number 2 in all 5 boxes of the array.
Line 6 says to create a new array of 8 ints and have list refer to that array (rather than the original array from line 2).
The second for loop says to put the number 3 in the boxes indexed 5, 6, and 7.
At this time, what are in the boxes indexed 0,1,2,3, and 4?
We did not actually put anything in those boxes, so in some senses we
don't know what is in those boxes. Does Java automatically
set ints to 0? I will not address this here, so you
will need to research this.
Functions
Functions in Java are called methods. The are also often referred to as messages. Creating your own function follows the following form:
<access-modifier> <other-modifiers> <return-type> <identifier> (<parameter-list>)
{
<statement-list>
}
<access-modifier> can be private, public, protected, or package. If this is omitted, package is assumed. In this course, I expect you to not omit this part.
<other-modifiers> include static and final or nothing. This is often not useful.
<return-type> indicates the type of answer the function will give you. If there is no answer expected, then void is put here.
For the <parameter-list>, each parameter declaration is separated by a comma.
EG:
public void sayHello()
{
System.out.println("Hello");
}
public int multiply(int num1, int num2)
{
int answer = num1 * num2;
return num2;
}
Every program you write must have at least one method called main. The form of this method must be:
public static void main(String [] args)
{
}
The first statement in this method will be the first statement
to be executed during the program run. We will discuss in class
during the term what happens when there is more than one such method in
the code.
Overloading
Identifiers in Java can be overloaded. (ie, multiple things can have
the same name) In general, if Java can distinguish them by the context in
which they are used, it doesn't mind. For functions, it can distinguish
functions from one another by the parameter list. For instance, the
following functions are distinguishable because the number or type of parameters
is different for each.
void f(int x)
{
}
|
void f()
{
}
|
void f(int x, int y)
{
}
|
void f(int y, String s)
{
}
|
However, the following function:
void f (int a, int b)
{
}
would not be allowed because there is already a function called f with 2 int parameters.
Parameters
Parameters or arguments to methods (functions) in Java are
passed by value. Some other languages have "pass by
reference" or "var" parameters. These allow you to pass a
variable to a function. Once inside that function, the function
changes the value of the variable, AND that change affects the original
variable. This is NOT the case in Java. For example, consider this code:
void f1()
{
int x = 3;
f2(x);
System.out.println(x);
}
void f2(int x)
{
x = 5;
}
If function f1 above is executed, the number 3 will be printed out. The change inside f2 has no impact on the argument x.