Java
|
Java Overview
Java is a compiled, object-oriented programming language developed by Sun
Microsystems and originally released in 1995. Along with C/C++, it is one of the leading
programming languages today.
The fact that Java is a compiled language means that after Java code is written,
it must be converted (by a compiling program) into bytecode, which is easier for
the computer to understand and makes the program run faster.
To say that Java is object-oriented means that it is designed to facilitate user-defined
objects and promote the interactions and relationships between them. As a consequence, programs
written in Java are relatively easy to write and maintain.
The most common object in Java is a class. In fact, all Java code must be written inside a class,
similar to how HTML is written between the pair of tags <html> and </html>. A class contains
attributes and methods. Attributes are just variables holding information about the class.
For example, if you had a class "Student", its attributes might include "Name", "Class", "Schedule", and "Grades".
Methods are actions a class can take. In our "Student" class, methods could include "Study", "DoHomework", and "TakeTest".
We will see how to declare an attribute when we learn about datatypes. To declare a method, simply write:
|
public returnType nameOfMethod(arguments){InstructionsInJavaCode}
|
Here, returnType is what your method produces (as a datatype), whether it be text, a number, a true/false value, a
user-defined object, or nothing at all. We will see more about this when we discuss datatypes. The arguments inside
the parentheses are any information you want to give to the method for it to manipulate. Of course, nameOfMethod
is whatever you want to call your method and InstructionsInJavaCode are the instructions written in Java.
The most important method in a class is its main method. Since it is so important, it has special syntax:
|
public static returnType main(String[] args){InstructionsInJavaCode}
|
The main method is optional, but if a class has one, it is run whenever the class is.
Finally, we need to know how to make a class. The syntax is:
|
public class nameOfClass{AttributesAndMethods}
|
Again, nameOfClass is the name of the class and AttributesAndMethods are whatever attributes and methods
you want your class to have.
As an example, we will write a class that will print a message to the screen. We use the command
|
System.out.print(message);
|
to print message to the screen. Here is the class:
public class MessagePrinter{
public static void main(String[] args){
System.out.print("Hello.");
}
}
|
|
Datatypes
Java includes a number of datatypes for use in programming,
each supporting a different use. There are eight primitive
datatypes falling into four categories:
Integer Datatypes: There are four datatypes that deal
with integers. The difference in them is always how big an integer
it can store. A byte can hold integers between -128 and 127.
A short can hold integers between -32,768 and 32,767. An int
can hold integers between -2,147,483,648 and 2,147,483,647. Finally, a long
can hold integers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.
The larger the numbers it can hold, the more computer memory it takes to store that datatype.
If memory is not a concern, ints are typically used. Integer datatypes all
support some integer operations:
| Operation | Symbol | Returns |
| Addition | a + b | The sum of a and b |
| Subtraction | a - b | The difference of a and b |
| Multiplication | a * b | The product of a and b |
| Integer Division | a / b | The largest integer that is at most a divided by b |
| Modulo | a % b | The remainder when a is divided by b |
Real Number Datatypes: There are two datatypes for real numbers, that is, numbers with decimal parts.
The first type is float and the second is double. As with the integer datatypes, the difference is
the size of the numbers they can hold. Doubles hold more positions both to the left and to the right of the
decimal point, so if memory is not at a premium, a double is typically used. Both real number datatypes support
the following operations:
| Operation | Symbol | Returns |
| Addition | a + b | The sum of a and b |
| Subtraction | a - b | The difference of a and b |
| Multiplication | a * b | The product of a and b |
| Division | a / b | The quotient of a by b |
| Modulo | a % b | The remainder when a is divided by b |
Booleans: A boolean is simply a true/false value, and there is only one boolean datatype, namely boolean.
Java supports these operations on booleans:
| Operation | Symbol | Returns |
| AND | a && b | True if a and b are both true and false otherwise |
| OR | a || b | True if at least one of a and b is true and false otherwise |
| NOT | !a | True if a is false and false if a is true |
Characters: Java supports one character datatype, the char. It can hold alphanumeric symbols and punctuation marks.
Related to characters are Strings, which are, strictly speaking, not a Java datatype, but they behave in much the same way as primitive datatypes.
A String is just a string of characters, like "This is a String". Java supports the following String operations:
| Operation | Symbol | Returns |
| Concatenation | a + b | a followed by b, so if a="Hi " and b="there!", a+b="Hi there!" |
| Length | a.length() | The number of characters in a |
To make a variable to store information, you type "datatype variableName;", as in "int i;" or "char c;". Notice the semicolon
at the end of the assignment: ALL COMMANDS MUST END WITH A SEMICOLON!.Once you have made the
variable you can assign it a value by writing "variableName = desiredValue;". WHEN ASSIGNING A VALUE TO A VARIABLE, THE VARIABLE MUST BE ON
THE LEFT AND THE VALUE ON THE RIGHT! You can combine the last two steps as in "int i=10;". There is something to be careful of here. When you assign values to a char or String, you might
make a statement like "char c = b". But then Java does not know if you want the variable c to hold the value of the variable b or to hold the character b.
To avoid this ambiguity, character literals (the symbols a char can hold) must be enclosed in single quotes and String literals in double quotes, as in
"char c = 'b'" or "String s = "String"".
Sometimes you want to treat one datatype like another to make use of different operations. For example, suppose you want to divide one int, a, by another, b.
The Java code a/b executes integer division, so 7/3 would be 2. If you want the true quotient, 2.333, you need to execute real number division. You can
accomplish this with the code " (double) a/b". This says "treat a like a real-number double, and divide it by b accordingly". Since doubles use
real-number division, this produces the desired quotient. The process of treating one datatype like another is called casting.
|
Booleans
Boolean variables themselves do not sound too impressive, since they are just true/false values. However, booleans are what allow Java to
test relationships and take actions conditionally.
Some relations we are familiar with are equality and comparison. For example, suppose we have to ints, a and b. The way
Java tests if a and b are equal is with the "==" operator. The code "a==b" returns True if they are equal and False otherwise.
Since "a==b" is a true/false value, it is a boolean. We could assign its value to a variable as in "boolean equals = (a==b)".
Similarly, we could write "a<b" to determine if a is less than b, and this would be a boolean. We summarize common relations below:
| == | Equals |
| < | Less Than |
| > | Greater Than |
| <= | Less Than or Equal To |
| >= | Greater Than or Equal To |
The main reason booleans are important is that they allow programs differently in different situations. For example, suppose I have an int called x whose absolute
value I need to know. The problem is that the absolute value of x is simply x if x is greater than or equal to 0 and -x otherwise. In Java, these "if" statements are almost
as easy as in English:
|
int absoluteValueOfx ;
if (x >= 0){absoluteValueOfx = x ;}
if (x < 0){absoluteValueOfx = (-1)*x;}
|
Java even has an "else" keyword to better handle the "otherwise" clause:
|
int absoluteValueOfx ;
if (x >= 0){absoluteValueOfx = x ;}
else {absoluteValueOfx = (-1)*x;}
|
These if... and if...else... have a fairly easy syntax: the boolean condition following the if is enclosed in parentheses, and the code you want executed
if the condition is true is enclosed in curly braces.
|
Arrays
An array is a collection of objects of the same datatype. For example, if you have twenty names you need to store, rather than create
twenty String variables, just create a String array to hold them. Arrays make the information easier to store and retrieve.
To declare an array, use the command "datatype[] arrayName = new datatype[lengthOfArray]". Here, datatype
is the datatype of the variables in the array, arrayName is what you want to call the array, and lengthOfArray is how many variables
you want the array to hold. In the last paragraph, we decided to use a String array to hold twenty names. I could create that array by writing
"String [ ] Names = new String [ 20 ] ;". If I wanted to create an array of 12 ints called myIntArray, I would type "int [ ] myIntArray = new int [ 12 ] ;".
Once we have an array, we will want to fill it with values. If we want to fill in the ith element of the array arr with a value val, type
"arr [ i-1 ] = val ;". Notice that the ith element of the array is indexed with i-1, so the first is arr[0], the second is arr[1], and so on.
If there were 20 elements in arr, then the last element would be arr[19]. This is important, and is probably the most common error with arrays: ARRAYS
ARE ALWAYS INDEXED STARTING WITH 0.
Sometimes you are given an array to work with but you do not know how many elements it holds. This makes things like finding its last element difficult. Java has
a built-in operation to help us with this: length. For an array arr, we can get its length using arr.length. With this in mind, we can get the last element
of arr with the expression "arr [ arr.length - 1 ] ", without eer knowing how many elements arr has.
|
Loops
One of the most important features of programming languages is the ability to repeat tasks. Java supports repetition through loops.
There are three kinds of loops in Java, namely the for loop, the while loop, and the do...while loop (which we will not discuss). All of these loops
accomplish the same thing in that anything you can do with one you can do with the other two. Often, though, one kind of loop is easier to write
in a given situation, so that is the one to use.
A for loop uses the following syntax: for ( initialization ; endingCriterion ; update ) { codeToRun }. Here,
initialization does some setup work for you, like setting variables to their starting values. The endingCriterion is a condition that, if true,
causes codeToRun to run. After the code is run, update is executed, and the endingCriterion is tested again. This continues
until endingCriterion is false. One use of a for-loop would be to print all the elements in an array arr:
|
for ( int i = 0 ; i < arr.length ; i + + ) {System.out.print ( arr [ i ] + " ") ; }
|
A while loop uses the following syntax: while ( condition ) { codeToRun }. This checks condition, and if it
is true it runs codeToRun. This continues until condition is false. While-loops are often the best loop if a code must be executed until
something happens. For example, suppose you were playing a game where you continually roll a die. If you roll a 4, your turn is over. Otherwise, the number
you roll is added to your score. This could be written with a while-loop as follows:
|
while ( dieRoll != 4 ) { score = score + dieRoll ; }
|
|
|