Академический Документы
Профессиональный Документы
Культура Документы
CS &141
output:
run:
Hello World!
BUILD SUCCESSFUL (total time: 0 seconds)
2.1.1.1
2.1.1.2
2.1.1.3
ECC
The first five lines are comments (Javadoc compliant with @ tags
for author and version)
public class HelloWorld declares a class (class heading) named
HelloWorld. Since the class name is used as the base name for
the file, the file name must be exactly the same as the class with
java extension, i.e., HelloWorld.java. The keyword public is an
access modifierit means that other classes anywhere have
access to HelloWorld. Other access modifiers include private,
protected, and default (none). Of the four, only public and default
are applicable to top-level classes (in other words, there is no such
thing as a private or protected top-levelnot innerclasses).
Furthermore, a file cannot contain more than one public top-level
class.
Class names begin with a capital letter (convention, not
requirement) and must be nonempty string of letters, digits and
underscores as long as they begin with a letter, underscore or $
and contain no blanks. Java is case sensitiveupper and lower
case letters differ. So HelloWorld Helloworld and System
system.
1
Niko ulevski
Lesson 2
CS &141
2.1.1.4
2.1.1.5
2.1.1.6
2.1.1.7
ECC
Niko ulevski
Lesson 2
CS &141
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #2a--TestFrame
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// An Example of old style Frame
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.awt.*;
public class TestFrame
//tests the frame class
{
public static void main (String args [ ])
{
Frame frame = new Frame ("Example #2");
frame.setSize(250,100); //250x100 pixels
frame.setVisible(true);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #2b--JTestFrame
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// An Example of alternate version using Swing and JFrame
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
public class JTestFrame
//tests the frame class
{
public static void main (String args [])
{
JFrame jframe = new JFrame("Example #2");
jframe.setSize(250,100); //250x100 pixels
jframe.setVisible(true);
}
}
2.1.3 Temperature
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #3--Temperature
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// This program gets input from the user, temperature
// in Fahrenheit, and displays temperature in Celsius
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.io.*;
//Llook in this library for definition of classes
//IOException, InputStreamReader, and BufferedReader
import java.text.*; //Needed for the DecimalFormat class
public class Temperature
// convert Fahrenheit to Centigrade
{
public static void main (String args [ ]) throws IOException
{
double temperature;
//Fahrenheit temperature, declaration
String name, text;
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader (reader);
ECC
Niko ulevski
Lesson 2
CS &141
System.out.print("Enter your name: "); //Prompt for name
name = input.readLine();
System.out.print("Hello, " + name + "!");
System.out.print("\nPlease type the temperature (deg F): ");
text = input.readLine();
//Get temperature in Fahrenheit
temperature = new Double(text).doubleValue();
System.out.print("\n" + temperature);
temperature = (5.0 * (temperature - 32.0)) / 9.0;
//String myString = NumberFormat.getInstance().format(temperature);
output:
run:
Enter your name: Niko Culevski
Hello, Niko Culevski!
Please type the temperature (deg F): 56
56.0 deg F is 13.33333 deg C
BUILD SUCCESSFUL (total time: 20 seconds)
output:
run:
Enter the radius of the circle: 5.6
The area of a circle of radius 5.6 is
98.52034561657591
BUILD SUCCESSFUL (total time: 15 seconds)
ECC
Niko ulevski
Lesson 2
CS &141
}
}
While the JOptionPane class may appear complex because of the large number of methods, almost all
uses of this class are one-line calls to one of the static showXxxDialog methods shown below:
showConfirmDialog Asks a confirming question, like yes/no/cancel.
showInputDialog Prompt for some input.
showMessageDialog Tell the user about something that has happened.
showOptionDialog The Grand Unification of the above three.
2.2 Simple Input and Output. Output for Java applications is straightforward; not
so for input, unfortunately, until the recent addition of the Scanner class. I/O is
handled with much more ease in applets.
ECC
Niko ulevski
Lesson 2
CS &141
ECC
Niko ulevski
Lesson 2
CS &141
output:
run:
Hello out there.
I will add two numbers for you.
Enter two whole numbers on a line:
45
-12
The sum of those two numbers is: 33
BUILD SUCCESSFUL (total time: 7 seconds)
2.3.1.2
Each variable has unique name which is designated when the variable is
declared, e.g., double temperature = 56.8d;.
ECC
Literal
Data Type
Size
(bits)
Min
Max
Init.
value
true
false
boolean
108
byte
'c'
char
16
-28700
short
16
-215 =
-32768
215
- 1 = 32767
178
int
32
-231 =
-2147483648
231
- 1 = 2147483647
8864L
long
64
-263
263 - 1 =
9223372036854775807
0L
87.363F
float
32
1.4E-45
3.4028235E38
0.0f
37.266
double
64
4.9E-324
1.7976931348623157E308
0.0D
false
-27 =
-128
27
- 1 = 127
0
\u0000
Niko ulevski
Lesson 2
CS &141
37.266D
26.77e3
2.3.1.3
2.3.2 Objects. An object is an instance of a class and may contain many variables.
OOP encapsulates data (attributes) and methods (behavior) into packages
called objects; the data and methods of an object are intimately tied together.
Objects have the property of information hiding.
2.3.2.1 Object may instantiate an unlimited number of classes.
2.3.2.2 Objects have references, instead of names, so they need not be unique.
2.3.2.3 An object is created by using the new operator to invoke a constructor,
and it dies when it has no references.
2.3.2.4 Java manipulates objects by reference, but it passes object references to
methods by value (copies of address).
ECC
Niko ulevski
Lesson 2
CS &141
2.3.2.5
* / %
+ << >> >>>
== !=
&
^
|
&&
||
?:
= += -= *=
/= %= &= ^=
|= <<= >>=
>>>=
ECC
Type
parentheses array subscript member
selection
unary postincrement unary postdecrement
unary preincrement unary predecrement
unary plus unary minus unary logical
negation unary bitwise complement unary
cast
multiplication division modulus
addition subtraction
bitwise left shift bitwise right shift
with sign extension bitwise right shift
with zero extension
relational less than relational less than
or equal to relational greater than
relational greater than or equal to type
comparison
relational is equal to relational is not
equal to
bitwise AND
bitwise exclusive OR boolean logical
exclusive OR
bitwise inclusive OR boolean logical
inclusive OR
logical AND
logical OR
ternary conditional
assignment addition assignment
subtraction assignment multiplication
assignment division assignment modulus
assignment bitwise AND assignment bitwise
exclusive OR assignment bitwise inclusive
OR assignment bitwise left shift
assignment bitwise right shift with sign
9
Associativity
left to right
right to left
right to left
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
left to right
right to left
right to left
Niko ulevski
Lesson 2
CS &141
extension assignment bitwise right shift
with zero extension assignment
10
Niko ulevski
Lesson 2
CS &141
// Niko Culevski
// Program to show values of primitive types
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class MaxVariablesDemo
{
public static void main(String args[])
{
// integers
byte largestByte =
short largestShort
int largestInteger
long largestLong =
Byte.MAX_VALUE;
= Short.MAX_VALUE;
= Integer.MAX_VALUE;
Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = 'S';
boolean aBoolean = true;
// display them all
System.out.println("The largest byte value is " + largestByte);
System.out.println("The largest short value is " + largestShort);
System.out.println("The largest integer value is " + largestInteger);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");
} else {
System.out.println("The character " + aChar + " is lower case.");
}
System.out.println("The value of aBoolean is " + aBoolean);
}
}
Output:
run:
The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.4028235E38
The largest double value is 1.7976931348623157E308
The character S is upper case.
The value of aBoolean is true
BUILD SUCCESSFUL (total time: 2 seconds)
11
Niko ulevski
Lesson 2
CS &141
Output:
run:
c = R
c = S
c = T
j = 127
j = 126
j = 127
j = -128
k = 32767
k = 32763
k = -32768
BUILD SUCCESSFUL (total time: 0 seconds)
12
Niko ulevski
Lesson 2
CS &141
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class Arithmetic
{
//member variables--class level variables
static float f;
static double d = -10.0/0;
//no error!
public static void main(String[] args)
{
//local variables
int m = 25, n = 7;
System.out.println("m = " + (++m));
System.out.println("n = " + (n--));
//access member variables from within a static method
//requires static declaration of the variables
System.out.println("f = " + f);
System.out.println("d = " + d);
int sum = m + n;
System.out.println("m + n = " + sum);
int difference = m - n;
System.out.println("m - n = " + difference);
int product = m * n;
System.out.println("m * n = " + product);
int quotient = m / n;
System.out.println("m / n = " + quotient);
int remainder = m % n;
System.out.println("m % n = " + remainder);
System.out.println(12345*234567/234567);
System.out.println(12345/234567*234567);
System.out.println(7.6 % 2.9);
System.out.println(-5 % 2);
//m = 26, n = 6
System.out.println(m >> 2);
System.out.println(n << 3);
System.out.println(-1 >>> 2);
System.out.println(Double.NaN == Math.sqrt(-1));
System.out.println(Double.NaN != Double.NaN);
System.out.println("4 | 3 = " + (4 | 3)); // 4 = 0100, 3 = 0011
System.out.println("4 & 3 = " + (4 & 3));
System.out.println("~4 = " + ~4);
//-5 = 11111111111111111111111111111011
}
}
Output:
run:
m = 26
n = 7
f = 0.0
d = -Infinity
m + n = 32
m - n = 20
m * n = 156
m / n = 4
m % n = 2
ECC
13
Niko ulevski
Lesson 2
CS &141
-5965
0
1.7999999999999998
-1
6
48
1073741823
false
true
4 | 3 = 7
4 & 3 = 0
~4 = -5
BUILD SUCCESSFUL (total time: 2 seconds)
2.4 Data Types and Expressions. Most of the material in this section was covered
already in section 2.3. Here are few additional comments.
2.4.1 Dividing two integers together yields an integer. Thus, 7/5 = 1.
2.4.2 The modulus operator, m % n, is the remainder when m is divided by n,
e.g., 11 % 7 = 4. A useful rule of thumb for dealing with modulo
calculations that involve negative numbers is this: simply drop any
negative signs from either operand and calculate the result. Then, if the
original left operand was negative, negate the result. The sign of the
right operand is irrelevant. Verify for yourself that 5 % -2 = -1.
2.4.3 Java does not give warning for integer overflow:
int x = 100000 * 100000;
System.out.println(x);
//Output: 1410065408
2.4.4 Numbers in scientific notation are expressed with the so-called enotation, e.g., 0.5e+002, 2.817939e-15.
2.4.5 Internal representation of real numbers cannot be exact. Consider,
double x = 1.0/5.0 + 1.0/5.0 +1.0/5.0 0.6;
//result should be 0
System.out.println(x); //Output: 1.1102230246251565E-16
14
Niko ulevski
Lesson 2
CS &141
2.5 Classes, Methods and Objects. A Java class is a specific category of objects.
It specifies the range of data that objects of that class can have. There are three
essential features that distinguish classes from types in Java:
classes can be defined by a programmer.
class objects can contain variables, including references to other objects.
classes can contain methods that give their objects the ability to act.
Here is an example of a Point class:
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #11Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to usage of a Point class
// Note that the Class Point should be saved in a
// separate file
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class Point
// Objects represent points in the Cartesian plane
{
// the points coordinates are hidden from outside
private double x, y;
public Point(double a, double b)
//constructor, invoked to initialize
{
x = a;
y = b;
}
public double xcoord()
{
return x;
}
+ y + ")");
ECC
15
Niko ulevski
Lesson 2
Point p = new Point(2,3);
CS &141
// instantiate a point object
Output:
run:
p.xcoord() = 2.0, p.ycoord() = 3.0
p = (2.0, 3.0)
q = (7.0, 4.0)
q does not equal p
q = (2.0, 3.0)
q equals p
BUILD SUCCESSFUL (total time: 2 seconds)
2.5.1 The String Class. A string is a sequence of characters. The String class
is a special, heavily used class in Java.
2.5.1.1 String objects can be created without the required new for other
objects, by writing string literalssequence of character within
double quotes.
2.5.1.2 Strings have the concatenation operator, + which converts
integers into strings for concatenating with a string.
2.5.1.3 String object suffer the restriction of being immutable; they
cannot be changed. Java provides the separate StringBuffer class
for string objects that need to be changed. Use this class instead!
2.5.1.4 Every String object has a unique integer value, called its hash
code and computed from the Unicode values of characters in the
string. For example, the hash value of the string
ABCDEFGHIJKLMNOPQRSTUVWXYZ is 218640813. This
number has no meaning other than serving as a numerical label
for the object. Hash values are used as storage locators when the
ECC
16
Niko ulevski
Lesson 2
CS &141
2.5.1.5
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #12String Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to demonstrate few methods of the String class
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class Alphabet
{
public static void main(String[] args)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//no new
System.out.println(alphabet);
System.out.println("This string contains " + alphabet.length()
+ " characters.");
System.out.println("The character at index 4 is "
+ alphabet.charAt(4));
//letter E, 4 letters before E
System.out.println("The index of the character Z is "
+ alphabet.indexOf('Z')); //number of characters that precede Z
System.out.println("The hash code for this string is "
+ alphabet.hashCode());
}
}
Output:
run:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
This string contains 26 characters.
The character at index 4 is E
The index of the character Z is 25
The hash code for this string is 218640813
BUILD SUCCESSFUL (total time: 2 seconds)
2.5.1.6
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #13String Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to demonstrate the substring() method
// of the String class
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class Substrings
ECC
17
Niko ulevski
Lesson 2
CS &141
{
public static void main(String args[])
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(alphabet);
System.out.println("The substring from index 4 to
+ alphabet.substring(4, 8));
System.out.println("The substring from index 4 to
+ alphabet.substring(4, 4));
//empty string
System.out.println("The substring from index 4 to
+ alphabet.substring(4, 5));
System.out.println("The substring from index 0 to
+ alphabet.substring(0, 8));
System.out.println("The substring from index 8 to
+ alphabet.substring(8));
}
index 8 is "
index 4 is "
index 5 is "
index 8 is "
the end is "
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
The substring from index 4
The substring from index 4
The substring from index 4
The substring from index 0
The substring from index 8
2.5.1.7
to
to
to
to
to
index 8
index 4
index 5
index 8
the end
is
is
is
is
is
EFGH
E
ABCDEFGH
IJKLMNOPQRSTUVWXYZ
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #14String Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to demonstrate the indexOf() method
// of the String class
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class SearchingForChars
{
public static void main(String args[ ])
{
String str = "This is the Mississippi River.";
System.out.println(str);
// display string
//one version of indexOf() method
int i = str.indexOf('s');
System.out.println("The first index of 's' is " + i);
//overloaded version of indexOf() method
int j = str.indexOf('s', i+1);
System.out.println("The next index of 's' is " + j);
int k = str.indexOf('s', j + 1);
System.out.println("The next index of 's' is " + k);
k = str.lastIndexOf('s');
System.out.println("The last index of 's' is " + k);
System.out.println(str.substring(k));
System.out.println(str.toLowerCase());
System.out.println(str.toUpperCase());
ECC
18
Niko ulevski
Lesson 2
CS &141
}
}
Output:
run:
This is the Mississippi River.
The first index of 's' is 3
The next index of 's' is 6
The next index of 's' is 14
The last index of 's' is 18
sippi River.
this is the mississippi river.
THIS IS THE MISSISSIPPI RIVER.
BUILD SUCCESSFUL (total time: 1 second)
2.5.1.8
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #15String Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to demonstrate converting Strings into
// primitive data types
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class TestConversions
{
public static void main(String args[])
{
String today = "April 18, 2009";
String todaysDayString = today.substring(6, 8);
int todaysDayInt = Integer.parseInt(todaysDayString);
int nextWeeksDayInt = todaysDayInt + 7;
String nextWeek = today.substring(0, 6) + nextWeeksDayInt
+ today.substring(8);
System.out.println("Today's date is " + today);
System.out.println("Today's day is " + todaysDayInt);
System.out.println("Next week's day is " + nextWeeksDayInt);
System.out.println("Next week's date is " + nextWeek);
}
}
Output:
run:
Today's date is April 18, 2009
Today's day is 18
Next week's day is 25
Next week's date is April 25, 2009
BUILD SUCCESSFUL (total time: 2 seconds)
2.5.1.9
ECC
Niko ulevski
Lesson 2
CS &141
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #15StringBuffer Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Program to demonstrate the StringBuffer class
// The StringBuffer is superior to the String class and
// should be used in lieu of the String class whenever possible
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public class TestAppending
{
public static void main(String[] args)
{
StringBuffer buf = new StringBuffer(10);
buf.append("It was");
System.out.println("buf = " + buf);
System.out.println("buf.length() = " + buf.length());
System.out.println("buf.capacity() = " + buf.capacity());
buf.append(" the best");
System.out.println("buf = " + buf);
System.out.println("buf.length() = " + buf.length());
System.out.println("buf.capacity() = " + buf.capacity());
buf.append(" of times.");
System.out.println("buf = " + buf);
System.out.println("buf.length() = " + buf.length());
System.out.println("buf.capacity() = " + buf.capacity());
}
}
Output:
run:
buf = It was
buf.length() = 6
buf.capacity() = 10
buf = It was the best
buf.length() = 15
buf.capacity() = 22
buf = It was the best of times.
buf.length() = 25
buf.capacity() = 46
BUILD SUCCESSFUL (total time: 2 seconds)
20
Niko ulevski
Lesson 2
CS &141
or object.variable.
2.5.4 Prototypes.
2.6 Memory Concepts. Variable names, such as temperature, cent, and sum correspond to
computers memory location. Each variable has a name, a type, and a value. Java is
strongly-types, so mixing of types has to follow strict type conversion (casting) rules.
2.6.1 For example, when the statement
number1 = Integer.parseInt(firstNumber);
executes, firstNumber is converted to integer before storing it in
memory.
2.6.2 When the statement sum = sum + number1; is executed, sums previous
value is added with number1 and the result of that addition replaces the
variable sum.
2.7 Program Layout.
2.7.1 Use Javadoc headings (as comments) for each class an method,
describing its functionality, pre and post conditions, author, version,
parameters, and types).
2.7.2 Indent and make the code readable: strive for clarity and simplicity.
2.7.3 Watch your braces and semicolons!
2.7.4 Comment as you write the code and more than you think is necessary.
2.8 Debugging.
2.8.1 Syntax errorserrors due to grammatical misuse of the language rules.
2.8.2 Run-time errorsthe program compiles but it attempts to perform some
illegal operation (division by zero).
2.8.3 Logic errorsthe program compiles and runs but produces incorrect
results.
2.9 Decision Making: Equality and Relational Operators. The selection (if) statement
is treated fully in Chapter 4here it is introduced briefly in context with relational
operators.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Example #16 JOptionPane Class Example
// CS 151, 6 Apr 2009
// ECC, Spring 2009
// Niko Culevski
// Using if statements, relational operators,
// and equality operators
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import javax.swing.JOptionPane;
public class Comparison
{
ECC
21
Niko ulevski
Lesson 2
CS &141
Output:
ECC
22
Niko ulevski
Lesson 2
ECC
CS &141
23
Niko ulevski