Download Topic 1 – Fundamental Java Structures

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Topic 2 –
Fundamental Java Structures
CISC370/Object Oriented
Programming with Java
When faced with a decision, I always ask “what would be the most fun?”
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Use and Distribution Notice
Possession of any of these files implies understanding and
agreement to this policy.
The slides are provided for the use of students enrolled in Jeff
Six's Object Oriented Programming with Java class (CISC 370) at
the University of Delaware. They are the creation of Mr. Six and
he reserves all rights as to the slides. These slides are not to be
modified or redistributed in any way. All of these slides may only
be used by students for the purpose of reviewing the material
covered in lecture. Any other use, including but not limited to, the
modification of any slides or the sale of any slides or material, in
whole or in part, is expressly prohibited.
Most of the material in these slides, including the examples, is
derived from multiple textbooks. Credit is hereby given to the
authors of these textbook for much of the content. This content
is used here for the purpose of presenting this material in CISC
370, which uses, or has used, these textbooks.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A Quick Introduction to Some
Important and Varied Topics
Before we examine Java from the
bottom-up, beginning with OOP and the
specifics of classes, methods, and so
forth, we will look at some fundamental
structures in Java.
This includes datatypes, some
important classes from the Java class
library, output routines, and so forth.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
Let’s take a look at a very simple Java
program:
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
}
}
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
}
}
Everything in Java lives inside a class.
Here, we create a class called ‘Hello’. The
public keyword is an access modifier; this
controls what other parts of this program can
control or use the code inside this class.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
}
}
Following the ‘class’ keyword is the name of
this class, in this case, ‘Hello’.
Then, everything inside the parens, ‘{’ and ‘}’
is part of the ‘Hello’ class.
Thus, this code defines a class ‘Hello’ that has
‘public’ access control.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
}
}
Inside this class, we have one method. (A
function is called a method in Java.)
The one method is a ‘public static’ method.
For now, just believe that the ‘main’ method
needs to be ‘public static’.
This function is ‘void’; it returns no data.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
}
}
This method has one line of code.
Here, we use the System.out object and
call its println method. This call is
made using same syntax as C++.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
A First Java Program
System.out.println(“Hello”);
This function takes one parameter, a
string. After displaying the string on
the console, it terminates the line.
Note that the System.out object also
has a print() method that does not
terminate the line.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Comments
/* A very simple Java program */
public class Hello
{
public static void main(String[] arguments)
{
System.out.println(“Hello”);
// now, we’re done
}
}
Comments in Java follow the same form as
C++, with anything between /* and */
treated as a comment and anything following
// on a line treated as a comment.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Data Types
Java is a strongly typed language. This
means that every variable must be a
declared type. There are eight primitive
datatypes in Java:




int – 4 bytes
(-2,147,483,648 -> 2,147,483,647)
short – 2 bytes (-32,768 -> 32,767)
long – 8 bytes (really big integers)
byte – 1 byte (-128 -> 127)
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Data Types




float – 4 bytes (floating point)
double – 8 bytes (floating point)
char – 2 bytes (Unicode representation)
boolean – false or true
Variables are declared and initialized in the
same manner as C and C++, e.g.




int x;
double y = 3.14;
char q = ‘p’;
boolean isValid = false;
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Constants
In Java, to define a constant, the
datatype of a variable is preceded with
the keyword final. For example,
public class TestClass1
{
public static void main(String args[])
{
final double CM_PER_INCH = 2.540;
double width = 8.5;
double length = 11;
. . .
}
}
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Constants
final double CM_PER_INCH = 2.540;
Once this declaration appears, the
variable CM_PER_INCH can be read and
used, however, it cannot be assigned a
new value. It can never change from
2.540.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Class Constants
Sometimes, a constant should be
accessible by multiple methods inside a
class, this is done with static final, e.g.
public class TestClass2
{
public static final double CM_PER_IN = 2.540;
public static void main(String args[])
{
. . .
}
public static void other_stuff(int x)
{
. . .
}
}
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Operators
Java also has most of the same operators
as C and C++:




