Data Types and Operations
- Review
- Primitive Data Types and Operations
- naming conventions
- Class names - mixed case, first letter should be capitalized,
e.g.
SalariedEmployees
- Methods and Attributes (instance variables) - mixed case,
first
letter should be lower case, e.g. hourlyWage
- Local variables - all lower case
- Constants - all capitals
- The first character of each name must be a letter, an
underscore, or a $. The other
characters
may be letters, numbers, $, and the under_score character. Names cannot
be
the
same as JAVA keywords (e.g. new, if, class, public).
- types
- char - 16 bit unicode character
- byte - 1 byte (-128 to 127)
- short - 2 bytes (-32768 to 32767)
- int - 4 bytes (-2,147,483,648 to 2,147,483,647)
- long - 8 bytes (-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)
- float - 4 bytes (7 digits of precision +- 3.4E-38
to
+- 3.4E+38)
- double - 8 bytes (15 digits of precision +-
1.7E-308
to +- 1.7E+308)
- boolean - may hold the value true or false
- String - defines as a standard string object that
can
be assigned variable length strings, e.g "Barney Fife" (note the "S" in
string
is capitalized since it is an object, not a primative type).
- literals
- 1, 10000L, 1.0, 3.0F, 0123, 0xFFFA,
1.23E2,
"cat", 'c', '\n', '\uFFF4', \', \",true, false,null
- operations
- mathematical opertors
- +, -, *, /, ++x, x++, --x, x--, %
- integer round off error! 5/9 results in 0
- shortcut operators, -= , +=, /=, *=, %=
- comparison operators for numbers
- boolean operators
- ! (not), || (or), && (and), ^ (exclusive or)
- operator precedence, see
page 98. Use ( ) to clarify your equations.
- don't worry about, bitwise and unconditional operators
- beware of integer round off!, example 7 / 9 is 0
- the + is used to concatenate strings. Any number
contatenated
to a string is automatically converted. Beware of order of operations,
since
addition is done left to right, s2 and s3 below will have different
results!
E.g.
int n = 1, x = 2;
String s1 = "The value of n = "+n; // yields a String "The
value
of n = 1"
String s2 = "The value of n + x = "+x+y; // yields a
String
"The value of n + x = 12"
String s3 = "The value of n + x = "+(x+y); // yields
a
String "The value of n + x = 3"
- Some basic rules for assignment statements
- Java will allow you to store a variable of one type in a
variable
of another type so long as there is not a loss of precision or a
possibility
of overflow. Therefore:
- You can :
- store ints in longs, floats in doubles, ints in double
- You can't :
- store floats or doubles in ints
- store floats or doubles in longs
- Somtimes you will need to break a rule and force Java to
store
a double in an int, so long as you know the value of the variable won't
get
too big AND you don't mind losing all the decimal places, then you can
do
this with "casting". To cast a piece of data of one type to another,
simply
add a the new data type in a set of parenthesis E.g.
int x;
double d = 44.2;
x = (int)d; //
placing
(int) before the d tells Java you think you know what you're doing
- If you divide an integer by 0, then you will get an
ArithematicException
(program abort) with a divide by zero error
- If you divide a float or double by 0, then you get a special
value
of "infinity".
- Numbers stored as Strings (text) must be converted to ints or
doubles
before being used in an equation. See Double.parseDouble and
Integer.parseInt
below.
- If you divide one integer by another, then the decimal part is
lost,
even if the result is to be stored in a double, e.g.
double d =
5/6;
// result is 0.
Examples:
/*
* declare 3 integers and use them in a simple equation
*/
int x = 4; // declare x as a 32 bit integer and
initialize
it to 4
int y = 100; // declare y as a 32 bit integer and
initialize
to 100
int a, b, c; // declare a, b, and c
b = 2*y;
c = (int)Math.sqrt(x); // c is now the squareroot
of x
a = (x+y)/c + b;
a += (int)Math.pow(b,2); // set a to
itself
plus
b squared
c = a % 2; // c is 0 if a is odd, 1 if a is
even
/*
* some string examples
*/
String s1 = "Cat";
String s2 = "rat", s3 = "hampster";
String s4;
s4 = s1 + " ate the " + s3; // concatenates
all
three strings "Cat ate the hampster"
s4 = s2 + 44; // converts 44 to a string and
appends
it to s2, s4 is now "rat44"
s4 = ""+ x; // quick way to convert a number to a
string,
just add it to an empty string
Math class
- the math class contains a set of mathematical functions for
operations
more advanced than simple addition, subtraction, multiplication, and
division. most methods give a double back.
- Examples:
- Math.sqrt( a) // takes the square root of a
- Math.pow(a, b) // raises a to the b power
- Math.max(a,b) // returns the greater of a and b
- Math.min(a,b) // returns the smaller of a and b
- Math.abs(a) // returns the absolute value of a
- other functions exist for taking random numbers, sin, cosine,
tangent,
etc.
Integer.parseInt
public static int parseInt(String s)
throws NumberFormatException
- Parses the string argument as a signed decimal integer. The
characters
in the string must all be decimal digits, except that the first
character
may be an ASCII minus sign
'-'
('\u002D'
) to
indicate a negative value. The resulting integer value is returned.
Note, leading and
trailing spaces cause problems
-
- Parameters:
s
- a String
containing the int
representation to be parsed
- Returns:
- the integer value represented by the argument in decimal.
example:
int i = Integer.parseInt("33"); // convert the string "33" into
the
number 33
Double.parseDouble
public static double parseDouble(String s)
throws NumberFormatException
- Parses the string argument as a signed decimal integer. The
characters
in the string must all be decimal digits, except that the first
character
may be an ASCII minus sign
'-'
('\u002D'
) to
indicate a negative value. The resulting integer value is returned.
Note, leading and
trailing spaces cause problems
-
- Parameters:
s
- a String
containing the double
representation to be parsed
- Returns:
- the double value represented by the argument in decimal.
example:
double d = Double.parseDouble("33.44"); // convert the string
"33.44"
into the number 33.44
Some components:
- JButton - a click on button
- properties to set
- text - text to be placed on the button
- tool tip text - text that is shown to use when mouse is over
the component
- optionally
- font
- background - color of the button
- foreground - color of the button text
- mnemonic - a character (one that occurs in the text of the
button) that is used to click the button by using the alt key.
- JLabel - to show text on the screen. this text cannot be
changed by the user
- properties to set
- text - text in the label, (note, if you want the label
to be initially blank, put a couple of spaces in it. This will force a
Flowlayout manager to allocate space for it).
- horizontal alignment - how the text is placed horizontally in
the JLabel area (if the area is wider than needed for the text).
- vertical alignment - how the text is vertically aligned in
the JLabel area (if the area is higher than one line of text).
- optionally
- font
- background - color of the button
- foreground - color of the button text
- vertical alignment
- JTextField - to create an area where the user can type in
one line of text.
- properties to set
- text - initial text, (note, if you want the field to be
initially blank, put a couple of spaces in it. This will force a
Flowlayout manager to allocate space for it).
- columns - set it to the number of characters that you want
the user to be able to type in (width of the field in characters)
- horizontal alignment - how the text is placed horizontally in
the JLabel area (if the area is wider than needed for the text).
- vertical alignment - how the text is vertically aligned in
the JLabel area (if the area is higher than one line of text).
- tool-tip-text - text telling user what's expected, or the
format of what's expected.
- editable - true or false, if false, then the user cannot
change the text.
- optionally
- font
- background - color of the button
- foreground - color of the button text
- To retrieve text from a JTextField use the getText() method. getText
always returns a String, example:
String
input
= textField.getText();
- To retrieve text from a JTextField and convert to an integer,
use
getText() and Integer.parseInt() together,
String input = textField.getText(); //
get
the text entered by the user
// and store in variable input
int number = 0;
try{
number = Integer.parseInt(input); // convert text in input
into an
// integer stored in number.
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Invalid data entry");
}
- To retrieve text from a JTextField and convert to a double, use
getText()
and Double.parseDouble together,
String input = textField.getText(); //
get
the text entered by the user
// and store in variable input
double value = 0;
try{
value = Double.parseDouble(input); // convert text
in input into
// an double stored in value.
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,"Invalid data entry");
}
- To put text in a JTextField, use the setText(string) method,
setText
expects to be given a string. example:
double
pi
= 3.14;
textField.setText(""+pi);