+, -, *, /, % (add, subtract, multiple, divide,
modulus)
++ and -- (increment and decrement)
&, |, ^, ~ (bitwise AND, OR, XOR, NOT)
==, !=, <, >, <=, >= (relational operators,
evaluate to a boolean value)
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Mathematical Functions
and Constants
The Math class (included in the Java class
libraries in the JDK) includes a number of
mathematical functions (methods) and
related constants (final values):



double y = Math.pow(x, a);
double z = Math.sin(y);
double d = Math.exp(4.59) *
Math.PI
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Strings
Java makes strings very easy, compared to C,
C++, and many other languages.
The Java class libraries include a predefined
‘String’ class.
For example,
String empty_string = “”;
String nice_greeting = “Hello there.”;
String bad_greeting = “What do you want?”;
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
String Concatenation
Concatenation of strings is very easy, it
makes use of the ‘+’ operator.
String
String
String
String
nice_greeting = “Hello”;
first_name = “Jeffrey”;
last_name = “Six”;
blank_space = “ ”;
String greeting = nice_greeting + blank_space +
first_name + blank_space + last_name;
System.out.println(greeting);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
String Concatenation
If a string is concatenated with
something that is not a string, that
other datatype is converted to a string.
For example,
int total_points = 110;
int earned_points = 87;
float test_score = earned_points / total_points;
System.out.println(“Mr. Six’s score was” +
test_score);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Strings
Notice that the size of the string is not
specified when it is declared (this
determination happens automatically –
told you this was easy).
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Substrings
The String class also has a substring
method to extract part of a string.
This is a method of the String class and takes
two parameters, the index into the string to
start copying from and the index into the string
of the first character you do not want to copy.
Notice that the second parameter is not a
length or number of characters to be
extracted. It is a simple index.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Substrings
For example,
String sentence = “The quick brown fox is nice.”;
String s;
s = sentence.substring(4, 15);
System.out.println(s);
This causes “quick brown” to be
displayed to the console.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
String Equality Testing
To test if two strings are “equal”:
String string1 = “Hello”;
String string2 = “hello”;
boolean test;
test = string1.equals(string2);
The String class has an equals method
which returns a boolean, true if the strings
are equal, false if the strings are not equal.
Here, test is set to false after the call to the
equals method.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
String Equality Testing
The String class also offers an
equalsIgnoreCase method, which
tests for equality, ignoring case:
String string1 = “Hello”;
String string2 = “hello”;
boolean test;
test = string1.equalsIgnoreCase(string2);
Here, test is set to true after the call to
the equalsIgnoreCase method.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Strings as Characters
As in C++, a string is a collection of
characters. Thus, the String class offers some
methods to handle strings as characters. For
example, what would character1 and character
2 be set to in this code fragment?
String testString1;
testString1 = “This is a test.”;
char character1;
char character2 = testString1.charAt(3);
character1 = testString1.charAt(2);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Other String Manipulations
The methods we have just seen are a small
subset of the over 50 methods provided as
part of the String class.
There are methods to find the first (or last)
index of a certain character in a string, to find
the length of a string, to convert a string to
all lower (or upper) case, and many more.
All of these methods are described in the
online Java API/class library documentation.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Java API Documentation
This leads to an important topic…the Java API
/ class library documentation.
Sun provides a complete set of
documentation on every class included with
the JDK, and on every method and variable
contained within each class.
This is provided online, at:
http://java.sun.com/j2se/1.4.2/docs/
api/index.html

This URL is valid as of 23 August 2003 and links to
the documentation for Java 2 Standard Edition,
version 1.4.2.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow –
Conditional Statements
Java supports the if statement for
conditional execution:
if (purchaseAmount < availableCredit)
{
availableCredit = availableCredit –
purchaseAmount;
System.out.println(“Approved”);
}
else
System.out.println(“Denied”);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow –
Conditional Statements
Java supports the switch statement for
conditional execution…same form as C and
C++:
int x = 3;
switch(x) {
case (1) :
System.out.println(“It’s a 1.”);
break;
case (2) :
System.out.println(“It’s a 2.”);
break;
default:
System.out.println(“Not a 1 or 2.”);
}
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow – while Loops
Java supports the while statement for
loops, based on some condition:
counter = 0;
while (counter < 10)
{
System.out.println(counter);
counter++;
}
System.out.println(“Done.”);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow – do/while Loops
Java supports the do/while statement
for loops, based on some condition that
need to run at least once:
counter = 0;
do {
System.out.println(counter);
counter++;
} while (counter < 10);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow – for Loops
Java supports the for statement for
loops that have a determinate nature
(we know in advance how many times
the loop should run):
for (int count=10; count >= 1; count--)
{
System.out.println(“Counting down . . “ + count);
}
System.out.println(“Blastoff!”);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Control Flow – foreach Loops
Java 1.5 introduces the foreach loop, which
Sun calls the enhanced for loop.
This is a special form of the for loop that is
used to iterate over all elements in an array
in a simple, easy-to-read form…
int[] a;
int result = 0;
. . .
for (int i : a)
{
result += i;
}
This syntax is read as
“for each int element i in the
array a.” The loop body
is visited once for each possible
value of i.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Arrays
Java supports arrays.
To declare an array of integers:
int[] array_of_ints;
This declaration makes only a variable
named array_of_ints; it does not yet
initialize an array (or allocate memory
for the elements). To do so:
int[] array_of_ints = new int[100];
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Array Lengths
To find the number of elements in an
array, the length field can be used:
for (int a = 0; a < array_of_ints.length; a++)
{
array_of_ints[a] = 6;
}
for (int a = 0; a < array_of_ints.length; a++)
{
System.out.println(array_of_ints[a]);
}
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Array Overstepping
(or lack thereof)
In Java, it is not possible to overstep the
bounds of an array. Any attempt to do so will
result in program termination and the error
message “Array index out of bounds” message.
(This is really an exception…more about that
later).
For instance, in the previous array_of_ints, any
attempt to access array_of_ints[100] would
cause an exception/error to occur and the JVM
(and thus your program) to terminate.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Array Initialization
It is also possible to initialize an array at
its declaration:
int [] fibNumbs = {1, 1, 2, 3, 5, 8, 11};
Note that we do not use the new
keyword when allocating and initializing
an array in this manner.
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Array Copying
It is possible to copy one array variable
into another, but then both variables
refer to the same array (just like
manipulating pointers in C++).
int [] fibNumbs = {1, 1, 2, 3, 5, 8, 11};
int [] otherFibNumbs;
otherFibNumbs = fibNumbs;
otherFibNumbs[2] = 99;
Here, fibNumbs[2] and
otherFibNumbs[2] are both
equal to 99.
System.out.println(otherFibNumbs[2]);
System.out.println(fibNumbs[2]);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Array Copying
The copying of an array (element-byelement) can be done using the
arraycopy method in the System class:
System.arraycopy(from, fromIndex, to, toIndex, count);
For example:
int []
int []
Here, fibNumbs[2] is equal to
2 and otherFibNumbs[2] is
fibNumbs = {1, 1, 2, 3, 5, 8, 11};
equal to 99.
otherFibNumbs = new int[7];
System.arraycopy(fibNumbs,0,otherFibNumbs,0,7);
otherFibNumbs[2] = 99;
System.out.println(otherFibNumbs[2]);
System.out.println(fibNumbs[2]);
CISC370 – Object Oriented Programming with Java / © 2003 J. Six
Arrays in Java
versus Arrays in C++
This copying complication shows that
arrays in Java are quite different then
arrays in C or C++. For example,
int[] array_of_ints = new int[100]; // Java
is not the same as:
int array_of_ints[100];
// C++
but is the same as:
int * array_of_ints = new int[100]
// C++
The array variable is the same as a
pointer that points to the beginning of an
array in C++.